commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
152a782cc3dcbec3c015c5046da112d9762a53c1
PhotoOrganizer/Program.cs
PhotoOrganizer/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using CommandLine.Text; namespace PhotoOrganizer { class Program { static void Main(string[] args) { var opts = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, opts)) { Console.WriteLine(HelpText.AutoBuild(opts)); return; } if (string.IsNullOrEmpty(opts.SourceFolder)) opts.SourceFolder = System.Environment.CurrentDirectory; DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder); if (!destination.Exists) { Console.WriteLine("Error: Destination folder doesn't exist."); return; } DirectoryInfo source = new DirectoryInfo(opts.SourceFolder); if (!source.Exists) { Console.WriteLine("Error: Source folder doesn't exist. Nothing to do."); return; } FileOrganizer organizer = new FileOrganizer(destination, opts); organizer.ProcessSourceFolder(source); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using CommandLine.Text; namespace PhotoOrganizer { class Program { static void Main(string[] args) { var opts = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, opts)) { Console.WriteLine(HelpText.AutoBuild(opts)); return; } if (string.IsNullOrEmpty(opts.SourceFolder)) opts.SourceFolder = System.Environment.CurrentDirectory; DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder); if (!destination.Exists) { Console.WriteLine("Error: Destination folder doesn't exist."); return; } DirectoryInfo source = new DirectoryInfo(opts.SourceFolder); if (!source.Exists) { Console.WriteLine("Error: Source folder doesn't exist. Nothing to do."); return; } if (opts.DeleteSourceOnExistingFile) { Console.Write("Delete source files on existing files in destination is enabled.\nTHIS MAY CAUSE DATA LOSS, are you sure? [Y/N]: "); var key = Console.ReadKey(); if (!(key.KeyChar == 'y' || key.KeyChar == 'Y')) return; Console.WriteLine(); } FileOrganizer organizer = new FileOrganizer(destination, opts); organizer.ProcessSourceFolder(source); } } }
Add warning on delete from source
Add warning on delete from source
C#
mit
rgregg/photo-organizer
5871b9af2368a2473a8e8c6620cbeb95682ef01c
src/Orchard.Web/Program.cs
src/Orchard.Web/Program.cs
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Start(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }
Revert "make command line host non blocking"
Revert "make command line host non blocking" This reverts commit ac8634448e72602545e0c886403ab185b89d75d6. It prevented the web process to be started
C#
bsd-3-clause
xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,alexbocharov/Orchard2,lukaskabrt/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,jtkech/Orchard2,alexbocharov/Orchard2,yiji/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,yiji/Orchard2,lukaskabrt/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,jtkech/Orchard2,OrchardCMS/Brochard,lukaskabrt/Orchard2,petedavis/Orchard2,jtkech/Orchard2,alexbocharov/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,yiji/Orchard2
15d33d4a03eab711d3312719af12d63198da94dd
sample-app/CafeTests/AddingEventHandlers.cs
sample-app/CafeTests/AddingEventHandlers.cs
using Cafe.Tab; using Edument.CQRS; using Events.Cafe; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebFrontend; namespace CafeTests { [TestFixture] public class AddingEventHandlers { [Test] public void ShouldAddEventHandlers() { // Arrange Guid testId = Guid.NewGuid(); var command = new OpenTab() { Id = testId, TableNumber = 5, Waiter = "Bob" }; var expectedEvent = new TabOpened() { Id = testId, TableNumber = 5, Waiter = "Bob" }; ISubscribeTo<TabOpened> handler = new EventHandler(); // Act Domain.Setup(); Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler); Domain.Dispatcher.SendCommand(command); // Assert Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id); } public class EventHandler : ISubscribeTo<TabOpened> { public TabOpened Actual { get; private set; } public void Handle(TabOpened e) { Actual = e; } } } }
using Cafe.Tab; using Edument.CQRS; using Events.Cafe; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebFrontend; namespace CafeTests { [TestFixture] public class AddingEventHandlers { private static void Arrange(out OpenTab command, out TabOpened expectedEvent, out ISubscribeTo<TabOpened> handler) { // Arrange Guid testId = Guid.NewGuid(); command = new OpenTab() { Id = testId, TableNumber = 5, Waiter = "Bob" }; expectedEvent = new TabOpened() { Id = testId, TableNumber = 5, Waiter = "Bob" }; handler = new EventHandler(); } [Test] public void ShouldAddEventHandlers() { ISubscribeTo<TabOpened> handler; OpenTab command; TabOpened expectedEvent; Arrange(out command, out expectedEvent, out handler); // Act Domain.Setup(); Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler); Domain.Dispatcher.SendCommand(command); // Assert Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id); } public class EventHandler : ISubscribeTo<TabOpened> { public TabOpened Actual { get; private set; } public void Handle(TabOpened e) { Actual = e; } } } }
Refactor the arrange part of the test
Refactor the arrange part of the test
C#
bsd-3-clause
GoodSoil/cqrs-starter-kit,GoodSoil/cqrs-starter-kit
9f353507afdafb767241f50e6b4b5d3bc5055090
test/test-library/EnvironmentTests.cs
test/test-library/EnvironmentTests.cs
using Xunit; using Squirrel; using Squirrel.Nodes; namespace Tests { public class EnvironmentTests { private static readonly string TestVariableName = "x"; private static readonly INode TestVariableValue = new IntegerNode(1); [Fact] public void TestGetValueFromCurrentEnvironment() { var environment = new Environment(); environment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, environment.Get(TestVariableName)); } [Fact] public void TestGetValueFromParentEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); parentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestGetValueFromGrandparentEnvironment() { var grandparentEnvironment = new Environment(); var parentEnvironment = new Environment(grandparentEnvironment); var childEnvironment = new Environment(parentEnvironment); grandparentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } } }
using Xunit; using Squirrel; using Squirrel.Nodes; namespace Tests { public class EnvironmentTests { private static readonly string TestVariableName = "x"; private static readonly INode TestVariableValue = new IntegerNode(1); [Fact] public void TestCanGetValueFromCurrentEnvironment() { var environment = new Environment(); environment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, environment.Get(TestVariableName)); } [Fact] public void TestCanGetValueFromParentEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); parentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestCanGetValueFromGrandparentEnvironment() { var grandparentEnvironment = new Environment(); var parentEnvironment = new Environment(grandparentEnvironment); var childEnvironment = new Environment(parentEnvironment); grandparentEnvironment.Put(TestVariableName, TestVariableValue); Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName)); } [Fact] public void TestCannotGetValueFromChildEnvironment() { var parentEnvironment = new Environment(); var childEnvironment = new Environment(parentEnvironment); childEnvironment.Put(TestVariableName, TestVariableValue); Assert.NotEqual(TestVariableValue, parentEnvironment.Get(TestVariableName)); } } }
Create negative test for getting values from nested environments
Create negative test for getting values from nested environments
C#
mit
escamilla/squirrel
5a2c8b29151d186570f36323835c8c0c2618fec2
src/ChessVariantsTraining/Models/Variant960/Clock.cs
src/ChessVariantsTraining/Models/Variant960/Clock.cs
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Start(); } public void Pause() { stopwatch.Stop(); stopwatch.Reset(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
using MongoDB.Bson.Serialization.Attributes; using System.Diagnostics; namespace ChessVariantsTraining.Models.Variant960 { public class Clock { Stopwatch stopwatch; [BsonElement("secondsLeftAfterLatestMove")] public double SecondsLeftAfterLatestMove { get; set; } [BsonElement("increment")] public int Increment { get; set; } public Clock() { stopwatch = new Stopwatch(); } public Clock(TimeControl tc) : this() { Increment = tc.Increment; SecondsLeftAfterLatestMove = tc.InitialSeconds; } public void Start() { stopwatch.Reset(); stopwatch.Start(); } public void Pause() { stopwatch.Stop(); } public void AddIncrement() { SecondsLeftAfterLatestMove += Increment; } public void MoveMade() { Pause(); AddIncrement(); SecondsLeftAfterLatestMove = GetSecondsLeft(); } public double GetSecondsLeft() { return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds; } } }
Reset stopwatch on Start instead of Pause
Reset stopwatch on Start instead of Pause
C#
agpl-3.0
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
fbf3c0130bc9776f30e1044222e47a4b568f17b0
NBi.genbiL/Parser/Action.cs
NBi.genbiL/Parser/Action.cs
using NBi.GenbiL.Action; using Sprache; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.GenbiL.Parser { class Action { public readonly static Parser<IAction> Parser = ( from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser))) from terminator in Grammar.Terminator.AtLeastOnce() select sentence ); } }
using NBi.GenbiL.Action; using Sprache; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.GenbiL.Parser { class Action { public readonly static Parser<IAction> Parser = ( from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser.Or(Variable.Parser)))) from terminator in Grammar.Terminator.AtLeastOnce() select sentence ); } }
Add VariableParser to the main parser
Add VariableParser to the main parser
C#
apache-2.0
Seddryck/NBi,Seddryck/NBi
115e08d0c86a2620ac86ab6e4e48940f0a85b904
Wox.Infrastructure/Http/HttpRequest.cs
Wox.Infrastructure/Http/HttpRequest.cs
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF-8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
Fix a http request issues.
Fix a http request issues.
C#
mit
Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,lances101/Wox,Wox-launcher/Wox,lances101/Wox
489014e018183b1c6a0c1a82dd6b87fa6a5d7542
NBi.Core/Batch/SqlServer/BatchRunCommand.cs
NBi.Core/Batch/SqlServer/BatchRunCommand.cs
using Microsoft.SqlServer.Management.Smo; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Batch.SqlServer { class BatchRunCommand : IDecorationCommandImplementation { private readonly string connectionString; private readonly string fullPath; public BatchRunCommand(IBatchRunCommand command, SqlConnection connection) { this.connectionString = connection.ConnectionString; this.fullPath = command.FullPath; } public void Execute() { if (!File.Exists(fullPath)) throw new ExternalDependencyNotFoundException(fullPath); var script = File.ReadAllText(fullPath); var server = new Server(); server.ConnectionContext.ConnectionString = connectionString; server.ConnectionContext.ExecuteNonQuery(script); } } }
using Microsoft.SqlServer.Management.Smo; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Batch.SqlServer { class BatchRunCommand : IDecorationCommandImplementation { private readonly string connectionString; private readonly string fullPath; public BatchRunCommand(IBatchRunCommand command, SqlConnection connection) { this.connectionString = connection.ConnectionString; this.fullPath = command.FullPath; } public void Execute() { if (!File.Exists(fullPath)) throw new ExternalDependencyNotFoundException(fullPath); var script = File.ReadAllText(fullPath); Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, script); var server = new Server(); server.ConnectionContext.ConnectionString = connectionString; server.ConnectionContext.ExecuteNonQuery(script); } } }
Add trace to check effective bug
Add trace to check effective bug
C#
apache-2.0
Seddryck/NBi,Seddryck/NBi
f6303a28558cba4a0eee8b4b5695d18789d4e4f4
osu.Game/Screens/BlurrableBackgroundScreen.cs
osu.Game/Screens/BlurrableBackgroundScreen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Transforms; using osu.Game.Graphics.Backgrounds; using osuTK; namespace osu.Game.Screens { public abstract class BlurrableBackgroundScreen : BackgroundScreen { protected Background Background; protected Vector2 BlurTarget; public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None) => Background?.BlurTo(BlurTarget = sigma, duration, easing); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Transforms; using osu.Game.Graphics.Backgrounds; using osuTK; namespace osu.Game.Screens { public abstract class BlurrableBackgroundScreen : BackgroundScreen { protected Background Background; protected Vector2 BlurTarget; public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None) { BlurTarget = sigma; return Background?.BlurTo(BlurTarget, duration, easing); } } }
Fix songselect blur potentially never being applied
Fix songselect blur potentially never being applied
C#
mit
2yangk23/osu,peppy/osu,UselessToucan/osu,ppy/osu,naoey/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,ppy/osu,peppy/osu-new,ZLima12/osu,NeoAdonis/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,ZLima12/osu,smoogipooo/osu,DrabWeb/osu,DrabWeb/osu,naoey/osu,2yangk23/osu
f2aa695836cbf98827b64dc290ac9b14cda90c4a
src/DbLocalizationProvider/DataAnnotations/ModelMetadataLocalizationHelper.cs
src/DbLocalizationProvider/DataAnnotations/ModelMetadataLocalizationHelper.cs
using System; using DbLocalizationProvider.Internal; namespace DbLocalizationProvider.DataAnnotations { internal class ModelMetadataLocalizationHelper { internal static string GetTranslation(string resourceKey) { var result = resourceKey; if(!ConfigurationContext.Current.EnableLocalization()) { return result; } var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey); result = localizedDisplayName; if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode()) return result; // for the legacy purposes - we need to look for this resource value as resource translation // once again - this will make sure that existing XPath resources are still working if(localizedDisplayName.StartsWith("/")) { result = LocalizationProvider.Current.GetString(localizedDisplayName); } //If other data annotations exists execept for [Display], an exception is thrown when displayname is "" //It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty if (string.IsNullOrWhiteSpace(localizedDisplayName)) { return null; } return result; } internal static string GetTranslation(Type containerType, string propertyName) { var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName); return GetTranslation(resourceKey); } } }
using System; using DbLocalizationProvider.Internal; namespace DbLocalizationProvider.DataAnnotations { internal class ModelMetadataLocalizationHelper { internal static string GetTranslation(string resourceKey) { var result = resourceKey; if(!ConfigurationContext.Current.EnableLocalization()) return result; var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey); result = localizedDisplayName; if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode()) return result; // for the legacy purposes - we need to look for this resource value as resource translation // once again - this will make sure that existing XPath resources are still working if(localizedDisplayName.StartsWith("/")) result = LocalizationProvider.Current.GetString(localizedDisplayName); // If other data annotations exists execept for [Display], an exception is thrown when displayname is "" // It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty return string.IsNullOrWhiteSpace(localizedDisplayName) ? null : result; } internal static string GetTranslation(Type containerType, string propertyName) { var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName); return GetTranslation(resourceKey); } } }
Reformat code in metdata provider
Reformat code in metdata provider
C#
apache-2.0
valdisiljuconoks/LocalizationProvider
88b5567bcabd3a7db4115d74b4e31ab78ab60751
tests/cs/delegate-typedef/DelegateTypedef.cs
tests/cs/delegate-typedef/DelegateTypedef.cs
using System; public delegate int IntMap(int x); public static class Program { private static int Apply(IntMap f, int x) { return f(x); } private static int Square(int x) { return x * x; } public static void Main() { Console.WriteLine(Apply(Square, 10)); } }
using System; public delegate T2 Map<T1, T2>(T1 x); public static class Program { private static int Apply(Map<int, int> f, int x) { return f(x); } private static int Square(int x) { return x * x; } public static void Main() { Console.WriteLine(Apply(Square, 10)); } }
Make the delegate test more challenging
Make the delegate test more challenging
C#
mit
jonathanvdc/ecsc
8518535395703aeae8a0a6440c6492bed675ff3a
postalcodefinder/postalcodefinder/Properties/AssemblyInfo.cs
postalcodefinder/postalcodefinder/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("postalcodefinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("postalcodefinder")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("6a604569-bbd4-4f13-b308-ff3969ff7549")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("postalcodefinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Experian")] [assembly: AssemblyProduct("postalcodefinder")] [assembly: AssemblyCopyright("Copyright © Experian 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("6a604569-bbd4-4f13-b308-ff3969ff7549")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Update company name and copyright.
Update company name and copyright.
C#
apache-2.0
M15sy/postalcodefinder,martincostello/postalcodefinder,martincostello/postalcodefinder,TeamArachne/postalcodefinder,TeamArachne/postalcodefinder,M15sy/postalcodefinder
c1093ac52150af7fac615c3c0ad958c2108998dc
ReverseWords/LinkedListInOrderInsertion/LinkedList.cs
ReverseWords/LinkedListInOrderInsertion/LinkedList.cs
namespace LinkedListInOrderInsertion { using System; using System.Collections.Generic; public class LinkedList { private Element Head = null; private Element Iterator = new Element(); internal void Add(int value) { Element insertedElement = new Element { Value = value }; if (Head == null) { Head = insertedElement; Iterator.Next = Head; } else { Element current = Head; if(current.Value > insertedElement.Value) { Head = insertedElement; Head.Next = current; Iterator.Next = Head; return; } while(current.Next != null) { if(current.Next.Value > insertedElement.Value) { insertedElement.Next = current.Next; current.Next = insertedElement; return; } current = current.Next; } current.Next = insertedElement; } } internal int Last() { Element current = Head; while (current.Next != null) { current = current.Next; } return current.Value; } internal IEnumerable<Element> Next() { if(Iterator.Next != null) { yield return Iterator.Next; } } } }
namespace LinkedListInOrderInsertion { using System; using System.Collections.Generic; public class LinkedList { private Element Head = null; private Element Iterator = new Element(); internal void Add(int value) { Element insertedElement = new Element { Value = value }; if (Head == null) { Head = insertedElement; Iterator.Next = Head; } else { Element current = Head; if(current.Value > insertedElement.Value) { Head = insertedElement; Head.Next = current; Iterator.Next = Head; return; } while(current.Next != null) { if(current.Next.Value > insertedElement.Value) { insertedElement.Next = current.Next; current.Next = insertedElement; return; } current = current.Next; } current.Next = insertedElement; } } internal int Last() { Element current = Head; while (current.Next != null) { current = current.Next; } return current.Value; } internal void PrintInReversedOrder(Element startElement) { if (startElement == null) { return; } PrintInReversedOrder(startElement.Next); Console.WriteLine(startElement.Value); } internal IEnumerable<Element> Next() { if(Iterator.Next != null) { yield return Iterator.Next; } } } }
Print in reversed order method
Print in reversed order method
C#
apache-2.0
ozim/CakeStuff
c71f98bd0689661127645b8d1678e017b145d64a
osu.Framework/Graphics/DrawableExtensions.cs
osu.Framework/Graphics/DrawableExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Framework.Graphics { /// <summary> /// Holds extension methods for <see cref="Drawable"/>. /// </summary> public static class DrawableExtensions { /// <summary> /// Adjusts specified properties of a <see cref="Drawable"/>. /// </summary> /// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param> /// <param name="adjustment">The adjustment function.</param> /// <returns>The given <see cref="Drawable"/>.</returns> public static T With<T>(this T drawable, Action<T> adjustment) where T : Drawable { adjustment?.Invoke(drawable); return drawable; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Development; using osu.Framework.Graphics.Containers; namespace osu.Framework.Graphics { /// <summary> /// Holds extension methods for <see cref="Drawable"/>. /// </summary> public static class DrawableExtensions { /// <summary> /// Adjusts specified properties of a <see cref="Drawable"/>. /// </summary> /// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param> /// <param name="adjustment">The adjustment function.</param> /// <returns>The given <see cref="Drawable"/>.</returns> public static T With<T>(this T drawable, Action<T> adjustment) where T : Drawable { adjustment?.Invoke(drawable); return drawable; } /// <summary> /// Forces removal of this drawable from its parent, followed by immediate synchronous disposal. /// </summary> /// <remarks> /// This is intended as a temporary solution for the fact that there is no way to easily dispose /// a component in a way that is guaranteed to be synchronously run on the update thread. /// /// Eventually components will have a better method for unloading. /// </remarks> /// <param name="drawable">The <see cref="Drawable"/> to be disposed.</param> public static void RemoveAndDisposeImmediately(this Drawable drawable) { ThreadSafety.EnsureUpdateThread(); switch (drawable.Parent) { case Container cont: cont.Remove(drawable); break; case CompositeDrawable comp: comp.RemoveInternal(drawable); break; } drawable.Dispose(); } } }
Add extension methods to run guaranteed synchronous disposal
Add extension methods to run guaranteed synchronous disposal Intended to be a temporary resolution to cases we need to ensure components are disposed on the update thread. Should be used from methods like `Screen.OnExiting` to force immediate cleanup of a child drawable.
C#
mit
peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework
9bf20da25f074cb1e84a1e3912d22c035cb2fa48
Orders.com.Core/Extensions/DateExtensions.cs
Orders.com.Core/Extensions/DateExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public static class Extensions { public static DayResult Days(this int days) { return new DayResult(days); } public static YearResult Years(this int years) { return new YearResult(years); } public static DateTime Ago(this DayResult result) { return DateTime.Now.AddDays(-result.NumberOfDays); } public static DateTime Ago(this YearResult result) { return DateTime.Now.AddYears(-result.NumberOfYears); } public static DateTime FromNow(this DayResult result) { return DateTime.Now.AddDays(result.NumberOfDays); } public static DateTime FromNow(this YearResult result) { return DateTime.Now.AddYears(result.NumberOfYears); } } public class DayResult { public DayResult(int numberOfDays) { NumberOfDays = numberOfDays; } public int NumberOfDays { get; private set; } } public class YearResult { public YearResult(int numberOfYears) { NumberOfYears = numberOfYears; } public int NumberOfYears { get; private set; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public static class Extensions { public static MinuteResult Minutes(this int minutes) { return new MinuteResult(minutes); } public static DayResult Days(this int days) { return new DayResult(days); } public static YearResult Years(this int years) { return new YearResult(years); } public static DateTime Ago(this MinuteResult result) { return DateTime.Now.AddMinutes(-result.NumberOfMinutes); } public static DateTime Ago(this DayResult result) { return DateTime.Now.AddDays(-result.NumberOfDays); } public static DateTime Ago(this YearResult result) { return DateTime.Now.AddYears(-result.NumberOfYears); } public static DateTime FromNow(this DayResult result) { return DateTime.Now.AddDays(result.NumberOfDays); } public static DateTime FromNow(this YearResult result) { return DateTime.Now.AddYears(result.NumberOfYears); } } public class MinuteResult { public MinuteResult(int numberOfMinutes) { NumberOfMinutes = numberOfMinutes; } public int NumberOfMinutes { get; private set; } } public class DayResult { public DayResult(int numberOfDays) { NumberOfDays = numberOfDays; } public int NumberOfDays { get; private set; } } public class YearResult { public YearResult(int numberOfYears) { NumberOfYears = numberOfYears; } public int NumberOfYears { get; private set; } }
Add support for minutes in date extensions
Add support for minutes in date extensions
C#
mit
ahanusa/facile.net,peasy/Samples,ahanusa/Peasy.NET,peasy/Samples,peasy/Peasy.NET,peasy/Samples
bfa275ad1c32e0cda7eab918a8de14d7269f0491
osu.Game/Users/UserStatistics.cs
osu.Game/Users/UserStatistics.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class UserStatistics { [JsonProperty(@"level")] public LevelInfo Level; public class LevelInfo { [JsonProperty(@"current")] public int Current; [JsonProperty(@"progress")] public int Progress; } [JsonProperty(@"pp")] public decimal? PP; [JsonProperty(@"pp_rank")] public int Rank; [JsonProperty(@"ranked_score")] public long RankedScore; [JsonProperty(@"hit_accuracy")] public decimal Accuracy; [JsonProperty(@"play_count")] public int PlayCount; [JsonProperty(@"total_score")] public long TotalScore; [JsonProperty(@"total_hits")] public int TotalHits; [JsonProperty(@"maximum_combo")] public int MaxCombo; [JsonProperty(@"replays_watched_by_others")] public int ReplayWatched; [JsonProperty(@"grade_counts")] public Grades GradesCount; public class Grades { [JsonProperty(@"ss")] public int SS; [JsonProperty(@"s")] public int S; [JsonProperty(@"a")] public int A; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class UserStatistics { [JsonProperty(@"level")] public LevelInfo Level; public struct LevelInfo { [JsonProperty(@"current")] public int Current; [JsonProperty(@"progress")] public int Progress; } [JsonProperty(@"pp")] public decimal? PP; [JsonProperty(@"pp_rank")] public int Rank; [JsonProperty(@"ranked_score")] public long RankedScore; [JsonProperty(@"hit_accuracy")] public decimal Accuracy; [JsonProperty(@"play_count")] public int PlayCount; [JsonProperty(@"total_score")] public long TotalScore; [JsonProperty(@"total_hits")] public int TotalHits; [JsonProperty(@"maximum_combo")] public int MaxCombo; [JsonProperty(@"replays_watched_by_others")] public int ReplayWatched; [JsonProperty(@"grade_counts")] public Grades GradesCount; public struct Grades { [JsonProperty(@"ss")] public int SS; [JsonProperty(@"s")] public int S; [JsonProperty(@"a")] public int A; } } }
Change some small classes to struct to avoid potential null check.
Change some small classes to struct to avoid potential null check.
C#
mit
UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,naoey/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,EVAST9919/osu,2yangk23/osu,ZLima12/osu,peppy/osu-new,Damnae/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,Drezi126/osu,ZLima12/osu,Nabile-Rahmani/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,UselessToucan/osu,ppy/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,Frontear/osuKyzer
cbde90e5ed1119332cd5b19f6958fdfc5814a544
ConsoleTesting/WhistTest.cs
ConsoleTesting/WhistTest.cs
// WhistTest.cs // <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright> using System; using CardGames.Whist; namespace ConsoleTesting { /// <summary> /// The whist test class /// </summary> public class WhistTest : IGameTest { /// <summary> /// Run the test /// </summary> public void RunTest() { Whist whist = new Whist(); ConsolePlayer p1 = new ConsolePlayer(); ConsolePlayer p2 = new ConsolePlayer(); ConsolePlayer p3 = new ConsolePlayer(); whist.AddPlayer(p1); whist.AddPlayer(p2); whist.AddPlayer(p3); whist.Start(); } public void RunWithAi() { Console.WriteLine("Es gibt kein AI"); Console.WriteLine("There is no AI") } } }
// WhistTest.cs // <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright> using System; using CardGames.Whist; namespace ConsoleTesting { /// <summary> /// The whist test class /// </summary> public class WhistTest : IGameTest { /// <summary> /// Run the test /// </summary> public void RunTest() { Whist whist = new Whist(); ConsolePlayer p1 = new ConsolePlayer(); ConsolePlayer p2 = new ConsolePlayer(); ConsolePlayer p3 = new ConsolePlayer(); whist.AddPlayer(p1); whist.AddPlayer(p2); whist.AddPlayer(p3); whist.Start(); } public void RunWithAi() { Console.WriteLine("Es gibt kein AI"); Console.WriteLine("There is no AI"); } } }
Add english as well as german
Add english as well as german
C#
mit
ashfordl/cards
c87d27a7ce47ec4208c60a4aec188081e03d105a
Build/AssemblyInfoCommon.cs
Build/AssemblyInfoCommon.cs
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // The following assembly information is common to all Python Tools for Visual // Studio assemblies. // If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your // Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below. // (See also AssemblyVersion.cs in this same directory.) [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Python Tools for Visual Studio")] [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // The following assembly information is common to all Python Tools for Visual // Studio assemblies. // If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your // Properties\AssemblyInfo.cs file and remove any lines duplicating the ones below. // (See also AssemblyVersion.cs in this same directory.) [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Python Tools for Visual Studio")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
Update the Copyright year to 2013
Update the Copyright year to 2013
C#
apache-2.0
fjxhkj/PTVS,fjxhkj/PTVS,jkorell/PTVS,modulexcite/PTVS,gomiero/PTVS,int19h/PTVS,DinoV/PTVS,gilbertw/PTVS,DinoV/PTVS,msunardi/PTVS,denfromufa/PTVS,DinoV/PTVS,jkorell/PTVS,Microsoft/PTVS,gilbertw/PTVS,huguesv/PTVS,jkorell/PTVS,DEVSENSE/PTVS,zooba/PTVS,mlorbetske/PTVS,DEVSENSE/PTVS,dut3062796s/PTVS,fjxhkj/PTVS,Habatchii/PTVS,MetSystem/PTVS,DEVSENSE/PTVS,juanyaw/PTVS,DEVSENSE/PTVS,denfromufa/PTVS,MetSystem/PTVS,jkorell/PTVS,ChinaQuants/PTVS,christer155/PTVS,int19h/PTVS,bolabola/PTVS,denfromufa/PTVS,Habatchii/PTVS,zooba/PTVS,fjxhkj/PTVS,DinoV/PTVS,Microsoft/PTVS,Habatchii/PTVS,int19h/PTVS,modulexcite/PTVS,christer155/PTVS,fjxhkj/PTVS,msunardi/PTVS,gilbertw/PTVS,gomiero/PTVS,crwilcox/PTVS,ChinaQuants/PTVS,Microsoft/PTVS,xNUTs/PTVS,int19h/PTVS,bolabola/PTVS,mlorbetske/PTVS,fivejjs/PTVS,huguesv/PTVS,xNUTs/PTVS,mlorbetske/PTVS,gilbertw/PTVS,Habatchii/PTVS,DEVSENSE/PTVS,alanch-ms/PTVS,christer155/PTVS,xNUTs/PTVS,msunardi/PTVS,xNUTs/PTVS,msunardi/PTVS,bolabola/PTVS,ChinaQuants/PTVS,gomiero/PTVS,jkorell/PTVS,dut3062796s/PTVS,juanyaw/PTVS,fivejjs/PTVS,msunardi/PTVS,MetSystem/PTVS,Habatchii/PTVS,mlorbetske/PTVS,juanyaw/PTVS,Microsoft/PTVS,ChinaQuants/PTVS,bolabola/PTVS,mlorbetske/PTVS,zooba/PTVS,MetSystem/PTVS,alanch-ms/PTVS,fivejjs/PTVS,mlorbetske/PTVS,gomiero/PTVS,modulexcite/PTVS,crwilcox/PTVS,int19h/PTVS,dut3062796s/PTVS,bolabola/PTVS,modulexcite/PTVS,ChinaQuants/PTVS,MetSystem/PTVS,DinoV/PTVS,fjxhkj/PTVS,Microsoft/PTVS,DEVSENSE/PTVS,crwilcox/PTVS,xNUTs/PTVS,alanch-ms/PTVS,gomiero/PTVS,zooba/PTVS,jkorell/PTVS,modulexcite/PTVS,christer155/PTVS,huguesv/PTVS,DinoV/PTVS,ChinaQuants/PTVS,juanyaw/PTVS,gilbertw/PTVS,christer155/PTVS,christer155/PTVS,huguesv/PTVS,dut3062796s/PTVS,denfromufa/PTVS,dut3062796s/PTVS,Microsoft/PTVS,fivejjs/PTVS,denfromufa/PTVS,zooba/PTVS,MetSystem/PTVS,gomiero/PTVS,gilbertw/PTVS,alanch-ms/PTVS,fivejjs/PTVS,msunardi/PTVS,juanyaw/PTVS,int19h/PTVS,alanch-ms/PTVS,alanch-ms/PTVS,crwilcox/PTVS,crwilcox/PTVS,juanyaw/PTVS,zooba/PTVS,modulexcite/PTVS,huguesv/PTVS,crwilcox/PTVS,fivejjs/PTVS,Habatchii/PTVS,bolabola/PTVS,dut3062796s/PTVS,huguesv/PTVS,denfromufa/PTVS,xNUTs/PTVS
b28ff45d8f126fcd62f048945ba017ff68b57e8b
osu!StreamCompanion/Code/Core/Loggers/SentryLogger.cs
osu!StreamCompanion/Code/Core/Loggers/SentryLogger.cs
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using Sentry; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string SentryDsn = "https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2"; public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions { Dsn = SentryDsn, Release = Program.ScVersion }); public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>(); private object _lockingObject = new object(); public void Log(object logMessage, LogLevel logLevel, params string[] vals) { if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException)) { var sentryEvent = new SentryEvent(exception); lock (_lockingObject) { foreach (var contextKeyValue in ContextData) { sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value); } SentryClient.CaptureEvent(sentryEvent); } } } public void SetContextData(string key, string value) { lock (_lockingObject) ContextData[key] = value; } } }
using System; using System.Collections.Generic; using osu_StreamCompanion.Code.Helpers; using Sentry; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces.Services; namespace osu_StreamCompanion.Code.Core.Loggers { public class SentryLogger : IContextAwareLogger { public static string SentryDsn = "https://3187b2a91f23411ab7ec5f85ad7d80b8@sentry.pioo.space/2"; public static SentryClient SentryClient { get; } = new SentryClient(new SentryOptions { Dsn = SentryDsn, Release = Program.ScVersion, SendDefaultPii = true, BeforeSend = BeforeSend }); private static SentryEvent? BeforeSend(SentryEvent arg) { arg.User.IpAddress = null; return arg; } public static Dictionary<string, string> ContextData { get; } = new Dictionary<string, string>(); private object _lockingObject = new object(); public void Log(object logMessage, LogLevel logLevel, params string[] vals) { if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException)) { var sentryEvent = new SentryEvent(exception); lock (_lockingObject) { foreach (var contextKeyValue in ContextData) { sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value); } SentryClient.CaptureEvent(sentryEvent); } } } public void SetContextData(string key, string value) { lock (_lockingObject) ContextData[key] = value; } } }
Update sentry to send data necessary for linking events with users
Misc: Update sentry to send data necessary for linking events with users Example event data that is being sent: https://gist.github.com/Piotrekol/147a93588aaeb489011cc79983dca90e
C#
mit
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
2c1c2530972922640e393f9e28c0f423818a44cc
src/Slack.Webhooks/Properties/AssemblyInfo.cs
src/Slack.Webhooks/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("Slack.Webhooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Slack.Webhooks")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98c19dcd-28da-4ebf-8e81-c9e051d65625")] // 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.8.*")] [assembly: AssemblyFileVersion("0.1.8.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("Slack.Webhooks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Slack.Webhooks")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98c19dcd-28da-4ebf-8e81-c9e051d65625")] // 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.8.*")] [assembly: AssemblyFileVersion("0.1.8.0")] [assembly: InternalsVisibleTo("Slack.Webhooks.Tests")]
Make internals visible to the testing project
Make internals visible to the testing project
C#
mit
nerdfury/Slack.Webhooks,nerdfury/Slack.Webhooks
a64aa5bafc690ea044c1675d6361d78b22b39ad7
src/SFA.DAS.EmployerUsers.Domain/Auditing/AccountLockedAuditMessage.cs
src/SFA.DAS.EmployerUsers.Domain/Auditing/AccountLockedAuditMessage.cs
using System.Collections.Generic; using SFA.DAS.Audit.Types; namespace SFA.DAS.EmployerUsers.Domain.Auditing { public class AccountLockedAuditMessage : EmployerUsersAuditMessage { public AccountLockedAuditMessage(User user) { Category = "ACCOUNT_LOCKED"; Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked"; AffectedEntity = new Entity { Type = "User", Id = user.Id }; ChangedProperties = new List<PropertyUpdate> { PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts) }; } } }
using System.Collections.Generic; using SFA.DAS.Audit.Types; namespace SFA.DAS.EmployerUsers.Domain.Auditing { public class AccountLockedAuditMessage : EmployerUsersAuditMessage { public AccountLockedAuditMessage(User user) { Category = "ACCOUNT_LOCKED"; Description = $"User {user.Email} (id: {user.Id}) has exceeded the limit of failed logins and the account has been locked"; AffectedEntity = new Entity { Type = "User", Id = user.Id }; ChangedProperties = new List<PropertyUpdate> { PropertyUpdate.FromInt(nameof(user.FailedLoginAttempts), user.FailedLoginAttempts), PropertyUpdate.FromBool(nameof(user.IsLocked), user.IsLocked) }; } } }
Add IsLocked to audit for account locked message
Add IsLocked to audit for account locked message
C#
mit
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
482e34cd95cf01a54cee426bb25cbbd027f38531
src/FluentMigrator.Runner/Generators/Jet/JetQuoter.cs
src/FluentMigrator.Runner/Generators/Jet/JetQuoter.cs
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Jet { public class JetQuoter : GenericQuoter { public override string OpenQuote { get { return "["; } } public override string CloseQuote { get { return "]"; } } public override string CloseQuoteEscapeString { get { return string.Empty; } } public override string OpenQuoteEscapeString { get { return string.Empty; } } public override string FormatDateTime(DateTime value) { return ValueQuote + (value).ToString("MM/dd/yyyy HH:mm:ss") + ValueQuote; } } }
using System; using FluentMigrator.Runner.Generators.Generic; namespace FluentMigrator.Runner.Generators.Jet { public class JetQuoter : GenericQuoter { public override string OpenQuote { get { return "["; } } public override string CloseQuote { get { return "]"; } } public override string CloseQuoteEscapeString { get { return string.Empty; } } public override string OpenQuoteEscapeString { get { return string.Empty; } } public override string FormatDateTime(DateTime value) { return ValueQuote + (value).ToString("YYYY-MM-DD HH:mm:ss") + ValueQuote; } } }
Change date format to iso format
Change date format to iso format
C#
apache-2.0
daniellee/fluentmigrator,FabioNascimento/fluentmigrator,MetSystem/fluentmigrator,dealproc/fluentmigrator,lcharlebois/fluentmigrator,bluefalcon/fluentmigrator,KaraokeStu/fluentmigrator,fluentmigrator/fluentmigrator,fluentmigrator/fluentmigrator,barser/fluentmigrator,mstancombe/fluentmig,DefiSolutions/fluentmigrator,tohagan/fluentmigrator,igitur/fluentmigrator,drmohundro/fluentmigrator,tommarien/fluentmigrator,tommarien/fluentmigrator,spaccabit/fluentmigrator,eloekset/fluentmigrator,dealproc/fluentmigrator,igitur/fluentmigrator,bluefalcon/fluentmigrator,eloekset/fluentmigrator,itn3000/fluentmigrator,mstancombe/fluentmigrator,spaccabit/fluentmigrator,mstancombe/fluentmigrator,DefiSolutions/fluentmigrator,swalters/fluentmigrator,mstancombe/fluentmig,KaraokeStu/fluentmigrator,jogibear9988/fluentmigrator,jogibear9988/fluentmigrator,amroel/fluentmigrator,schambers/fluentmigrator,tohagan/fluentmigrator,swalters/fluentmigrator,MetSystem/fluentmigrator,lahma/fluentmigrator,istaheev/fluentmigrator,amroel/fluentmigrator,alphamc/fluentmigrator,IRlyDontKnow/fluentmigrator,lahma/fluentmigrator,modulexcite/fluentmigrator,IRlyDontKnow/fluentmigrator,modulexcite/fluentmigrator,akema-fr/fluentmigrator,DefiSolutions/fluentmigrator,wolfascu/fluentmigrator,wolfascu/fluentmigrator,daniellee/fluentmigrator,istaheev/fluentmigrator,tohagan/fluentmigrator,lcharlebois/fluentmigrator,itn3000/fluentmigrator,lahma/fluentmigrator,FabioNascimento/fluentmigrator,akema-fr/fluentmigrator,vgrigoriu/fluentmigrator,istaheev/fluentmigrator,barser/fluentmigrator,stsrki/fluentmigrator,mstancombe/fluentmig,alphamc/fluentmigrator,daniellee/fluentmigrator,vgrigoriu/fluentmigrator,stsrki/fluentmigrator,drmohundro/fluentmigrator,schambers/fluentmigrator
7e5a2f1710946038d91ee3a204c4c8205a57b7b7
mscorlib/system/notsupportedexception.cs
mscorlib/system/notsupportedexception.cs
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: NotSupportedException ** ** ** Purpose: For methods that should be implemented on subclasses. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class NotSupportedException : SystemException { public NotSupportedException() : base(Environment.GetResourceString("Arg_NotSupportedException")) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } public NotSupportedException(String message) : base(message) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } public NotSupportedException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: NotSupportedException ** ** ** Purpose: For methods that should be implemented on subclasses. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public partial class NotSupportedException : SystemException { public NotSupportedException() : base(Environment.GetResourceString("Arg_NotSupportedException")) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } public NotSupportedException(String message) : base(message) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } public NotSupportedException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_NOTSUPPORTED); } protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
Make NotSupportedException partial to allow XI to add an helper method
[mscorlib] Make NotSupportedException partial to allow XI to add an helper method
C#
mit
esdrubal/referencesource,evincarofautumn/referencesource,mono/referencesource,ludovic-henry/referencesource,directhex/referencesource,stormleoxia/referencesource
1b0e7cb1da116e33303d7873c40500ce4dc21db9
SupportManager.Web/Infrastructure/ApiKey/ApiKeyAuthenticationHandler.cs
SupportManager.Web/Infrastructure/ApiKey/ApiKeyAuthenticationHandler.cs
using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SupportManager.DAL; namespace SupportManager.Web.Infrastructure.ApiKey { public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions> { private readonly SupportManagerContext db; public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { this.db = db; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { if (Request.Query["apikey"].Count != 1) return AuthenticateResult.Fail("Invalid request"); var key = Request.Query["apikey"][0]; var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User) .SingleOrDefaultAsync(); if (user == null) return AuthenticateResult.Fail("Invalid API Key"); var claims = new[] {new Claim(ClaimTypes.Name, user.Login)}; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } } }
using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SupportManager.DAL; namespace SupportManager.Web.Infrastructure.ApiKey { public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions> { private readonly SupportManagerContext db; public ApiKeyAuthenticationHandler(SupportManagerContext db, IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { this.db = db; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { string key; if (Request.Headers["X-API-Key"].Count == 1) key = Request.Headers["X-API-Key"][0]; else if (Request.Query["apikey"].Count == 1) key = Request.Query["apikey"][0]; else return AuthenticateResult.Fail("Invalid request"); var user = await db.ApiKeys.Where(apiKey => apiKey.Value == key).Select(apiKey => apiKey.User) .SingleOrDefaultAsync(); if (user == null) return AuthenticateResult.Fail("Invalid API Key"); var claims = new[] {new Claim(ClaimTypes.Name, user.Login)}; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } } }
Support API Key authentication using header
Support API Key authentication using header
C#
mit
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
0801ebc93bd8844aea371f922a424902dbec0377
test/Telegram.Bot.Tests.Unit/Serialization/MethodNameTests.cs
test/Telegram.Bot.Tests.Unit/Serialization/MethodNameTests.cs
using Newtonsoft.Json; using Telegram.Bot.Requests; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class MethodNameTests { [Fact(DisplayName = "Should serialize method name in webhook responses")] public void Should_Serialize_MethodName_In_Webhook_Responses() { var sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = true }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.Contains(@"""method"":""sendMessage""", request); } [Fact(DisplayName = "Should not serialize method name in webhook responses")] public void Should_Not_Serialize_MethodName_In_Webhook_Responses() { var sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = false }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.DoesNotContain(@"""method"":""sendMessage""", request); } } }
using Newtonsoft.Json; using Telegram.Bot.Requests; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class MethodNameTests { [Fact(DisplayName = "Should serialize method name in webhook responses")] public void Should_Serialize_MethodName_In_Webhook_Responses() { SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = true }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.Contains(@"""method"":""sendMessage""", request); } [Fact(DisplayName = "Should not serialize method name in webhook responses")] public void Should_Not_Serialize_MethodName_In_Webhook_Responses() { SendMessageRequest sendMessageRequest = new SendMessageRequest(1, "text") { IsWebhookResponse = false }; var request = JsonConvert.SerializeObject(sendMessageRequest); Assert.DoesNotContain(@"""method"":""sendMessage""", request); } } }
Remove var keyword in tests
Remove var keyword in tests
C#
mit
TelegramBots/telegram.bot,MrRoundRobin/telegram.bot
b01aa1f6c994781550b8ac3b9cc016d28ba3dfe1
Source/Reflection/fsTypeLookup.cs
Source/Reflection/fsTypeLookup.cs
using System; using System.Reflection; namespace FullSerializer.Internal { /// <summary> /// Provides APIs for looking up types based on their name. /// </summary> internal static class fsTypeLookup { public static Type GetType(string typeName) { //-- // see // http://answers.unity3d.com/questions/206665/typegettypestring-does-not-work-in-unity.html // Try Type.GetType() first. This will work with types defined by the Mono runtime, in // the same assembly as the caller, etc. var type = Type.GetType(typeName); // If it worked, then we're done here if (type != null) return type; // If the TypeName is a full name, then we can try loading the defining assembly // directly if (typeName.Contains(".")) { // Get the name of the assembly (Assumption is that we are using fully-qualified // type names) var assemblyName = typeName.Substring(0, typeName.IndexOf('.')); // Attempt to load the indicated Assembly var assembly = Assembly.Load(assemblyName); if (assembly == null) return null; // Ask that assembly to return the proper Type type = assembly.GetType(typeName); if (type != null) return type; } // If we still haven't found the proper type, we can enumerate all of the loaded // assemblies and see if any of them define the type var currentAssembly = Assembly.GetExecutingAssembly(); var referencedAssemblies = currentAssembly.GetReferencedAssemblies(); foreach (var assemblyName in referencedAssemblies) { // Load the referenced assembly var assembly = Assembly.Load(assemblyName); if (assembly != null) { // See if that assembly defines the named type type = assembly.GetType(typeName); if (type != null) return type; } } // The type just couldn't be found... return null; } } }
using System; using System.Reflection; namespace FullSerializer.Internal { /// <summary> /// Provides APIs for looking up types based on their name. /// </summary> internal static class fsTypeLookup { /// <summary> /// Attempts to lookup the given type. Returns null if the type lookup fails. /// </summary> public static Type GetType(string typeName) { Type type = null; // Try a direct type lookup type = Type.GetType(typeName); if (type != null) { return type; } // If we still haven't found the proper type, we can enumerate all of the loaded // assemblies and see if any of them define the type foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // See if that assembly defines the named type type = assembly.GetType(typeName); if (type != null) { return type; } } return null; } } }
Fix buggy type lookup when Type.FindType fails
Fix buggy type lookup when Type.FindType fails
C#
mit
nuverian/fullserializer,jacobdufault/fullserializer,shadowmint/fullserializer,jagt/fullserializer,Ksubaka/fullserializer,lazlo-bonin/fullserializer,shadowmint/fullserializer,jagt/fullserializer,karlgluck/fullserializer,Ksubaka/fullserializer,shadowmint/fullserializer,darress/fullserializer,Ksubaka/fullserializer,jacobdufault/fullserializer,caiguihou/myprj_02,zodsoft/fullserializer,jacobdufault/fullserializer,jagt/fullserializer
cac8255904a3381233d8f276266f6d95d5528b59
Framework/Lokad.Cqrs.Azure.Tests/MiscTests.cs
Framework/Lokad.Cqrs.Azure.Tests/MiscTests.cs
using Lokad.Cqrs.Build.Engine; using NUnit.Framework; namespace Lokad.Cqrs { [TestFixture] public sealed class MiscTests { // ReSharper disable InconsistentNaming [Test] public void Azure_queues_regex_is_valid() { Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue")); Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue")); } } }
using Lokad.Cqrs.Build.Engine; using NUnit.Framework; namespace Lokad.Cqrs { [TestFixture] public sealed class MiscTests { // ReSharper disable InconsistentNaming [Test] public void Azure_queues_regex_is_valid() { Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("some-queue")); Assert.IsTrue(AzureEngineModule.QueueName.IsMatch("to-watchtower")); Assert.IsFalse(AzureEngineModule.QueueName.IsMatch("-some-queue")); } } }
Verify that "to-project" is a valid queue name
Verify that "to-project" is a valid queue name
C#
bsd-3-clause
modulexcite/lokad-cqrs
74d3703892141f79a367d81b43556f702f2617d6
Msiler/DialogPages/ExtensionDisplayOptions.cs
Msiler/DialogPages/ExtensionDisplayOptions.cs
using System.ComponentModel; namespace Msiler.DialogPages { public class ExtensionDisplayOptions : MsilerDialogPage { [Category("Display")] [DisplayName("Listing font name")] [Description("")] public string FontName { get; set; } = "Consolas"; [Category("Display")] [DisplayName("Listing font size")] [Description("")] public int FontSize { get; set; } = 12; [Category("Display")] [DisplayName("Show line numbers")] [Description("")] public bool LineNumbers { get; set; } = true; [Category("Display")] [DisplayName("VS Color theme")] [Description("Visual Studio color theme, Msiler highlighting will be adjusted based on this value")] public MsilerColorTheme ColorTheme { get; set; } = MsilerColorTheme.Auto; } }
using System.ComponentModel; namespace Msiler.DialogPages { public class ExtensionDisplayOptions : MsilerDialogPage { [Category("Display")] [DisplayName("Listing font name")] [Description("")] public string FontName { get; set; } = "Consolas"; [Category("Display")] [DisplayName("Listing font size")] [Description("")] public int FontSize { get; set; } = 12; [Category("Display")] [DisplayName("Show line numbers")] [Description("")] public bool LineNumbers { get; set; } = false; [Category("Display")] [DisplayName("VS Color theme")] [Description("Visual Studio color theme, Msiler highlighting will be adjusted based on this value")] public MsilerColorTheme ColorTheme { get; set; } = MsilerColorTheme.Auto; } }
Disable line numbers by default
Disable line numbers by default
C#
mit
segrived/Msiler
30e6bde4a79fcd797de571d2561211172f8f5788
OpcMock/OpcMockTests/ProtocolComparerTests.cs
OpcMock/OpcMockTests/ProtocolComparerTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void Protocols_With_The_Same_Name_Are_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void ProtocolsWithTheSameNameShould_Be_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } }
Test names changed to Should notation
Test names changed to Should notation
C#
mit
msdeibel/opcmock
f09fd206f17c9de6d65fbcb4693891e2cf4b8bfe
src/Glimpse.Common/Broker/IMessageBus.cs
src/Glimpse.Common/Broker/IMessageBus.cs
using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>(); IObservable<T> ListenIncludeLatest<T>(); void SendMessage(object message); } }
using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>() where T : IMessage; IObservable<T> ListenIncludeLatest<T>() where T : IMessage; void SendMessage(IMessage message); } }
Update types on Message Bus definition
Update types on Message Bus definition
C#
mit
mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype
e306b01895369d35102ab47ad0ea24ccf3def80c
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/HashingService.cs
src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/HashingService.cs
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",10, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } }
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",6, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } }
Change so that the minimum hash length is 6 characters and not 10
Change so that the minimum hash length is 6 characters and not 10
C#
mit
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
b8e07e786c893af6e5ac550021ede9d27fd6d183
src/bindings/TAPCfgTest.cs
src/bindings/TAPCfgTest.cs
using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } }
using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Src: {0}", packet.Source); Console.WriteLine("Dst: {0}", packet.Destination); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } }
Print source and destination addresses on ICMPv6 packets
Print source and destination addresses on ICMPv6 packets
C#
lgpl-2.1
zhanleewo/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg
e79ba9a1299fc54728d9762af30e5e38a02f0e4b
osu.Game/Utils/FormatUtils.cs
osu.Game/Utils/FormatUtils.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 1d. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 100m. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 1d</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy, bool alwaysShowDecimals = false) => accuracy == 1 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 100m</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy, bool alwaysShowDecimals = false) => accuracy == 100 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00}%"; } }
Add alwaysShowDecimals param to FormatAccuracy
Add alwaysShowDecimals param to FormatAccuracy This allows us to specify whether we want it to show decimal places if accuracy is 100%.
C#
mit
NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu
5d66dbd61002e02441420dd6649bd56b8c9ab0e1
build.cake
build.cake
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore("SimpSim.NET.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration)); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj"); DotNetCoreTest("./SimpSim.NET.Presentation.Tests/SimpSim.NET.Presentation.Tests.csproj"); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Build") .Does(() => { DotNetCoreBuild("SimpSim.NET.sln", new DotNetCoreBuildSettings{Configuration = configuration}); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest(); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
Use DotNetCoreBuild in Cake script.
Use DotNetCoreBuild in Cake script.
C#
mit
ryanjfitz/SimpSim.NET
42b77cf0fce04fc60997827c389e31237dc80192
ECS/EntityComponentSystem.cs
ECS/EntityComponentSystem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } // TODO: Is this needed and is this right place for this method? public IEnumerable<Entity> QueryActiveEntities(Aspect aspect) { return entityManager.GetEntitiesForAspect(aspect); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } }
Add method for querying active entities
Add method for querying active entities
C#
apache-2.0
isurakka/ecs
112070c536e34b31124c68c2a0309d5754a79ed4
starboard-remote/Properties/AssemblyInfo.cs
starboard-remote/Properties/AssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ascend")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Ascend 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
Change remote app version to v0.1
Change remote app version to v0.1
C#
mit
ascendedguard/starboard-sc2
10cc9ba0745d07e5616b58133ec60dd1b220482d
Samples/Toolkit/Desktop/MiniCube/Program.cs
Samples/Toolkit/Desktop/MiniCube/Program.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 MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new SphereGame()) program.Run(); } } }
// 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 MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new MiniCubeGame()) program.Run(); } } }
Fix compilation error in sample
[Build] Fix compilation error in sample
C#
mit
tomba/Toolkit,sharpdx/Toolkit,sharpdx/Toolkit
90f7e83a68dc2372b3b648f228768c0f4d38902e
dev/Manisero.DSLExecutor.Parser.SampleDSL/ExpressionGeneration/FunctionExpressionGeneration/FunctionTypeResolvers/TypeSamplesAndSuffixConventionBasedFunctionTypeResolver.cs
dev/Manisero.DSLExecutor.Parser.SampleDSL/ExpressionGeneration/FunctionExpressionGeneration/FunctionTypeResolvers/TypeSamplesAndSuffixConventionBasedFunctionTypeResolver.cs
using System; using System.Collections.Generic; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); foreach (var functionTypeSample in _functionTypeSamples) { // TODO: Scan sample's assembly for function types // TODO: Fill result with type names without "Function" suffix } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Manisero.DSLExecutor.Domain.FunctionsDomain; using Manisero.DSLExecutor.Extensions; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); var assembliesToScan = _functionTypeSamples.Select(x => x.Assembly).Distinct(); var typesToScan = assembliesToScan.SelectMany(x => x.GetTypes()); foreach (var type in typesToScan) { var functionDefinitionImplementation = type.GetGenericInterfaceDefinitionImplementation(typeof(IFunction<>)); if (functionDefinitionImplementation == null) { continue; } // TODO: Fill result with type names without "Function" suffix } return result; } } }
Implement scanning assemblies for function types
Implement scanning assemblies for function types
C#
mit
manisero/DSLExecutor
2188c50ee44b4b42a5d27c0342776364ecb30413
Assets/MixedRealityToolkit.Services/InputSystem/DefaultRaycastProvider.cs
Assets/MixedRealityToolkit.Services/InputSystem/DefaultRaycastProvider.cs
using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } }
Add missing copyright header text.
Add missing copyright header text.
C#
mit
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity
04446b0633116305a02376c0787526467be409db
XamarinApp/MyTrips/MyTrips.iOS/Screens/Trips/TripSummaryViewController.cs
XamarinApp/MyTrips/MyTrips.iOS/Screens/Trips/TripSummaryViewController.cs
using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await DismissViewControllerAsync(true); await ViewModel.SaveRecordingTripAsync(); } } }
using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await ViewModel.SaveRecordingTripAsync(); await DismissViewControllerAsync(true); } } }
Save trip before dismissing summary.
[iOS] Save trip before dismissing summary.
C#
mit
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
830fc7900b5807f10790e0f134313f994f0f0c1e
WalletWasabi/Io/MutexIoManager.cs
WalletWasabi/Io/MutexIoManager.cs
using Nito.AsyncEx; using WalletWasabi.Crypto; namespace WalletWasabi.Io { public class MutexIoManager : IoManager { public MutexIoManager(string filePath) : base(filePath) { var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(1, 7); // https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8 // On a server that is running Terminal Services, a named system mutex can have two levels of visibility. // If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. // If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. // In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. // If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". // Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, // and both are visible to all processes in the terminal server session. // That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes. Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}"); } public AsyncMutex Mutex { get; } } }
using Nito.AsyncEx; using WalletWasabi.Crypto; namespace WalletWasabi.Io { public class MutexIoManager : IoManager { public MutexIoManager(string filePath) : base(filePath) { var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(0, 7); // https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8 // On a server that is running Terminal Services, a named system mutex can have two levels of visibility. // If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. // If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. // In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. // If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". // Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, // and both are visible to all processes in the terminal server session. // That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes. Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}"); } public AsyncMutex Mutex { get; } } }
Fix off by one bug
Fix off by one bug
C#
mit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
47010a1cf7b4524ce919f59474aaac0a58ccea16
Mathematicians.UnitTests/SqlGeneratorTests.cs
Mathematicians.UnitTests/SqlGeneratorTests.cs
using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } } }
using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } [Fact] public void GeneratesNoSqlWhenUpToDate() { var migrations = new Migrations(); var migrationHistory = GivenCompleteMigrationHistory(migrations); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(0); } private MigrationHistory GivenCompleteMigrationHistory(Migrations migrations) { var model = new ModelSpecification(); migrations.AddMigrations(model); return model.MigrationHistory; } } }
Test for migrations up to date.
Test for migrations up to date.
C#
mit
schemavolution/schemavolution,schemavolution/schemavolution
b8c5b18fb61b394bfed594fc71137a17ea36015c
Criteo.Profiling.Tracing/Utils/RandomUtils.cs
Criteo.Profiling.Tracing/Utils/RandomUtils.cs
using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int seed = Environment.TickCount; private static readonly ThreadLocal<Random> rand = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static long NextLong() { return (long)((rand.Value.NextDouble() * 2.0 - 1.0) * long.MaxValue); } } }
using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int _seed = Guid.NewGuid().GetHashCode(); private static readonly ThreadLocal<Random> LocalRandom = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref _seed))); public static long NextLong() { var buffer = new byte[8]; LocalRandom.Value.NextBytes(buffer); return BitConverter.ToInt64(buffer, 0); } } }
Change random to avoid identical seed
Change random to avoid identical seed It seems it is possible for two processes started at the exact same time to get the same seed. This could be the case for IIS where 2 handlers are started simultaneously. Change-Id: I156fac5fe8c91c0931d38b0b6e5fe5cfb0e83665
C#
apache-2.0
criteo/zipkin4net,criteo/zipkin4net
8b60af548da68814cde28002dee42f290c233d47
NuPack/PackageAuthoring.cs
NuPack/PackageAuthoring.cs
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { // Parse the arguments. The last argument is the content to be added to the package var manifestFile = args.First(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); using (Stream stream = File.Create(outputFile)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputFile); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { var manifestFile = args.First(); string outputDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); string outputPath = Path.Combine(outputDirectory, outputFile); using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputPath); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } }
Allow output directory to be specified as a second parameter.
Allow output directory to be specified as a second parameter.
C#
apache-2.0
oliver-feng/nuget,indsoft/NuGet2,xoofx/NuGet,indsoft/NuGet2,dolkensp/node.net,chocolatey/nuget-chocolatey,antiufo/NuGet2,alluran/node.net,mrward/NuGet.V2,jmezach/NuGet2,dolkensp/node.net,chocolatey/nuget-chocolatey,ctaggart/nuget,OneGet/nuget,RichiCoder1/nuget-chocolatey,themotleyfool/NuGet,ctaggart/nuget,oliver-feng/nuget,akrisiun/NuGet,xoofx/NuGet,pratikkagda/nuget,mrward/NuGet.V2,zskullz/nuget,mono/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,mrward/nuget,rikoe/nuget,pratikkagda/nuget,pratikkagda/nuget,indsoft/NuGet2,mrward/nuget,jholovacs/NuGet,mrward/nuget,mrward/nuget,dolkensp/node.net,pratikkagda/nuget,themotleyfool/NuGet,chocolatey/nuget-chocolatey,jmezach/NuGet2,alluran/node.net,xoofx/NuGet,ctaggart/nuget,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,antiufo/NuGet2,mrward/NuGet.V2,mono/nuget,indsoft/NuGet2,jmezach/NuGet2,jmezach/NuGet2,zskullz/nuget,xoofx/NuGet,atheken/nuget,akrisiun/NuGet,jholovacs/NuGet,GearedToWar/NuGet2,mrward/nuget,chester89/nugetApi,rikoe/nuget,GearedToWar/NuGet2,jmezach/NuGet2,xero-github/Nuget,zskullz/nuget,mrward/nuget,oliver-feng/nuget,mrward/NuGet.V2,xoofx/NuGet,GearedToWar/NuGet2,rikoe/nuget,mono/nuget,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,antiufo/NuGet2,antiufo/NuGet2,antiufo/NuGet2,atheken/nuget,anurse/NuGet,GearedToWar/NuGet2,pratikkagda/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,antiufo/NuGet2,jholovacs/NuGet,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,kumavis/NuGet,dolkensp/node.net,GearedToWar/NuGet2,OneGet/nuget,OneGet/nuget,oliver-feng/nuget,oliver-feng/nuget,chester89/nugetApi,chocolatey/nuget-chocolatey,xoofx/NuGet,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,indsoft/NuGet2,mono/nuget,mrward/NuGet.V2,kumavis/NuGet,jholovacs/NuGet,jholovacs/NuGet,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,OneGet/nuget,anurse/NuGet,rikoe/nuget,alluran/node.net,themotleyfool/NuGet,ctaggart/nuget,alluran/node.net,zskullz/nuget
15fb0c0690bc141ec464488194a07fc6e8544e30
osu.Framework/Allocation/AsyncDisposalQueue.cs
osu.Framework/Allocation/AsyncDisposalQueue.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.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Enqueue(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } }
// 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.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly List<IDisposable> disposal_queue = new List<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Add(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } }
Make the queue into a list
Make the queue into a list
C#
mit
EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework
4a1e3fbd42b1a00c07c81527e40512f2eb1c5eba
tests/Okanshi.Tests/PerformanceCounterTest.cs
tests/Okanshi.Tests/PerformanceCounterTest.cs
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } } }
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } } }
Make performance counter tests more stable
Make performance counter tests more stable
C#
mit
mvno/Okanshi,mvno/Okanshi,mvno/Okanshi
736aa068ccbc58ca4a38221be9514c641f9fa754
mvcWebApp/Controllers/HomeController.cs
mvcWebApp/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; namespace mvcWebApp.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { string domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); // NICE-TO-HAVE Sort images by height. string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images"); string[] files = Directory.EnumerateFiles(imagesDir).Select(p => domain + "/Images/" + Path.GetFileName(p)).ToArray(); ViewBag.ImageVirtualPaths = files; return View(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; namespace mvcWebApp.Controllers { public class HomeController : Controller { public string domain { get { string domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); return domain; } } // // GET: /Home/ public ActionResult Index() { // NICE-TO-HAVE Sort images by height. string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images"); string[] files = Directory.EnumerateFiles(imagesDir).Select(p => this.domain + "/Images/" + Path.GetFileName(p)).ToArray(); ViewBag.ImageVirtualPaths = files; return View(); } } }
Make domain a property for reuse.
Make domain a property for reuse.
C#
mit
bigfont/sweet-water-revolver
48e50ba37c24cc2a3125ed0853708f3ca51f13bb
src/Nest/Domain/Responses/SearchShardsResponse.cs
src/Nest/Domain/Responses/SearchShardsResponse.cs
using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }
using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }
Fix wrong property mapping in SearchShard
Fix wrong property mapping in SearchShard
C#
apache-2.0
CSGOpenSource/elasticsearch-net,tkirill/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,ststeiger/elasticsearch-net,UdiBen/elasticsearch-net,faisal00813/elasticsearch-net,DavidSSL/elasticsearch-net,KodrAus/elasticsearch-net,tkirill/elasticsearch-net,tkirill/elasticsearch-net,adam-mccoy/elasticsearch-net,DavidSSL/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,robrich/elasticsearch-net,abibell/elasticsearch-net,junlapong/elasticsearch-net,SeanKilleen/elasticsearch-net,azubanov/elasticsearch-net,starckgates/elasticsearch-net,faisal00813/elasticsearch-net,mac2000/elasticsearch-net,KodrAus/elasticsearch-net,starckgates/elasticsearch-net,starckgates/elasticsearch-net,RossLieberman/NEST,DavidSSL/elasticsearch-net,TheFireCookie/elasticsearch-net,mac2000/elasticsearch-net,gayancc/elasticsearch-net,LeoYao/elasticsearch-net,robrich/elasticsearch-net,jonyadamit/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,ststeiger/elasticsearch-net,gayancc/elasticsearch-net,faisal00813/elasticsearch-net,adam-mccoy/elasticsearch-net,joehmchan/elasticsearch-net,wawrzyn/elasticsearch-net,elastic/elasticsearch-net,robrich/elasticsearch-net,jonyadamit/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,ststeiger/elasticsearch-net,abibell/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,SeanKilleen/elasticsearch-net,geofeedia/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,jonyadamit/elasticsearch-net,geofeedia/elasticsearch-net,joehmchan/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,LeoYao/elasticsearch-net,mac2000/elasticsearch-net,wawrzyn/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,junlapong/elasticsearch-net,LeoYao/elasticsearch-net
fecd3d778a6dcd5722637e092a1f3e6c6ae8c466
Src/Glimpse.Nancy/GlimpseRegistrations.cs
Src/Glimpse.Nancy/GlimpseRegistrations.cs
using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IApplicationRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }
using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }
Remove usage of obsolete IApplicationRegistration
Remove usage of obsolete IApplicationRegistration
C#
mit
csainty/Glimpse.Nancy,csainty/Glimpse.Nancy,csainty/Glimpse.Nancy
1f90b9f159b4a190c815b90e5a2057c6b5955b3d
Battery-Commander.Web/Models/EvaluationListViewModel.cs
Battery-Commander.Web/Models/EvaluationListViewModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => _.ThruDate > DateTime.Today).Where(_ => DateTime.Today.AddDays(30) < _.ThruDate).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(30)).Where(_ => DateTime.Today.AddDays(60) <= _.ThruDate).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(60)).Where(_ => DateTime.Today.AddDays(90) <= _.ThruDate).Count(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }
Fix logic on 30/60/90 day buckets
Fix logic on 30/60/90 day buckets
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
18e54b8bdc2e427a4929c8b7177478c3d370fd74
src/Tests/NamespaceTests.cs
src/Tests/NamespaceTests.cs
using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } } }
using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } [Fact] public void TinyIoc_Stays_Internal() { typeof(TinyIoCContainer).IsPublic.Should().BeFalse(); } } }
Test to check tinyioc is internal
Test to check tinyioc is internal
C#
mit
AMVSoftware/NSaga
94441380f5586776b487ae70e2b8ccdc0254d982
src/Yio/Views/Shared/_AboutPanelPartial.cshtml
src/Yio/Views/Shared/_AboutPanelPartial.cshtml
@{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. Built by <a href="https://zyr.io">Zyrio</a>. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>
@{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. </p> <p> Built by <a href="https://zyr.io">Zyrio</a>. Licensed under the MIT license, with code available on <a href="https://git.zyr.io/zyrio/yio">Zyrio Git</a>. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>
Add license and disclaimer to About panel
Add license and disclaimer to About panel
C#
mit
Zyrio/ictus,Zyrio/ictus
7ee8f0cca2fee7ee576bb40995d07c03d0746c29
src/ResourceManager/Profile/Commands.Profile/DataCollection/EnableAzureRMDataCollection.cs
src/ResourceManager/Profile/Commands.Profile/DataCollection/EnableAzureRMDataCollection.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void BeginProcessing() { // do not call begin processing there is no context needed for this cmdlet } protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } }
Fix data collection cmdlets to not require login
Fix data collection cmdlets to not require login
C#
apache-2.0
zhencui/azure-powershell,naveedaz/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,pomortaz/azure-powershell,devigned/azure-powershell,zhencui/azure-powershell,zhencui/azure-powershell,dulems/azure-powershell,yoavrubin/azure-powershell,dominiqa/azure-powershell,akurmi/azure-powershell,atpham256/azure-powershell,alfantp/azure-powershell,krkhan/azure-powershell,Matt-Westphal/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,nemanja88/azure-powershell,arcadiahlyy/azure-powershell,DeepakRajendranMsft/azure-powershell,juvchan/azure-powershell,yoavrubin/azure-powershell,alfantp/azure-powershell,haocs/azure-powershell,haocs/azure-powershell,stankovski/azure-powershell,naveedaz/azure-powershell,juvchan/azure-powershell,krkhan/azure-powershell,yantang-msft/azure-powershell,ankurchoubeymsft/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,yoavrubin/azure-powershell,pankajsn/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,shuagarw/azure-powershell,dominiqa/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,CamSoper/azure-powershell,dominiqa/azure-powershell,CamSoper/azure-powershell,seanbamsft/azure-powershell,naveedaz/azure-powershell,CamSoper/azure-powershell,alfantp/azure-powershell,shuagarw/azure-powershell,stankovski/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,juvchan/azure-powershell,DeepakRajendranMsft/azure-powershell,akurmi/azure-powershell,jtlibing/azure-powershell,ClogenyTechnologies/azure-powershell,jtlibing/azure-powershell,seanbamsft/azure-powershell,jasper-schneider/azure-powershell,AzureAutomationTeam/azure-powershell,akurmi/azure-powershell,rohmano/azure-powershell,TaraMeyer/azure-powershell,jasper-schneider/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,AzureAutomationTeam/azure-powershell,dominiqa/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,hovsepm/azure-powershell,pomortaz/azure-powershell,yantang-msft/azure-powershell,dulems/azure-powershell,stankovski/azure-powershell,ankurchoubeymsft/azure-powershell,TaraMeyer/azure-powershell,jasper-schneider/azure-powershell,DeepakRajendranMsft/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,ClogenyTechnologies/azure-powershell,AzureRT/azure-powershell,haocs/azure-powershell,AzureRT/azure-powershell,jtlibing/azure-powershell,rohmano/azure-powershell,ankurchoubeymsft/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,Matt-Westphal/azure-powershell,nemanja88/azure-powershell,hungmai-msft/azure-powershell,juvchan/azure-powershell,hungmai-msft/azure-powershell,dulems/azure-powershell,hovsepm/azure-powershell,AzureAutomationTeam/azure-powershell,CamSoper/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,AzureRT/azure-powershell,jasper-schneider/azure-powershell,hungmai-msft/azure-powershell,haocs/azure-powershell,CamSoper/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,pomortaz/azure-powershell,hovsepm/azure-powershell,shuagarw/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,AzureRT/azure-powershell,stankovski/azure-powershell,hovsepm/azure-powershell,krkhan/azure-powershell,pomortaz/azure-powershell,seanbamsft/azure-powershell,DeepakRajendranMsft/azure-powershell,yoavrubin/azure-powershell,seanbamsft/azure-powershell,haocs/azure-powershell,seanbamsft/azure-powershell,arcadiahlyy/azure-powershell,nemanja88/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,AzureRT/azure-powershell,ClogenyTechnologies/azure-powershell,rohmano/azure-powershell,ankurchoubeymsft/azure-powershell,DeepakRajendranMsft/azure-powershell,Matt-Westphal/azure-powershell,hungmai-msft/azure-powershell,jasper-schneider/azure-powershell,pankajsn/azure-powershell,ankurchoubeymsft/azure-powershell,dominiqa/azure-powershell,pankajsn/azure-powershell,TaraMeyer/azure-powershell,yoavrubin/azure-powershell,Matt-Westphal/azure-powershell,pomortaz/azure-powershell,akurmi/azure-powershell,devigned/azure-powershell,TaraMeyer/azure-powershell,arcadiahlyy/azure-powershell,zhencui/azure-powershell,atpham256/azure-powershell,stankovski/azure-powershell,pankajsn/azure-powershell,arcadiahlyy/azure-powershell,AzureRT/azure-powershell,dulems/azure-powershell,ClogenyTechnologies/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,shuagarw/azure-powershell,Matt-Westphal/azure-powershell,nemanja88/azure-powershell,TaraMeyer/azure-powershell,dulems/azure-powershell,arcadiahlyy/azure-powershell,juvchan/azure-powershell,atpham256/azure-powershell,shuagarw/azure-powershell
b93b6ba2ca215fac5a66e224695a908ff57925e9
osu.Game.Rulesets.Osu/Mods/OsuModSingleTap.cs
osu.Game.Rulesets.Osu/Mods/OsuModSingleTap.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; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"ST"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } }
// 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; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"SG"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } }
Change "single tap" mod acronym to not conflict with "strict tracking"
Change "single tap" mod acronym to not conflict with "strict tracking"
C#
mit
ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
f324072d44d70ec439fe8ef17e95f7dff2d426a2
osu.Game.Tournament.Tests/TestCaseMapPool.cs
osu.Game.Tournament.Tests/TestCaseMapPool.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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : CompositeDrawable { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo)); } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Screens; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; using OpenTK; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : OsuScreen { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Spacing = new Vector2(20), Padding = new MarginPadding(50), Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }); } } }
Make map pool layout more correct
Make map pool layout more correct
C#
mit
johnneijzen/osu,EVAST9919/osu,2yangk23/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu
30a5a4abed9fb2519b6e72308977f624484b5b57
BobTheBuilder/NamedArgumentsDynamicBuilder.cs
BobTheBuilder/NamedArgumentsDynamicBuilder.cs
using System; using System.Dynamic; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { return wrappedBuilder.TryInvokeMember(binder, args, out result); } public T Build() { return wrappedBuilder.Build(); } } }
using System; using System.Dynamic; using System.Linq; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder.Name == "With") { ParseNamedArgumentValues(binder.CallInfo, args); } return wrappedBuilder.TryInvokeMember(binder, args, out result); } private void ParseNamedArgumentValues(CallInfo callInfo, object[] args) { var argumentName = callInfo.ArgumentNames.First(); argumentName = argumentName.First().ToString().ToUpper() + argumentName.Substring(1); argumentStore.SetMemberNameAndValue(argumentName, args.First()); } public T Build() { return wrappedBuilder.Build(); } } }
Add support for named argument parsing.
Add support for named argument parsing. The argument name munging is not pretty and needs improving (and perhaps breaking out into another class?), but it does at least currently work.
C#
apache-2.0
alastairs/BobTheBuilder,fffej/BobTheBuilder
f5aa6b09edc9338111114e4e8ea425be37f99cce
src/NodaTime/Extensions/StopwatchExtensions.cs
src/NodaTime/Extensions/StopwatchExtensions.cs
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. #if !PCL using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } } #endif
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } }
Enable stopwatch extension methods for .NET Core
Enable stopwatch extension methods for .NET Core I suspect Stopwatch wasn't available in earlier versions of .NET Standard - or possibly not in netstandard1.1 when we targeted that. But it's fine for netstandard1.3.
C#
apache-2.0
malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,jskeet/nodatime,nodatime/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime
e466e3d15f8522d4db37575a6665d943d8c6e1e6
src/RedCard.API/Controllers/StatsController.cs
src/RedCard.API/Controllers/StatsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [HttpGet] public IActionResult RedCardCountForCountry() { var redCardCount = _dbContext.Players .GroupBy(player => player.Country) .Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }) .ToArray(); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; using RedCard.API.Models; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [Route("redcards")] [HttpGet] public IActionResult RedCardCountForCountry() { Func<IGrouping<string, Player>, object> getRedCardsForCountry = (grouping) => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }; var redCardCount = _CardsForCountry(getRedCardsForCountry); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } [Route("yellowcards")] [HttpGet] public IActionResult YellowCardCountForCountry() { Func<IGrouping<string, Player>, object> getYellowCardsForCountry = (grouping) => new { country = grouping.Key, yellowCardCount = grouping.Sum(player => player.YellowCards) }; var yellowCardCount = _CardsForCountry(getYellowCardsForCountry); return new ObjectResult(new { yellowCardCountForCountry = yellowCardCount }); } IEnumerable<object> _CardsForCountry(Func<IGrouping<string, Player>, object> getInfo) { return _dbContext.Players .GroupBy(player => player.Country) .Select(getInfo) .ToArray(); } } }
Add group by yellow cards count
Add group by yellow cards count
C#
mit
mglodack/RedCard.API,mglodack/RedCard.API
f0cf94f283aaca7981561800cc250eea11742d42
Client/Utilities/CoroutineUtil.cs
Client/Utilities/CoroutineUtil.cs
using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } }
using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { if (delayInSec > 0) yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } }
Allow coroutines of 0 sec delay
Allow coroutines of 0 sec delay
C#
mit
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
6b17d8bab2977129f97f3960307e2728d0ef74c4
uSync/uSync.cs
uSync/uSync.cs
namespace uSync { /// <summary> /// we only have this class, so there is a dll in the root /// uSync package. /// /// With a root dll, the package can be stopped from installing /// on .netframework sites. /// </summary> public static class uSync { // private static string Welcome = "uSync all the things"; } }
using System; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Packaging; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Migrations; using Umbraco.Cms.Infrastructure.Packaging; namespace uSync { /// <summary> /// we only have this class, so there is a dll in the root /// uSync package. /// /// With a root dll, the package can be stopped from installing /// on .netframework sites. /// </summary> public static class uSync { public static string PackageName = "uSync"; // private static string Welcome = "uSync all the things"; } /// <summary> /// A package migration plan, allows us to put uSync in the list /// of installed packages. we don't actually need a migration /// for uSync (doesn't add anything to the db). but by doing /// this people can see that it is insalled. /// </summary> public class uSyncMigrationPlan : PackageMigrationPlan { public uSyncMigrationPlan() : base(uSync.PackageName) { } protected override void DefinePlan() { To<SetupuSync>(new Guid("65735030-E8F2-4F34-B28A-2201AF9792BE")); } } public class SetupuSync : PackageMigrationBase { public SetupuSync( IPackagingService packagingService, IMediaService mediaService, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, IMigrationContext context) : base(packagingService, mediaService, mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, context) { } protected override void Migrate() { // we don't actually need to do anything, but this means we end up // on the list of installed packages. } } }
Add blank package migration (to get into the list)
Add blank package migration (to get into the list)
C#
mpl-2.0
KevinJump/uSync,KevinJump/uSync,KevinJump/uSync
0ded40800b7f6395fb5a18278a58a379ececb763
Web/Controllers/HomeController.cs
Web/Controllers/HomeController.cs
using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { var model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }
using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { ProtobufModelDto model = null; if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf") { model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } var content = await response.Content.ReadAsStringAsync(); model = JsonConvert.DeserializeObject<ProtobufModelDto>(content); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }
Add check for content type when parsing in client. Fallback to Json if Protobuf is not available
Add check for content type when parsing in client. Fallback to Json if Protobuf is not available
C#
mit
Hypnobrew/StockMonitor
5c958ebeb8e847fd47a7fc383b82e42a4beea1a1
ExpressionToCodeTest/ExceptionsSerialization.cs
ExpressionToCodeTest/ExceptionsSerialization.cs
using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } } }
using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); #pragma warning disable SYSLIB0011 // BinaryFormatter is Obsolete static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } #pragma warning restore SYSLIB0011 } }
Disable warnings about obsoletion since the point is testing the obsolete stuff still works
Disable warnings about obsoletion since the point is testing the obsolete stuff still works
C#
apache-2.0
EamonNerbonne/ExpressionToCode
27b3f23ff3c7b040885784b46a90e9523e633e93
OpenSim/Services/Interfaces/IAttachmentsService.cs
OpenSim/Services/Interfaces/IAttachmentsService.cs
//////////////////////////////////////////////////////////////// // // (c) 2009, 2010 Careminster Limited and Melanie Thielker // // All rights reserved // using System; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using Nini.Config; using log4net; using Careminster; using OpenMetaverse; namespace Careminster { public interface IAttachmentsService { string Get(string id); void Store(string id, string data); } }
//////////////////////////////////////////////////////////////// // // (c) 2009, 2010 Careminster Limited and Melanie Thielker // // All rights reserved // using System; using Nini.Config; namespace OpenSim.Services.Interfaces { public interface IAttachmentsService { string Get(string id); void Store(string id, string data); } }
Remove some usings that stopped compilation
Remove some usings that stopped compilation
C#
bsd-3-clause
RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC
28bd86e720ffdb3dbb2440484fd5b0bdf92a6f3a
IntermediatorBotSample/Controllers/Api/ConversationsController.cs
IntermediatorBotSample/Controllers/Api/ConversationsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get() { return Builder<Conversation>.CreateListOfSize(2) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew().Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew().Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew().Build()) .Build() .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get(int convId, int top) { var channels = new[] { "facebook", "skype", "skype for business", "directline" }; var random = new RandomGenerator(); return Builder<Conversation>.CreateListOfSize(5) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew() .With(ci => ci.MessagesCount = random.Next(2, 30)) .With(ci => ci.SentimentScore = random.Next(0.0d, 1.0d)) .Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew() .With(cr => cr.ChannelId = channels[random.Next(0, channels.Count())]) .Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew() .Build()) .Build() .ToList(); } //TODO: Retrieve ALL the conversation //TOOD: Forward conersation //TODO: DELETE Conversation = immediate kill by conversationId } }
Add intermediate comments to help explain what to do
Add intermediate comments to help explain what to do
C#
mit
tompaana/intermediator-bot-sample,tompaana/intermediator-bot-sample
a5cfc060d903486786102726db324ae8b9b2d82e
game/server/weapons/minigun.projectile.sfx.cs
game/server/weapons/minigun.projectile.sfx.cs
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioClose3D; preload = true; };
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/ricochet1-1.wav"; alternate[0] = "share/sounds/rotc/ricochet1-1.wav"; alternate[1] = "share/sounds/rotc/ricochet1-2.wav"; alternate[2] = "share/sounds/rotc/ricochet1-3.wav"; alternate[3] = "share/sounds/rotc/ricochet1-4.wav"; alternate[4] = "share/sounds/rotc/ricochet1-5.wav"; alternate[5] = "share/sounds/rotc/ricochet1-6.wav"; description = AudioClose3D; preload = true; };
Use different sounds for minigun's missed enemy effect.
Use different sounds for minigun's missed enemy effect.
C#
lgpl-2.1
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
cd56b49e34486d1733a97a5c6dd593abacee9993
EchoServer/Program.cs
EchoServer/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); CancellationToken cancellationToken = new CancellationTokenSource().Token; TcpListener listener = new TcpListener(IPAddress.IPv6Loopback, 8080); listener.Start(); TcpClient client = await listener.AcceptTcpClientAsync(); client.ReceiveTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); while (true) { string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); if (cancellationToken.IsCancellationRequested) break; } listener.Stop(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); TcpListener server = new TcpListener(IPAddress.IPv6Loopback, 8080); Console.WriteLine("Starting listener"); server.Start(); while (true) { TcpClient client = await server.AcceptTcpClientAsync(); Task.Factory.StartNew(() => HandleConnection(client)); } server.Stop(); } static async Task HandleConnection(TcpClient client) { Console.WriteLine($"New connection from {client.Client.RemoteEndPoint}"); client.ReceiveTimeout = 30; client.SendTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); } } }
Move client handling into a separate method.
Move client handling into a separate method.
C#
mit
darkriszty/NetworkCardsGame
66a2a54aebcc6197c1bacf84b0aa5105b86e3f27
src/Generator/Passes/FieldToPropertyPass.cs
src/Generator/Passes/FieldToPropertyPass.cs
using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name, field.Name); return false; } } }
using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug($"Property created from field: {field.QualifiedName}"); return false; } } }
Clean up the diagnostic in FieldToProperty pass.
Clean up the diagnostic in FieldToProperty pass.
C#
mit
mono/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mono/CppSharp,mono/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,mono/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp
9a89c1721f0767da2ee7fc8863e02ce3b80c27bc
src/HttpMock.Unit.Tests/HttpFactoryTests.cs
src/HttpMock.Unit.Tests/HttpFactoryTests.cs
 using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } }
 using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] [Ignore ("Makes the test suite flaky (???)")] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } }
Mark evil test as ignore, again
UnitTest: Mark evil test as ignore, again
C#
mit
mattolenik/HttpMock,hibri/HttpMock,oschwald/HttpMock,zhdusurfin/HttpMock
00a4d60e8910869457d3e70ec04b6727b705d15f
osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs
osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.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; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = current.TravelDistance + current.JumpDistance; return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
// 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; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
Make sure distance is clamped to sane values
Make sure distance is clamped to sane values
C#
mit
johnneijzen/osu,EVAST9919/osu,2yangk23/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,naoey/osu,ZLima12/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,NeoAdonis/osu,naoey/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu
b7c20065a46d23a1032285cb97ed66b46129f2c8
Src/Qart.Testing/TestSystem.cs
Src/Qart.Testing/TestSystem.cs
using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } }
using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Concat(new[]{"."}).Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } }
Fix for GetTestCases not returning current folder
Fix for GetTestCases not returning current folder
C#
apache-2.0
avao/Qart,mcraveiro/Qart,tudway/Qart
cc61c53579ea9714abfc881565a89c7c9882dc9b
src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs
src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use. /// </summary> /// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value> public bool IsInUse { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets the locker id. /// </summary> /// <value>The locker id.</value> public Guid? LockerId { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } }
Refactor virtual judge user table schema
Refactor virtual judge user table schema
C#
mit
JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge
cf079690e528cadd4387402ca2a050d388604796
osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs
osu.Game/Beatmaps/Drawables/BeatmapSetCover.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; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(TextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
// 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; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } }
Use LargeTextureStore for online retrievals
Use LargeTextureStore for online retrievals
C#
mit
UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,naoey/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,naoey/osu,peppy/osu,ZLima12/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu
37053608f1544f0a6a294b6695cbac323730931c
EOLib/Net/Handlers/PacketHandlingTypeFinder.cs
EOLib/Net/Handlers/PacketHandlingTypeFinder.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder() { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Connection, PacketAction.Player) }; } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; using System.Linq; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers) { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList(); } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }
Use registered types for Out of Band handlers in packet handling type finder
Use registered types for Out of Band handlers in packet handling type finder Replaces manually built up collection. Should be able to eventually have just 1 collection where it is either in-band or not in-band.
C#
mit
ethanmoffat/EndlessClient
084e7fc2d8bd4f9dd169395bb33ed0fff65ff520
Chainey/SentenceConstruct.cs
Chainey/SentenceConstruct.cs
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get { return Forwards.Count + Backwards.Count - order; } } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { int start = Forwards.Count - order; return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { int start = Backwards.Count - order; return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain, int order) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); this.order = order; } internal void Append(string word) { Forwards.Add(word); } internal void Prepend(string word) { Backwards.Add(word); } } }
using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get; private set; } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { var chain = new string[order]; int start = Forwards.Count - order; Forwards.CopyTo(start, chain, 0, order); return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { var chain = new string[order]; int start = Backwards.Count - order; Backwards.CopyTo(start, chain, 0, order); return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); WordCount = split.Length; order = split.Length; } internal void Append(string word) { Forwards.Add(word); WordCount++; } internal void Prepend(string word) { Backwards.Add(word); WordCount++; } } }
Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.
Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.
C#
bsd-2-clause
IvionSauce/MeidoBot
597f3ee243aa7d6bbeff4ca991bec61f2cf8f29f
src/keypay-dotnet/Properties/AssemblyInfo.cs
src/keypay-dotnet/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("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc")] [assembly: AssemblyFileVersion("1.0.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("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc2")] [assembly: AssemblyFileVersion("1.0.0.0")]
Update Nuget version of package to 1.1.0.10-rc
Update Nuget version of package to 1.1.0.10-rc
C#
mit
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
32cc1d99aaa4c844657cc9199d8b7b6223cda738
nunit.migrator/CodeActions/AssertUserMessageDecorator.cs
nunit.migrator/CodeActions/AssertUserMessageDecorator.cs
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly ExceptionExpectancyAtAttributeLevel _attribute; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { _attribute = attribute; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly string _userMessage; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); _userMessage = attribute.UserMessage; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_userMessage}\""))); var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }
Refactor - UserMessage instead of attribute
Refactor - UserMessage instead of attribute
C#
mit
wachulski/nunit-migrator
8057202fe1cd718c20225dc8065d33f5391eedbd
MFlow.Core/Internal/ExpressionBuilder.cs
MFlow.Core/Internal/ExpressionBuilder.cs
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } class InvokeCacheKey { public object Target{get;set;} public object Func{get;set;} } }
 using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } }
Remove caching of invoked expressions as it is hard to do and adds little benefit
Remove caching of invoked expressions as it is hard to do and adds little benefit
C#
mit
ccoton/MFlow,ccoton/MFlow,ccoton/MFlow
ba32cc21d92bed02a0b08c16d8a8131c7e57ec53
SSMScripter/Scripter/Smo/SmoObjectMetadata.cs
SSMScripter/Scripter/Smo/SmoObjectMetadata.cs
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Schema = schema; Name = name; } } }
using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Type = type; Schema = schema; Name = name; ParentSchema = parentSchema; ParentName = parentName; } } }
Add missing ctor field initializations
Add missing ctor field initializations
C#
mit
mkoscielniak/SSMScripter
a2fccb073d6aa0b636b0f4b63fae22182d91930d
SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml
SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Comment</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; ViewBag.Message = "Comment"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="container"> <h2>@ViewBag.Title</h2> <h4>@ViewBag.Message</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10" style="margin-top: 10px"> <input type="submit" value="Save" class="btn btn-success" /> @Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" }) </div> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Change div class and change the position of button back
Change div class and change the position of button back
C#
mit
Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog
0263707a5971a00bfd23b9d0a70c0b1afd44f63b
tests/YouTrackSharp.Tests/Integration/Issues/GetIssuesInProject.cs
tests/YouTrackSharp.Tests/Integration/Issues/GetIssuesInProject.cs
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); Assert.Collection(result, issue => Assert.Equal("DP1", ((dynamic)issue).ProjectShortName)); } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); foreach (dynamic issue in result) { Assert.Equal("DP1", issue.ProjectShortName); } } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }
Change assertion to support multiple issues in test
Change assertion to support multiple issues in test
C#
apache-2.0
JetBrains/YouTrackSharp,JetBrains/YouTrackSharp
244f8289c8501f16d306c156be724a831ac651d8
src/Glimpse.Host.Web.AspNet/GlimpseExtension.cs
src/Glimpse.Host.Web.AspNet/GlimpseExtension.cs
 using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } } }
 using Glimpse.Web; using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app, Func<IHttpContext, bool> shouldRun) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices, shouldRun).Invoke); } } }
Update aspnet middleware extension message to allow shouldRun to be passed in
Update aspnet middleware extension message to allow shouldRun to be passed in
C#
mit
Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
0e99f212146096d953d93a7f9230888055e3b3ac
MbCacheTest/Logic/Concurrency/SimultaneousCachePutTest.cs
MbCacheTest/Logic/Concurrency/SimultaneousCachePutTest.cs
using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 10.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }
using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 1000.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }
Make sure test fails more often if locks are removed
Make sure test fails more often if locks are removed
C#
mit
RogerKratz/mbcache
9588cf302179f60a5ad81430caac0523d0509f0c
Telerik.JustMock.MSTest2.Tests/Properties/AssemblyInfo.cs
Telerik.JustMock.MSTest2.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if LITE_EDITION [assembly: InternalsVisibleTo("Telerik.JustMock")] #endif
Make internals in MSTest2 visible for JustMock dll in lite version
Make internals in MSTest2 visible for JustMock dll in lite version
C#
apache-2.0
telerik/JustMockLite
af5d06384ece596659efb6db4ee71a8dfb9e7024
src/Fixie.Tests/TestExtensions.cs
src/Fixie.Tests/TestExtensions.cs
namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }
namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }
Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core.
Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core.
C#
mit
fixie/fixie
86ca19686bd40a184ad322d705fdb0d2bda88f17
MultiMiner.Win/ApplicationConfiguration.cs
MultiMiner.Win/ApplicationConfiguration.cs
using MultiMiner.Engine.Configuration; using System; using System.IO; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } }
using Microsoft.Win32; using MultiMiner.Engine.Configuration; using System; using System.IO; using System.Windows.Forms; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); ApplyLaunchOnWindowsStartup(); } private void ApplyLaunchOnWindowsStartup() { RegistryKey registrykey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (LaunchOnWindowsLogin) registrykey.SetValue("MultiMiner", Application.ExecutablePath); else registrykey.DeleteValue("MultiMiner", false); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } }
Implement the option to start the app when logging into Windows
Implement the option to start the app when logging into Windows
C#
mit
IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner
656cf0725ad22da1da3a7a39350d8ee928394dad
Battlezeppelins/Models/PlayerTable/GameTable.cs
Battlezeppelins/Models/PlayerTable/GameTable.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable() { } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } }
Add non-args constructor for serialization.
Add non-args constructor for serialization.
C#
apache-2.0
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
a34e407999b381770bfe5a98c75758c461ec903d
tests/NBench.VisualStudio.TestAdapter.Tests.Unit/NBenchTestDiscoverer/NBenchTestDiscoverer/WhenTheNBenchFunctionalityWRapperIsNotNull.cs
tests/NBench.VisualStudio.TestAdapter.Tests.Unit/NBenchTestDiscoverer/NBenchTestDiscoverer/WhenTheNBenchFunctionalityWRapperIsNotNull.cs
namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = null; } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }
namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = this.Fixture.Create<INBenchFunctionalityWrapper>(); } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }
Create a non-null functionality wrapper in the required test.
Create a non-null functionality wrapper in the required test.
C#
apache-2.0
SeanFarrow/NBench.VisualStudio
6dd0479fd1dd5a3fd39dbe45fcede1ee42babc0f
FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs
FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs
using System; using System.Diagnostics; using System.Reflection; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Security.Principal; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } public static bool IsAdmin() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public static IEnumerable<Process> GetAllProcesses() { Process[] processlist = Process.GetProcesses(); return processlist.ToList(); } public static bool IsProcessRunningById(Process process) { try { Process.GetProcessById(process.Id); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static bool IsProcessRunningByName(string processName) { try { Process.GetProcessesByName(processName); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static Process GetProcessByName(string processName) { Process result = new Process(); foreach (Process process in GetAllProcesses()) { if (process.ProcessName == processName) { result = process; break; } } return result; } } }
Add several methods for Windows: IsAdmin
Add several methods for Windows: IsAdmin
C#
mit
fredatgithub/UsefulFunctions
5a89383ed6005d90ecd486fc7de9cdb4c87d9304
OutlookMatters.Core.Test/Settings/EnumMatchToBooleanConverterTest.cs
OutlookMatters.Core.Test/Settings/EnumMatchToBooleanConverterTest.cs
using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } }
using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } [Test] [TestCase(true, "ApiVersionOne", MattermostVersion.ApiVersionOne)] [TestCase(false, "ApiVersionOne", null)] [TestCase(true, null, null)] [TestCase(null, "ApiVersionOne", null)] public void ConvertBack_ConvertsToExpectedResult(object value, object parameter, object expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.ConvertBack(value, typeof(MattermostVersion), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } }
Add additional tests for EnumMatchToBooleanConverter
Add additional tests for EnumMatchToBooleanConverter
C#
mit
maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters,makmu/outlook-matters
2bc17f2941863312957adbd1ee5f19b59056b2b3
ChutesAndLaddersDemo/Simulation/Chute/Program.cs
ChutesAndLaddersDemo/Simulation/Chute/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 // board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); board.GameActionOutput_SmallSample(); #endregion } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); // board.GameActionOutput_SmallSample(); #endregion } } }
Reset Chutes & Ladders demos to run demo 1 by default
Reset Chutes & Ladders demos to run demo 1 by default
C#
mit
bsstahl/AIDemos,bsstahl/AIDemos
1890e818f910c35e530150701c34141c9ea02088
Dexiom.EPPlusExporterTests/Helpers/TestHelper.cs
Dexiom.EPPlusExporterTests/Helpers/TestHelper.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bogus; using Dexiom.EPPlusExporter; using OfficeOpenXml; namespace Dexiom.EPPlusExporterTests.Helpers { public static class TestHelper { public static void OpenDocument(ExcelPackage excelPackage) { Console.WriteLine("Opening document"); Directory.CreateDirectory("temp"); var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx"); excelPackage.SaveAs(fileInfo); Process.Start(fileInfo.FullName); } public static ExcelPackage FakeAnExistingDocument() { Console.WriteLine("FakeAnExistingDocument"); var retVal = new ExcelPackage(); var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet"); worksheet.Cells[1, 1].Value = "I am a normal sheet"; worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!"; return retVal; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bogus; using Dexiom.EPPlusExporter; using OfficeOpenXml; namespace Dexiom.EPPlusExporterTests.Helpers { public static class TestHelper { public static void OpenDocument(ExcelPackage excelPackage) { Console.WriteLine("Opening document"); Directory.CreateDirectory("temp"); var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx"); excelPackage.SaveAs(fileInfo); Process.Start(fileInfo.FullName); } public static ExcelPackage FakeAnExistingDocument() { var retVal = new ExcelPackage(); var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet"); worksheet.Cells[1, 1].Value = "I am a normal sheet"; worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!"; return retVal; } } }
Remove output on some tests
Remove output on some tests
C#
mit
Dexiom/Dexiom.EPPlusExporter
af129b3eaba1233654e87b6de4185876933ba033
osu.Game.Rulesets.Mania/Objects/ManiaHitObject.cs
osu.Game.Rulesets.Mania/Objects/ManiaHitObject.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Mania.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mania.Objects { public abstract class ManiaHitObject : HitObject, IHasColumn { public int Column { get; set; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Mania.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mania.Objects { public abstract class ManiaHitObject : HitObject, IHasColumn { public int Column { get; set; } /// <summary> /// The number of other <see cref="ManiaHitObject"/> that start at /// the same time as this hit object. /// </summary> public int Siblings { get; set; } } }
Add siblings, will be used in generator branches.
Add siblings, will be used in generator branches.
C#
mit
osu-RP/osu-RP,DrabWeb/osu,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,smoogipooo/osu,Frontear/osuKyzer,naoey/osu,ZLima12/osu,peppy/osu-new,Nabile-Rahmani/osu,ppy/osu,DrabWeb/osu,DrabWeb/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,Damnae/osu,UselessToucan/osu,UselessToucan/osu,naoey/osu,ppy/osu,naoey/osu,tacchinotacchi/osu,peppy/osu,peppy/osu,Drezi126/osu,peppy/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu
76314fe193306f89b762d12657f57dd9f4748eab
LtiLibrary.Core/Outcomes/v2/LineItemContainer.cs
LtiLibrary.Core/Outcomes/v2/LineItemContainer.cs
using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject LineItemMembershipSubject { get; set; } } }
using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject MembershipSubject { get; set; } } }
Simplify property name for LineItemMembershipSubject
Simplify property name for LineItemMembershipSubject
C#
apache-2.0
andyfmiller/LtiLibrary
a93b22803dfb1384bb7055f0798b0f55f5212985
src/Nest/Domain/Responses/SearchShardsResponse.cs
src/Nest/Domain/Responses/SearchShardsResponse.cs
using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }
using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }
Fix wrong property mapping in SearchShard
Fix wrong property mapping in SearchShard
C#
apache-2.0
KodrAus/elasticsearch-net,RossLieberman/NEST,starckgates/elasticsearch-net,gayancc/elasticsearch-net,amyzheng424/elasticsearch-net,CSGOpenSource/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,ststeiger/elasticsearch-net,DavidSSL/elasticsearch-net,jonyadamit/elasticsearch-net,DavidSSL/elasticsearch-net,UdiBen/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net,faisal00813/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,elastic/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,tkirill/elasticsearch-net,LeoYao/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,junlapong/elasticsearch-net,mac2000/elasticsearch-net,tkirill/elasticsearch-net,robrich/elasticsearch-net,KodrAus/elasticsearch-net,joehmchan/elasticsearch-net,robrich/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,wawrzyn/elasticsearch-net,starckgates/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,junlapong/elasticsearch-net,UdiBen/elasticsearch-net,faisal00813/elasticsearch-net,SeanKilleen/elasticsearch-net,TheFireCookie/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,amyzheng424/elasticsearch-net,LeoYao/elasticsearch-net,ststeiger/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,ststeiger/elasticsearch-net,tkirill/elasticsearch-net,elastic/elasticsearch-net,SeanKilleen/elasticsearch-net,KodrAus/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,geofeedia/elasticsearch-net
190d0522fc1180f260608cbe99529c9836b53b78
src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Filesystem/FilesystemQueries.cs
src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Filesystem/FilesystemQueries.cs
using HotChocolate.Types; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>().Description("The path to explore.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null) return DriveInfo.GetDrives(); if (path.Exists) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } }
using HotChocolate.Types; using Microsoft.DotNet.PlatformAbstractions; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>() .Description("The path to explore. If this is null, returns a listing of drives on Windows, " + "or the root directory on a Unix-like system.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return DriveInfo.GetDrives(); if (path == null && (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return new DirectoryInfo("/"); if (path?.Exists ?? false) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } }
Clarify behaviour on non-Windows systems
HC.filesystem: Clarify behaviour on non-Windows systems
C#
mpl-2.0
SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake
f8802b3778ba30219b7415ed7037a2b8f419782c
Tiny-JSON/Tiny-JSON/AssemblyInfo.cs
Tiny-JSON/Tiny-JSON/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.1.2")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.2.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
Increase assembly version to 1.2.0
Increase assembly version to 1.2.0
C#
mit
gering/Tiny-JSON
5c8511e3c01e3a7183a00ad1d04db4ea9e122bac
Utility/Extensions/ConcurrentDictionaryExtensions.cs
Utility/Extensions/ConcurrentDictionaryExtensions.cs
using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// This is a hack but is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can (not 100%!) /// </remarks> public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value) { ICollection<KeyValuePair<TKey, TValue>> collection = dictionary; return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } }
using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// HACK: is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can. /// </remarks> public static bool TryRemove<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value) { return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } }
Change try remove key pair method semantics
Change try remove key pair method semantics
C#
mit
Ben-Barron/Utility
6c928ace917c525c84b685fdc27df48679337f2a
IdeaWeb.Test/Controllers/HomeControllerTests.cs
IdeaWeb.Test/Controllers/HomeControllerTests.cs
using IdeaWeb.Controllers; using Microsoft.AspNetCore.Mvc; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { HomeController _controller; [SetUp] public void SetUp() { _controller = new HomeController(); } [Test] public void IndexReturnsIdeasView() { IActionResult result = _controller.Index(); Assert.That(result, Is.Not.Null); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdeaWeb.Controllers; using IdeaWeb.Data; using IdeaWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { const int NUM_IDEAS = 10; HomeController _controller; [SetUp] public void SetUp() { // Create unique database names based on the test id var options = new DbContextOptionsBuilder<IdeaContext>() .UseInMemoryDatabase(TestContext.CurrentContext.Test.ID) .Options; // Seed the in-memory database using (var context = new IdeaContext(options)) { for(int i = 1; i <= NUM_IDEAS; i++) { context.Add(new Idea { Name = $"Idea name {i}", Description = $"Description {i}", Rating = i % 3 + 1 }); } context.SaveChanges(); } // Use a clean copy of the context within the tests _controller = new HomeController(new IdeaContext(options)); } [Test] public async Task IndexReturnsListOfIdeas() { ViewResult result = await _controller.Index() as ViewResult; Assert.That(result?.Model, Is.Not.Null); Assert.That(result.Model, Has.Count.EqualTo(NUM_IDEAS)); IEnumerable<Idea> ideas = result.Model as IEnumerable<Idea>; Idea idea = ideas?.FirstOrDefault(); Assert.That(idea, Is.Not.Null); Assert.That(idea.Name, Is.EqualTo("Idea name 1")); Assert.That(idea.Description, Does.Contain("1")); Assert.That(idea.Rating, Is.EqualTo(2)); } } }
Use the in-memory database for testing the home controller
Use the in-memory database for testing the home controller
C#
mit
rprouse/IdeaWeb,rprouse/IdeaWeb
4a263e12ffee4de8bade20184193f3f08e05cdff
src/DependencyInjection.Console/PatternApp.cs
src/DependencyInjection.Console/PatternApp.cs
namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(10, 10); _patternWriter.Write(pattern); } } }
namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(25, 15); _patternWriter.Write(pattern); } } }
Adjust initial size to look nicer
Adjust initial size to look nicer
C#
mit
jcrang/dependency-injection-kata-series,mjac/dependency-injection-kata-series
5c6aed889194147895c53baa910e057990a26fd5
src/EmotionAPI.Tests/EmotionAPIClientTests.cs
src/EmotionAPI.Tests/EmotionAPIClientTests.cs
using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Controller() { var controller = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(controller); Assert.NotEmpty(controller.OcpApimSubscriptionKey); } } }
using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Class() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(sut); } [Fact] public void OcpApimSubscriptionKey_Is_Being_Set() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotEmpty(sut.OcpApimSubscriptionKey); } } }
Split test into two separate tests
Split test into two separate tests
C#
mit
Felsig/Emotion-API