commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
4813bb47f72d556a0512eab18e65df4b7fa6cd15 | fix crash on twitch connector | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/TwitchConnector.cs | TCC.Core/TwitchConnector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.ViewModels;
using TwitchLib;
using TwitchLib.Models.Client;
namespace TCC
{
public class TwitchConnector
{
private static TwitchConnector _instance;
public static TwitchConnector Instance => _instance ?? (_instance = new TwitchConnector());
private TwitchClient client;
private ConnectionCredentials cred;
private void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
{
var msg = new TCC.Data.ChatMessage(ChatChannel.Twitch, e.ChatMessage.Username, "<FONT>" + e.ChatMessage.Message + "</FONT>");
ChatWindowViewModel.Instance.AddChatMessage(msg);
}
public void Init()
{
if (string.IsNullOrEmpty(SettingsManager.TwitchToken) ||
string.IsNullOrEmpty(SettingsManager.TwitchName) ||
string.IsNullOrEmpty(SettingsManager.TwitchChannelName)) return;
if (SettingsManager.TwitchName.Length < 4) return;
cred = new ConnectionCredentials(SettingsManager.TwitchName, SettingsManager.TwitchToken);
client = new TwitchClient(cred, SettingsManager.TwitchChannelName);
client.OnMessageReceived += Client_OnMessageReceived;
client.OnDisconnected += Client_OnDisconnected;
client.Connect();
}
private void Client_OnDisconnected(object sender, TwitchLib.Events.Client.OnDisconnectedArgs e)
{
try
{
client.Connect();
}
catch
{
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.ViewModels;
using TwitchLib;
using TwitchLib.Models.Client;
namespace TCC
{
public class TwitchConnector
{
private static TwitchConnector _instance;
public static TwitchConnector Instance => _instance ?? (_instance = new TwitchConnector());
private TwitchClient client;
private ConnectionCredentials cred;
private void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
{
var msg = new TCC.Data.ChatMessage(ChatChannel.Twitch, e.ChatMessage.Username, "<FONT>" + e.ChatMessage.Message + "</FONT>");
ChatWindowViewModel.Instance.AddChatMessage(msg);
}
public void Init()
{
if (string.IsNullOrEmpty(SettingsManager.TwitchToken) ||
string.IsNullOrEmpty(SettingsManager.TwitchName) ||
string.IsNullOrEmpty(SettingsManager.TwitchChannelName)) return;
if (SettingsManager.TwitchName.Length < 4) return;
cred = new ConnectionCredentials(SettingsManager.TwitchName, SettingsManager.TwitchToken);
client = new TwitchClient(cred, SettingsManager.TwitchChannelName);
client.OnMessageReceived += Client_OnMessageReceived;
client.OnDisconnected += Client_OnDisconnected;
client.Connect();
}
private void Client_OnDisconnected(object sender, TwitchLib.Events.Client.OnDisconnectedArgs e)
{
client.Connect();
}
}
}
| mit | C# |
0c3c93959e00d3903ef20844892bb3fa8998d14c | Add IssueMethodsTest class | ats124/backlog4net | src/Backlog4net.Test/IssueMethodsTest.cs | src/Backlog4net.Test/IssueMethodsTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Backlog4net.Test
{
using Api;
using Api.Option;
using Conf;
using TestConfig;
[TestClass]
public class IssueMethodsTest
{
private static BacklogClient client;
private static GeneralConfig generalConfig;
private static object projectId;
private static IList<IssueType> issueTypes;
[ClassInitialize]
public static async Task SetupClient(TestContext context)
{
generalConfig = GeneralConfig.Instance.Value;
var conf = new BacklogJpConfigure(generalConfig.SpaceKey);
conf.ApiKey = generalConfig.ApiKey;
client = new BacklogClientFactory(conf).NewClient();
var project = await client.GetProjectAsync(generalConfig.ProjectKey);
projectId = project.Id;
issueTypes = await client.GetIssueTypesAsync(projectId);
}
[TestMethod]
public async Task IssuesAsyncTest()
{
}
}
}
| //using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Microsoft.VisualStudio.TestTools.UnitTesting;
//namespace Backlog4net.Test
//{
// using Api;
// using Api.Option;
// using Conf;
// using TestConfig;
// [TestClass]
// public class IssueMethodsTest
// {
// private static BacklogClient client;
// private static GeneralConfig generalConfig;
// private static object projectId;
// private static IList<IssueType> issueTypes;
// [ClassInitialize]
// public static async Task SetupClient(TestContext context)
// {
// generalConfig = GeneralConfig.Instance.Value;
// var conf = new BacklogJpConfigure(generalConfig.SpaceKey);
// conf.ApiKey = generalConfig.ApiKey;
// client = new BacklogClientFactory(conf).NewClient();
// var project = await client.GetProjectAsync(generalConfig.ProjectKey);
// projectId = project.Id;
// issueTypes = await client.GetIssueTypesAsync(projectId);
// }
// [TestMethod]
// public async Task GetIssuesCountAsync()
// {
// var count = await client.GetIssuesCountAsync(new GetIssuesCountParams(55947));
// Assert.IsTrue(count > 0);
// }
// //[TestMethod]
// //public async Task AddUpdateGetDeleteIssueAsync()
// //{
// // var createParams = new CreateIssueParams(projectId, "summary-test", issueTypes.First(), IssuePriorityType.High)
// // {
// // };
// //}
// }
//}
| mit | C# |
9529ba649f86891cb87545c2d2850908a05bdd14 | Use overloads instead of optional parameters | jamesfoster/DeepEqual | src/DeepEqual/Syntax/ObjectExtensions.cs | src/DeepEqual/Syntax/ObjectExtensions.cs | namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected)
{
return IsDeepEqual(actual, expected, null);
}
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result != ComparisonResult.Fail;
}
public static void ShouldDeepEqual(this object actual, object expected)
{
ShouldDeepEqual(actual, expected, null);
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
throw new DeepEqualException(context);
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
} | namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison = null)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result != ComparisonResult.Fail;
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison = null)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
throw new DeepEqualException(context);
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
} | mit | C# |
9f7ff73417ab7164e3e001ce1979e764fd998522 | Update HarmVeenstra.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/HarmVeenstra.cs | src/Firehose.Web/Authors/HarmVeenstra.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class HarmVeenstra : IAmACommunityMember
{
public string FirstName => "Harm";
public string LastName => "Veenstra";
public string ShortBioOrTagLine => "Cloud Consultant at NEXXT (Https://www.nexxt.one)";
public string StateOrRegion => "Overijssel";
public string EmailAddress => "harm.veenstra@gmail.com";
public string TwitterHandle => "HarmVeenstra";
public string GravatarHash => "432c4a0a81ea2b900a6d654452002964";
public string GitHubHandle => "HarmVeenstra";
public GeoPosition Position => new GeoPosition(52.786708, 6.116538);
public Uri WebSite => new Uri("https://powershellisfun.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://powershellisfun.com//feed/"); }
}
public string FeedLanguageCode => "en";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class HarmVeenstra : IAmACommunityMember
{
public string FirstName => "Harm";
public string LastName => "Veenstra";
public string ShortBioOrTagLine => "Cloud Consultant at NEXXT (Https://www.nexxt.one)";
public string StateOrRegion => "Overijssel";
public string EmailAddress => "harm.veenstra@gmail.com";
public string TwitterHandle => "HarmVeenstra";
public string GravatarHash => "432c4a0a81ea2b900a6d654452002964";
public string GitHubHandle => "HarmVeenstra";
public GeoPosition Position => new GeoPosition(52.786708, 6.116538);
public Uri WebSite => new Uri("https://powershellisfun.com/");public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://powershellisfun.com//feed/"); }
}
public string FeedLanguageCode => "en";
}
}
| mit | C# |
b0fb28dd4ebfbf9ce9052cf9a6c0f0d85c87284c | Make tests use console log handler | bizcad/LeanJJN,kaffeebrauer/Lean,bdilber/Lean,FrancisGauthier/Lean,JKarathiya/Lean,Obawoba/Lean,dalebrubaker/Lean,bizcad/LeanAbhi,florentchandelier/Lean,florentchandelier/Lean,iamkingmaker/Lean,AnObfuscator/Lean,bizcad/LeanITrend,desimonk/Lean,QuantConnect/Lean,Phoenix1271/Lean,bizcad/LeanITrend,AlexCatarino/Lean,tomhunter-gh/Lean,AnObfuscator/Lean,exhau/Lean,Mendelone/forex_trading,Phoenix1271/Lean,QuantConnect/Lean,bizcad/Lean,dalebrubaker/Lean,bizcad/Lean,tomhunter-gh/Lean,Jay-Jay-D/LeanSTP,Neoracle/Lean,Phoenix1271/Lean,mabeale/Lean,AnshulYADAV007/Lean,StefanoRaggi/Lean,dalebrubaker/Lean,rchien/Lean,dpavlenkov/Lean,racksen/Lean,bizcad/LeanAbhi,wowgeeker/Lean,FrancisGauthier/Lean,Jay-Jay-D/LeanSTP,Obawoba/Lean,bizcad/LeanAbhi,florentchandelier/Lean,AnshulYADAV007/Lean,iamkingmaker/Lean,bizcad/Lean,racksen/Lean,young-zhang/Lean,StefanoRaggi/Lean,desimonk/Lean,iamkingmaker/Lean,young-zhang/Lean,Jay-Jay-D/LeanSTP,tzaavi/Lean,tzaavi/Lean,Neoracle/Lean,tzaavi/Lean,Mendelone/forex_trading,AnshulYADAV007/Lean,Neoracle/Lean,dpavlenkov/Lean,racksen/Lean,devalkeralia/Lean,kaffeebrauer/Lean,squideyes/Lean,bdilber/Lean,jameschch/Lean,tomhunter-gh/Lean,squideyes/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,wowgeeker/Lean,Phoenix1271/Lean,exhau/Lean,young-zhang/Lean,JKarathiya/Lean,AnObfuscator/Lean,bizcad/LeanJJN,rchien/Lean,FrancisGauthier/Lean,StefanoRaggi/Lean,mabeale/Lean,devalkeralia/Lean,bizcad/LeanAbhi,jameschch/Lean,bizcad/LeanITrend,AnshulYADAV007/Lean,StefanoRaggi/Lean,bdilber/Lean,Mendelone/forex_trading,tzaavi/Lean,Neoracle/Lean,AnshulYADAV007/Lean,bizcad/LeanITrend,Mendelone/forex_trading,dpavlenkov/Lean,AlexCatarino/Lean,andrewhart098/Lean,JKarathiya/Lean,andrewhart098/Lean,kaffeebrauer/Lean,andrewhart098/Lean,exhau/Lean,rchien/Lean,Obawoba/Lean,jameschch/Lean,dpavlenkov/Lean,rchien/Lean,tomhunter-gh/Lean,mabeale/Lean,exhau/Lean,squideyes/Lean,wowgeeker/Lean,devalkeralia/Lean,AlexCatarino/Lean,kaffeebrauer/Lean,redmeros/Lean,bizcad/LeanJJN,desimonk/Lean,QuantConnect/Lean,QuantConnect/Lean,iamkingmaker/Lean,bizcad/Lean,FrancisGauthier/Lean,jameschch/Lean,devalkeralia/Lean,JKarathiya/Lean,AnObfuscator/Lean,wowgeeker/Lean,bizcad/LeanJJN,redmeros/Lean,jameschch/Lean,bdilber/Lean,racksen/Lean,andrewhart098/Lean,squideyes/Lean,florentchandelier/Lean,mabeale/Lean,dalebrubaker/Lean,redmeros/Lean,young-zhang/Lean,kaffeebrauer/Lean,Obawoba/Lean,Jay-Jay-D/LeanSTP,redmeros/Lean,desimonk/Lean,AlexCatarino/Lean | Tests/AssemblyInitialize.cs | Tests/AssemblyInitialize.cs | using NUnit.Framework;
using QuantConnect.Logging;
[SetUpFixture]
public class AssemblyInitialize
{
[SetUp]
public void SetLogHandler()
{
// save output to file as well
Log.LogHandler = new ConsoleLogHandler();
}
}
| using NUnit.Framework;
using QuantConnect.Logging;
[SetUpFixture]
public class AssemblyInitialize
{
[SetUp]
public void SetLogHandler()
{
// save output to file as well
Log.LogHandler = new CompositeLogHandler();
}
}
| apache-2.0 | C# |
a50c1c5a2a892f3b003b4e57dd09f3fa70fccd7c | Bump version to 0.30.4 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.30.4";
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.30.3";
}
}
| mit | C# |
754fca043b709e22e4152d0d09815f47f5e9e446 | Update version | akordowski/Cake.Compression,akordowski/Cake.Compression | src/Cake.Compression/Properties/AssemblyInfo.cs | src/Cake.Compression/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Cake.Compression")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.Compression")]
[assembly: AssemblyCopyright("Copyright (c) 2016 Artur Kordowski")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("dfce574d-731a-4c89-9b74-9ff2a93ed966")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.2.0")]
[assembly: AssemblyFileVersion("0.1.2.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Cake.Compression")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.Compression")]
[assembly: AssemblyCopyright("Copyright (c) 2016 Artur Kordowski")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("dfce574d-731a-4c89-9b74-9ff2a93ed966")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
| mit | C# |
c88947bdcf04063d695a4531f0055a8dfd5770b0 | support array parameter data type | sebastianhoffmann/querybuilder | src/Deviax.QueryBuilder.Postgres/UnnestTable.cs | src/Deviax.QueryBuilder.Postgres/UnnestTable.cs | using System;
using System.Collections.Generic;
using Deviax.QueryBuilder.Parts;
using Deviax.QueryBuilder.Visitors;
using NpgsqlTypes;
namespace Deviax.QueryBuilder
{
public class UnnestTable : Table
{
public UnnestTable(string alias) : base(null, null, alias) { }
internal List<IParameter> Parameters = new List<IParameter>();
public Field Field<T>(IEnumerable<T> i, NpgsqlDbType npgsqlDbType = NpgsqlDbType.Unknown)
{
var name = $"unest_{Parameters.Count}";
if(npgsqlDbType != NpgsqlDbType.Unknown)
Parameters.Add(new ArrayParameter<T>(i, name, npgsqlDbType));
else
Parameters.Add(new ArrayParameter<T>(i, name));
return new Field(this,name);
}
public override void Accept(INodeVisitor visitor)
{
visitor.Visit(this);
}
}
} | using System.Collections.Generic;
using Deviax.QueryBuilder.Parts;
using Deviax.QueryBuilder.Visitors;
namespace Deviax.QueryBuilder
{
public class UnnestTable : Table
{
public UnnestTable(string alias) : base(null, null, alias) { }
internal List<IParameter> Parameters = new List<IParameter>();
public Field Field<T>(IEnumerable<T> i)
{
var name = $"unest_{Parameters.Count}";
Parameters.Add(new ArrayParameter<T>(i, name));
return new Field(this,name);
}
public override void Accept(INodeVisitor visitor)
{
visitor.Visit(this);
}
}
} | mit | C# |
aa91087cecac6fafba0ef2730b319f43a7684c12 | fix after merge | Elders/Cronus,Elders/Cronus | src/Elders.Cronus/InMemory/InMemoryPublisher.cs | src/Elders.Cronus/InMemory/InMemoryPublisher.cs | using Elders.Cronus.Logging;
using Elders.Cronus.MessageProcessing;
using Elders.Cronus.Multitenancy;
namespace Elders.Cronus.InMemory
{
public class InMemoryPublisher<TContract> : Publisher<TContract> where TContract : IMessage
{
static readonly ILog log = LogProvider.GetLogger(typeof(InMemoryPublisher<>));
private readonly SubscriberCollection<IApplicationService> subscribtions;
private readonly InMemoryQueue messageQueue;
public InMemoryPublisher(SubscriberCollection<IApplicationService> messageProcessor, InMemoryQueue messageQueue)
: base(new DefaultTenantResolver())
{
this.subscribtions = messageProcessor;
this.messageQueue = messageQueue;
}
protected override bool PublishInternal(CronusMessage message)
{
messageQueue.Publish(message);
return true;
}
}
}
| using Elders.Cronus.Logging;
using Elders.Cronus.MessageProcessing;
using Elders.Cronus.Multitenancy;
namespace Elders.Cronus.InMemory
{
public class InMemoryPublisher<TContract> : Publisher<TContract> where TContract : IMessage
{
static readonly ILog log = LogProvider.GetLogger(typeof(InMemoryPublisher<>));
<<<<<<< Updated upstream
public InMemoryPublisher(SubscriberCollection<object> messageProcessor)
=======
private readonly SubscriberCollection<IApplicationService> subscribtions;
private readonly InMemoryQueue messageQueue;
public InMemoryPublisher(SubscriberCollection<IApplicationService> messageProcessor, InMemoryQueue messageQueue)
: base(new DefaultTenantResolver())
>>>>>>> Stashed changes
{
this.subscribtions = messageProcessor;
this.messageQueue = messageQueue;
}
protected override bool PublishInternal(CronusMessage message)
{
messageQueue.Publish(message);
return true;
}
}
}
| apache-2.0 | C# |
ac1d79dc47d51d8f6a1c07e33726f0674aa56659 | Check line ending fix | AntyaDev/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,mhertis/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,AntyaDev/Orleankka,mhertis/Orleankka,pkese/Orleankka,pkese/Orleankka | Source/Demo.App/ServiceLocator.cs | Source/Demo.App/ServiceLocator.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleankka.Cluster;
namespace Demo
{
public static class ServiceLocator
{
public static ITopicStorage TopicStorage
{
get; private set;
}
public class Bootstrap : Bootstrapper<IDictionary<string, string>>
{
static bool done;
protected override async Task Run(IDictionary<string, string> properties)
{
if (done)
throw new InvalidOperationException("Already done");
TopicStorage = await Demo.TopicStorage.Init(properties["account"]);
done = true;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleankka.Cluster;
namespace Demo
{
public static class ServiceLocator
{
public static ITopicStorage TopicStorage
{
get; private set;
}
public class Bootstrap : Bootstrapper<IDictionary<string, string>>
{
static bool done;
protected override async Task Run(IDictionary<string, string> properties)
{
if (done)
throw new InvalidOperationException("Already done");
TopicStorage = await Demo.TopicStorage.Init(properties["account"]);
done = true;
}
}
}
} | apache-2.0 | C# |
d20cada6f8d16b61682c707ad32fa1fbf4ef813e | Fix incorrect type passed into the xml serializer for CheckinEventService | timclipsham/tfs-hipchat | TfsHipChat/CheckinEventService.cs | TfsHipChat/CheckinEventService.cs | using System.IO;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.VersionControl.Common;
namespace TfsHipChat
{
public class CheckinEventService : IEventService
{
private INotifier _notifier;
public CheckinEventService()
{
}
public CheckinEventService(INotifier notifier)
{
this._notifier = notifier;
}
public void Notify(string eventXml, string tfsIdentityXml)
{
var serializer = new XmlSerializer(typeof(CheckinEvent));
CheckinEvent checkinEvent;
using (var reader = new StringReader(eventXml))
{
checkinEvent = serializer.Deserialize(reader) as CheckinEvent; // double check "TryCast"...
}
if (checkinEvent == null)
{
return;
}
// check whether the changeset has policy failures
if (checkinEvent.PolicyFailures.Count > 0)
{
}
}
}
}
| using System.IO;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.VersionControl.Common;
namespace TfsHipChat
{
public class CheckinEventService : IEventService
{
private INotifier _notifier;
public CheckinEventService()
{
}
public CheckinEventService(INotifier notifier)
{
this._notifier = notifier;
}
public void Notify(string eventXml, string tfsIdentityXml)
{
var serializer = new XmlSerializer(typeof(CheckinEventService));
CheckinEvent checkinEvent;
using (var reader = new StringReader(eventXml))
{
checkinEvent = serializer.Deserialize(reader) as CheckinEvent; // double check "TryCast"...
}
if (checkinEvent == null)
{
return;
}
// check whether the changeset has policy failures
if (checkinEvent.PolicyFailures.Count > 0)
{
}
}
}
}
| mit | C# |
a181622aab3d0650626279473a0a214ffb63d268 | Allow selection of multiple folders (BGO#586946) | allquixotic/banshee-gst-sharp-work,mono-soc-2011/banshee,Dynalon/banshee-osx,Dynalon/banshee-osx,Dynalon/banshee-osx,arfbtwn/banshee,mono-soc-2011/banshee,stsundermann/banshee,Carbenium/banshee,allquixotic/banshee-gst-sharp-work,GNOME/banshee,mono-soc-2011/banshee,directhex/banshee-hacks,petejohanson/banshee,petejohanson/banshee,eeejay/banshee,arfbtwn/banshee,GNOME/banshee,directhex/banshee-hacks,Carbenium/banshee,babycaseny/banshee,dufoli/banshee,lamalex/Banshee,GNOME/banshee,GNOME/banshee,directhex/banshee-hacks,stsundermann/banshee,Dynalon/banshee-osx,Carbenium/banshee,eeejay/banshee,mono-soc-2011/banshee,dufoli/banshee,arfbtwn/banshee,ixfalia/banshee,Carbenium/banshee,petejohanson/banshee,arfbtwn/banshee,GNOME/banshee,mono-soc-2011/banshee,stsundermann/banshee,dufoli/banshee,petejohanson/banshee,Carbenium/banshee,GNOME/banshee,GNOME/banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,babycaseny/banshee,petejohanson/banshee,mono-soc-2011/banshee,eeejay/banshee,GNOME/banshee,ixfalia/banshee,stsundermann/banshee,stsundermann/banshee,babycaseny/banshee,Dynalon/banshee-osx,Dynalon/banshee-osx,dufoli/banshee,Carbenium/banshee,arfbtwn/banshee,directhex/banshee-hacks,babycaseny/banshee,stsundermann/banshee,eeejay/banshee,babycaseny/banshee,lamalex/Banshee,allquixotic/banshee-gst-sharp-work,lamalex/Banshee,arfbtwn/banshee,ixfalia/banshee,ixfalia/banshee,babycaseny/banshee,Dynalon/banshee-osx,stsundermann/banshee,lamalex/Banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,ixfalia/banshee,arfbtwn/banshee,ixfalia/banshee,mono-soc-2011/banshee,dufoli/banshee,arfbtwn/banshee,ixfalia/banshee,eeejay/banshee,directhex/banshee-hacks,Dynalon/banshee-osx,lamalex/Banshee,lamalex/Banshee,ixfalia/banshee,dufoli/banshee,directhex/banshee-hacks,babycaseny/banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,petejohanson/banshee,babycaseny/banshee | src/Core/Banshee.ThickClient/Banshee.Library.Gui/FolderImportSource.cs | src/Core/Banshee.ThickClient/Banshee.Library.Gui/FolderImportSource.cs | //
// FolderImportSource.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
namespace Banshee.Library.Gui
{
public class FolderImportSource : IImportSource
{
public FolderImportSource ()
{
}
public void Import()
{
Banshee.Gui.Dialogs.FileChooserDialog chooser = new Banshee.Gui.Dialogs.FileChooserDialog (
Catalog.GetString ("Import Folder to Library"),
FileChooserAction.SelectFolder
);
chooser.AddButton (Stock.Cancel, ResponseType.Cancel);
chooser.AddButton (Stock.Open, ResponseType.Ok);
chooser.SelectMultiple = true;
chooser.DefaultResponse = ResponseType.Ok;
FileImportSource.SetChooserShortcuts (chooser);
if (chooser.Run () == (int)ResponseType.Ok) {
Banshee.ServiceStack.ServiceManager.Get<LibraryImportManager> ().Enqueue (chooser.Uris);
}
chooser.Destroy ();
}
public string Name {
get { return Catalog.GetString ("Local Folder"); }
}
public string [] IconNames {
get { return new string [] { "gtk-open" }; }
}
public bool CanImport {
get { return true; }
}
public int SortOrder {
get { return 0; }
}
}
}
| //
// FolderImportSource.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
namespace Banshee.Library.Gui
{
public class FolderImportSource : IImportSource
{
public FolderImportSource ()
{
}
public void Import()
{
Banshee.Gui.Dialogs.FileChooserDialog chooser = new Banshee.Gui.Dialogs.FileChooserDialog (
Catalog.GetString ("Import Folder to Library"),
FileChooserAction.SelectFolder
);
chooser.AddButton (Stock.Cancel, ResponseType.Cancel);
chooser.AddButton (Stock.Open, ResponseType.Ok);
chooser.DefaultResponse = ResponseType.Ok;
FileImportSource.SetChooserShortcuts (chooser);
if (chooser.Run () == (int)ResponseType.Ok) {
Banshee.ServiceStack.ServiceManager.Get<LibraryImportManager> ().Enqueue (chooser.Uri);
}
chooser.Destroy ();
}
public string Name {
get { return Catalog.GetString ("Local Folder"); }
}
public string [] IconNames {
get { return new string [] { "gtk-open" }; }
}
public bool CanImport {
get { return true; }
}
public int SortOrder {
get { return 0; }
}
}
}
| mit | C# |
ee188a0f899a0fa3a02bee60e6bfd2e4092ca877 | Fix in creating subcontainers for guilotine cut. | Ervie/PackingProblem | BinPackingProblem/Logic.Domain/Containers/2D/Guillotine/GuillotineCutContainer2D.cs | BinPackingProblem/Logic.Domain/Containers/2D/Guillotine/GuillotineCutContainer2D.cs | using Logic.Domain.Figures;
using Logic.Domain.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Logic.Domain.Containers._2D.Guillotine
{
public abstract class GuillotineCutContainer2D : Container2D
{
public GuillotineCutContainer2D(int width, int height) : base(width, height)
{
Subcontainers = new List<SubContainer2D>();
// At beginning new container is single subcontainer filling all space
CreateSubcontainer(new Position2D(0, 0), new Rectangle(Width, Height));
}
public abstract void SplitSubcontainer(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject);
protected override SubContainer2D CreateSubcontainer(Position2D position, Rectangle size)
{
GuillotineCutSubcontainer2D newSubcontainer = new GuillotineCutSubcontainer2D(position.X, position.Y, size.Width, size.Height);
Subcontainers.Add(newSubcontainer);
return newSubcontainer;
}
protected void SplitSubcontainerVertically(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject)
{
var topSubcontainerPosition = new Position2D(subcontainer.X, placedObject.Y2);
var topSubcontainerSize = new Rectangle(placedObject.Width, subcontainer.Height - placedObject.Height);
var topSubcontainer = new GuillotineCutSubcontainer2D(topSubcontainerPosition, topSubcontainerSize.Width, topSubcontainerSize.Height);
var rightSubcontainerPosition = new Position2D(placedObject.X2, subcontainer.Y);
var rightSubcontainerSize = new Rectangle(subcontainer.Width - placedObject.Width, subcontainer.Height);
var rightSubcontainer = new GuillotineCutSubcontainer2D(rightSubcontainerPosition, rightSubcontainerSize.Width, rightSubcontainerSize.Height);
// No need to add one dimensional container
if (topSubcontainer.Width != 0 && topSubcontainer.Height != 0)
Subcontainers.Add(topSubcontainer);
if (rightSubcontainer.Width != 0 && rightSubcontainer.Height != 0)
Subcontainers.Add(rightSubcontainer);
Subcontainers.Remove(subcontainer);
}
protected void SplitSubcontainerHorizontally(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject)
{
var topSubcontainerPosition = new Position2D(subcontainer.X, placedObject.Y2);
var topSubcontainerSize = new Rectangle(subcontainer.Width, subcontainer.Height - placedObject.Height);
var topSubcontainer = new GuillotineCutSubcontainer2D(topSubcontainerPosition, topSubcontainerSize.Width, topSubcontainerSize.Height);
var rightSubcontainerPosition = new Position2D(placedObject.X2, subcontainer.Y);
var rightSubcontainerSize = new Rectangle(subcontainer.Width - placedObject.Width, placedObject.Height);
var rightSubcontainer = new GuillotineCutSubcontainer2D(rightSubcontainerPosition, rightSubcontainerSize.Width, rightSubcontainerSize.Height);
// No need to add one dimensional container
if (topSubcontainer.Width != 0 && topSubcontainer.Height != 0)
Subcontainers.Add(topSubcontainer);
if (rightSubcontainer.Width != 0 && rightSubcontainer.Height != 0)
Subcontainers.Add(rightSubcontainer);
Subcontainers.Remove(subcontainer);
}
}
}
| using Logic.Domain.Figures;
using Logic.Domain.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Logic.Domain.Containers._2D.Guillotine
{
public abstract class GuillotineCutContainer2D : Container2D
{
public GuillotineCutContainer2D(int width, int height) : base(width, height)
{
Subcontainers = new List<SubContainer2D>();
// At beginning new container is single subcontainer filling all space
CreateSubcontainer(new Position2D(0, 0), new Rectangle(Width, Height));
}
public abstract void SplitSubcontainer(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject);
protected override SubContainer2D CreateSubcontainer(Position2D position, Rectangle size)
{
GuillotineCutSubcontainer2D newSubcontainer = new GuillotineCutSubcontainer2D(position.X, position.Y, size.Width, size.Height);
Subcontainers.Add(newSubcontainer);
return newSubcontainer;
}
protected void SplitSubcontainerVertically(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject)
{
var topSubcontainerPosition = new Position2D(subcontainer.X, placedObject.Y2);
var topSubcontainerSize = new Rectangle(placedObject.Width, subcontainer.Height - placedObject.Height);
var topSubcontainer = new GuillotineCutSubcontainer2D(topSubcontainerPosition, topSubcontainerSize.Width, topSubcontainerSize.Height);
var rightSubcontainerPosition = new Position2D(placedObject.X2, subcontainer.Y);
var rightSubcontainerSize = new Rectangle(subcontainer.Width - placedObject.Width, subcontainer.Height);
var rightSubcontainer = new GuillotineCutSubcontainer2D(rightSubcontainerPosition, rightSubcontainerSize.Width, rightSubcontainerSize.Height);
// No need to add one dimensional container
if (topSubcontainer.Width == 0 || topSubcontainer.Height == 0)
Subcontainers.Add(topSubcontainer);
if (rightSubcontainer.Width == 0 || rightSubcontainer.Height == 0)
Subcontainers.Add(rightSubcontainer);
Subcontainers.Remove(subcontainer);
}
protected void SplitSubcontainerHorizontally(GuillotineCutSubcontainer2D subcontainer, PlacedObject2D placedObject)
{
var topSubcontainerPosition = new Position2D(subcontainer.X, placedObject.Y2);
var topSubcontainerSize = new Rectangle(subcontainer.Width, subcontainer.Height - placedObject.Height);
var topSubcontainer = new GuillotineCutSubcontainer2D(topSubcontainerPosition, topSubcontainerSize.Width, topSubcontainerSize.Height);
var rightSubcontainerPosition = new Position2D(placedObject.X2, subcontainer.Y);
var rightSubcontainerSize = new Rectangle(subcontainer.Width - placedObject.Width, placedObject.Height);
var rightSubcontainer = new GuillotineCutSubcontainer2D(rightSubcontainerPosition, rightSubcontainerSize.Width, rightSubcontainerSize.Height);
// No need to add one dimensional container
if (topSubcontainer.Width == 0 || topSubcontainer.Height == 0)
Subcontainers.Add(topSubcontainer);
if (rightSubcontainer.Width == 0 || rightSubcontainer.Height == 0)
Subcontainers.Add(rightSubcontainer);
Subcontainers.Remove(subcontainer);
}
}
}
| mit | C# |
a0a1ec681fd6aab0c072769616e95ff25a151591 | Annotate System.Resources.ResourceWriter for nullable ref types (#41880) | poizan42/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr | src/System.Private.CoreLib/shared/System/Resources/ResourceTypeCode.cs | src/System.Private.CoreLib/shared/System/Resources/ResourceTypeCode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Resources
{
/* An internal implementation detail for .resources files, describing
what type an object is.
Ranges:
0 - 0x1F Primitives and reserved values
0x20 - 0x3F Specially recognized types, like byte[] and Streams
Note this data must be included in any documentation describing the
internals of .resources files.
*/
internal enum ResourceTypeCode
{
// Primitives
Null = 0,
String = 1,
Boolean = 2,
Char = 3,
Byte = 4,
SByte = 5,
Int16 = 6,
UInt16 = 7,
Int32 = 8,
UInt32 = 9,
Int64 = 0xa,
UInt64 = 0xb,
Single = 0xc,
Double = 0xd,
Decimal = 0xe,
DateTime = 0xf,
TimeSpan = 0x10,
// A meta-value - change this if you add new primitives
LastPrimitive = TimeSpan,
// Types with a special representation, like byte[] and Stream
ByteArray = 0x20,
Stream = 0x21,
// User types - serialized using the binary formatter.
StartOfUserTypes = 0x40
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Marker for types in .resources files
**
**
===========================================================*/
namespace System.Resources
{
/* An internal implementation detail for .resources files, describing
what type an object is.
Ranges:
0 - 0x1F Primitives and reserved values
0x20 - 0x3F Specially recognized types, like byte[] and Streams
Note this data must be included in any documentation describing the
internals of .resources files.
*/
internal enum ResourceTypeCode
{
// Primitives
Null = 0,
String = 1,
Boolean = 2,
Char = 3,
Byte = 4,
SByte = 5,
Int16 = 6,
UInt16 = 7,
Int32 = 8,
UInt32 = 9,
Int64 = 0xa,
UInt64 = 0xb,
Single = 0xc,
Double = 0xd,
Decimal = 0xe,
DateTime = 0xf,
TimeSpan = 0x10,
// A meta-value - change this if you add new primitives
LastPrimitive = TimeSpan,
// Types with a special representation, like byte[] and Stream
ByteArray = 0x20,
Stream = 0x21,
// User types - serialized using the binary formatter.
StartOfUserTypes = 0x40
}
}
| mit | C# |
37a0859d70d0c8a187ce55d89167407855a0e74a | Return false as a get value for ClosePortOnReboot for DeadSessionController | tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Host/Components/Watchdog/DeadSessionController.cs | src/Tgstation.Server.Host/Components/Watchdog/DeadSessionController.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Components.Watchdog
{
/// <summary>
/// Implements a fake "dead" <see cref="ISessionController"/>
/// </summary>
sealed class DeadSessionController : ISessionController
{
/// <inheritdoc />
public Task<LaunchResult> LaunchResult { get; }
/// <inheritdoc />
public bool IsPrimary => false;
/// <inheritdoc />
public bool TerminationWasRequested => true;
/// <inheritdoc />
public ApiValidationStatus ApiValidationStatus => throw new NotSupportedException();
/// <inheritdoc />
public IDmbProvider Dmb { get; }
/// <inheritdoc />
public ushort? Port => null;
/// <inheritdoc />
public bool ClosePortOnReboot
{
get => false;
set => throw new NotSupportedException();
}
/// <inheritdoc />
public RebootState RebootState => throw new NotSupportedException();
/// <inheritdoc />
public Task OnReboot { get; }
/// <inheritdoc />
public Task<int> Lifetime { get; }
/// <summary>
/// If the <see cref="DeadSessionController"/> was <see cref="Dispose"/>d
/// </summary>
bool disposed;
/// <summary>
/// Construct a <see cref="DeadSessionController"/>
/// </summary>
/// <param name="dmbProvider">The value of <see cref="Dmb"/></param>
public DeadSessionController(IDmbProvider dmbProvider)
{
Dmb = dmbProvider ?? throw new ArgumentNullException(nameof(dmbProvider));
LaunchResult = Task.FromResult(new LaunchResult
{
StartupTime = TimeSpan.FromSeconds(0)
});
Lifetime = Task.FromResult(-1);
OnReboot = new TaskCompletionSource<object>().Task;
}
/// <inheritdoc />
public void Dispose()
{
lock (this)
{
if (disposed)
return;
disposed = true;
}
Dmb.Dispose();
}
/// <inheritdoc />
public void EnableCustomChatCommands() => throw new NotSupportedException();
/// <inheritdoc />
public ReattachInformation Release() => throw new NotSupportedException();
/// <inheritdoc />
public void ResetRebootState() => throw new NotSupportedException();
/// <inheritdoc />
public Task<string> SendCommand(string command, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <inheritdoc />
public void SetHighPriority() => throw new NotSupportedException();
/// <inheritdoc />
public Task<bool> SetPort(ushort newPort, CancellationToken cancellatonToken) => throw new NotSupportedException();
/// <inheritdoc />
public Task<bool> SetRebootState(RebootState newRebootState, CancellationToken cancellationToken) => throw new NotSupportedException();
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Components.Watchdog
{
/// <summary>
/// Implements a fake "dead" <see cref="ISessionController"/>
/// </summary>
sealed class DeadSessionController : ISessionController
{
/// <inheritdoc />
public Task<LaunchResult> LaunchResult { get; }
/// <inheritdoc />
public bool IsPrimary => false;
/// <inheritdoc />
public bool TerminationWasRequested => true;
/// <inheritdoc />
public ApiValidationStatus ApiValidationStatus => throw new NotSupportedException();
/// <inheritdoc />
public IDmbProvider Dmb { get; }
/// <inheritdoc />
public ushort? Port => null;
/// <inheritdoc />
public bool ClosePortOnReboot
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
/// <inheritdoc />
public RebootState RebootState => throw new NotSupportedException();
/// <inheritdoc />
public Task OnReboot { get; }
/// <inheritdoc />
public Task<int> Lifetime { get; }
/// <summary>
/// If the <see cref="DeadSessionController"/> was <see cref="Dispose"/>d
/// </summary>
bool disposed;
/// <summary>
/// Construct a <see cref="DeadSessionController"/>
/// </summary>
/// <param name="dmbProvider">The value of <see cref="Dmb"/></param>
public DeadSessionController(IDmbProvider dmbProvider)
{
Dmb = dmbProvider ?? throw new ArgumentNullException(nameof(dmbProvider));
LaunchResult = Task.FromResult(new LaunchResult
{
StartupTime = TimeSpan.FromSeconds(0)
});
Lifetime = Task.FromResult(-1);
OnReboot = new TaskCompletionSource<object>().Task;
}
/// <inheritdoc />
public void Dispose()
{
lock (this)
{
if (disposed)
return;
disposed = true;
}
Dmb.Dispose();
}
/// <inheritdoc />
public void EnableCustomChatCommands() => throw new NotSupportedException();
/// <inheritdoc />
public ReattachInformation Release() => throw new NotSupportedException();
/// <inheritdoc />
public void ResetRebootState() => throw new NotSupportedException();
/// <inheritdoc />
public Task<string> SendCommand(string command, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <inheritdoc />
public void SetHighPriority() => throw new NotSupportedException();
/// <inheritdoc />
public Task<bool> SetPort(ushort newPort, CancellationToken cancellatonToken) => throw new NotSupportedException();
/// <inheritdoc />
public Task<bool> SetRebootState(RebootState newRebootState, CancellationToken cancellationToken) => throw new NotSupportedException();
}
}
| agpl-3.0 | C# |
b54ffba59bd9885934957117cac46f58c4b7b7b0 | Add some documentation to the Module class. | jammycakes/dolstagis.web,jammycakes/dolstagis.web,jammycakes/dolstagis.web | src/Dolstagis.Web/Module.cs | src/Dolstagis.Web/Module.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dolstagis.Web.Routing;
namespace Dolstagis.Web
{
/// <summary>
/// A container for services and configuration for one part of the application.
/// Modules can be enabled or disabled as required, and last for the duration
/// of the application lifecycle.
/// </summary>
public class Module
{
/// <summary>
/// Gets the text description of the module.
/// </summary>
public virtual string Description { get { return this.GetType().FullName; } }
/// <summary>
/// Gets or sets a value indicating whether the module is enabled.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Creates a new instance of this module.
/// </summary>
public Module()
{
this.Enabled = true;
}
/// <summary>
/// Registers a <see cref="Handler"/> in this module by type,
/// with a route specified in a [Route] attribute on the handler
/// class declaration.
/// </summary>
/// <typeparam name="T"></typeparam>
public void AddHandler<T>() where T: Handler
{
}
/// <summary>
/// Registers a <see cref="Handler"/> in this module with a specified route.
/// </summary>
/// <typeparam name="T">
/// The type of this handler.
/// </typeparam>
/// <param name="route">
/// The route definition for this handler.
/// </param>
public void AddHandler<T>(string route) where T: Handler
{
}
/// <summary>
/// Registers a <see cref="Handler"/> in this module with a specified route
/// and precondition.
/// </summary>
/// <typeparam name="T">
/// The type of this handler.
/// </typeparam>
/// <param name="route">
/// The route definition for this handler.
/// </param>
/// <param name="precondition">
/// A function giving a precondition whether this route is valid or not.
/// </param>
public void AddHandler<T>(string route, Func<RouteInfo, bool> precondition) where T: Handler
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dolstagis.Web.Routing;
namespace Dolstagis.Web
{
public class Module
{
public virtual string Description { get { return String.Empty; } }
public bool Enabled { get; set; }
public Module()
{
this.Enabled = true;
}
public void AddHandler<T>() where T: Handler
{
}
public void AddHandler<T>(string route) where T: Handler
{
}
public void AddHandler<T>(string route, Func<RouteInfo, bool> precondition) where T: Handler
{
}
}
}
| mit | C# |
ed77b7b3f44b3d8a8549844ff3ed4baf2325c391 | remove IDevice from interface | nicolgit/demo-xamarin-heartrate-ble | src/IHeartRateEnumerator.cs | src/IHeartRateEnumerator.cs | using System;
namespace CaledosLab.Runner.Commons.Abstractions
{
interface IHeartRateEnumerator
{
bool StartDeviceScan();
bool StopDeviceScan();
event EventHandler<string> DeviceScanUpdate;
event EventHandler DeviceScanTimeout;
}
} | using System;
using Plugin.BLE.Abstractions.Contracts;
namespace CaledosLab.Runner.Commons.Abstractions
{
interface IHeartRateEnumerator
{
bool StartDeviceScan();
bool StopDeviceScan();
event EventHandler<string> DeviceScanUpdate;
event EventHandler DeviceScanTimeout;
}
} | mit | C# |
a02c6c4a8dc641acf0254e6bcdd5728c11972de3 | Update Ring.cs | googlevr/daydream-elements | Assets/DaydreamElements/Elements/SwipeMenu/Demo/Scripts/Ring.cs | Assets/DaydreamElements/Elements/SwipeMenu/Demo/Scripts/Ring.cs | // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 UnityEngine;
namespace DaydreamElements.SwipeMenu {
/// Visual ring around the radial menu to further indicate when the player
/// has successfully selected a color by briefly glowing.
[RequireComponent(typeof(SpriteRenderer))]
public class Ring : MonoBehaviour {
private SpriteRenderer spriteRenderer;
private Color color = Color.white;
public GameObject swipeMenu;
void Start() {
swipeMenu.GetComponent<SwipeMenu>().OnSwipeSelect += OnSwipeSelect;
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Update() {
spriteRenderer.color = color;
color = color * 0.9f + Color.white * 0.1f;
}
private void OnSwipeSelect(int index) {
color = ColorUtil.ToColor((ColorUtil.Type)index);
}
}
}
| // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 UnityEngine;
namespace DaydreamElements.SwipeMenu {
/// Visual ring around the radial menu to further indicate when the player
/// has successfully selected a color by briefly glowing.
[RequireComponent(typeof(SpriteRenderer))]
public class Ring : MonoBehaviour {
private SpriteRenderer spriteRenderer;
private Color color = Color.white;
public GameObject swipeMenu;
void Start() {
swipeMenu.GetComponent<SwipeMenu>().OnSwipeSelect += OnSwipeSelect;
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Update() {
gameObject.GetComponent<SpriteRenderer>().color = color;
color = color * 0.9f + Color.white * 0.1f;
}
private void OnSwipeSelect(int index) {
color = ColorUtil.ToColor((ColorUtil.Type)index);
}
}
}
| apache-2.0 | C# |
3cfb4a7b70c20c02b5833e5d158831a3d6a17476 | Fix for automapper castle component | makingsensetraining/angular-webapi,makingsensetraining/angular-webapi,makingsensetraining/angular-webapi | Source/Hiperion/Hiperion/Infrastructure/Ioc/WindsorInstaller.cs | Source/Hiperion/Hiperion/Infrastructure/Ioc/WindsorInstaller.cs | namespace Hiperion.Infrastructure.Ioc
{
#region References
using System.Configuration;
using System.Web.Http;
using AutoMapper;
using Automapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using EF;
using EF.Interfaces;
using Mappings;
#endregion
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString;
container.Register(
Component.For<IMappingEngine>()
.UsingFactoryMethod(() => Mapper.Engine),
Component.For<IDbContext>()
.ImplementedBy<HiperionDbContext>()
.LifestylePerWebRequest()
.DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)),
Component.For(typeof (EntityResolver<>))
.ImplementedBy(typeof (EntityResolver<>))
.LifestyleTransient(),
Component.For(typeof (ManyToManyEntityResolver<,>))
.ImplementedBy(typeof (ManyToManyEntityResolver<,>))
.LifestyleTransient(),
Types.FromThisAssembly()
.Where(type => (type.Name.EndsWith("Services") ||
type.Name.EndsWith("Repository") ||
type.Name.EndsWith("Resolver") ||
type.Name.EndsWith("Controller")) && type.IsClass)
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
AutomapperConfiguration.Configure(container.Resolve);
GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container);
}
}
} | namespace Hiperion.Infrastructure.Ioc
{
#region References
using System.Configuration;
using System.Web.Http;
using AutoMapper;
using Automapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using EF;
using EF.Interfaces;
using Mappings;
#endregion
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString;
container.Register(
Component.For<IMappingEngine>()
.Instance(Mapper.Engine),
Component.For<IDbContext>()
.ImplementedBy<HiperionDbContext>()
.LifestylePerWebRequest()
.DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)),
Component.For(typeof (EntityResolver<>))
.ImplementedBy(typeof (EntityResolver<>))
.LifestyleTransient(),
Component.For(typeof (ManyToManyEntityResolver<,>))
.ImplementedBy(typeof (ManyToManyEntityResolver<,>))
.LifestyleTransient(),
Types.FromThisAssembly()
.Where(type => (type.Name.EndsWith("Services") ||
type.Name.EndsWith("Repository") ||
type.Name.EndsWith("Resolver") ||
type.Name.EndsWith("Controller")) && type.IsClass)
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
AutomapperConfiguration.Configure(container.Resolve);
GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container);
}
}
} | mit | C# |
61d898d70982d8a3ce8317ffa717165a800195f1 | Make ConvertPath to allow this functionality to be modified to allow for slashes in path | DigDes/SoapCore | src/SoapCore/TrailingServicePathTuner.cs | src/SoapCore/TrailingServicePathTuner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace SoapCore
{
/// <summary>
/// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc
/// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner());
/// </summary>
public class TrailingServicePathTuner
{
public virtual void ConvertPath(HttpContext httpContext)
{
string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/'));
httpContext.Request.Path = new PathString(trailingPath);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace SoapCore
{
/// <summary>
/// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc
/// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner());
/// </summary>
public class TrailingServicePathTuner
{
public void ConvertPath(HttpContext httpContext)
{
string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/'));
httpContext.Request.Path = new PathString(trailingPath);
}
}
}
| mit | C# |
8cbc96476b74a72925f9f14ed0eb062882a4a29d | Revert "Revert "Modified the Import class"" | GiveCampUK/GiveCRM,GiveCampUK/GiveCRM | src/GiveCRM.ImportExport/GiveCRM.ImportExport/ExcelImport.cs | src/GiveCRM.ImportExport/GiveCRM.ImportExport/ExcelImport.cs | using NPOI;
namespace GiveCRM.ImportExport
{
public class ExcelImport
{
}
} | namespace GiveCRM.ImportExport
{
public class ExcelImport
{
}
} | mit | C# |
0c860e999bc3c5ffa44b5db2daf47c0edbfbb678 | Reimplement after merge | leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS | src/Umbraco.Web/WebApi/Filters/HttpQueryStringModelBinder.cs | src/Umbraco.Web/WebApi/Filters/HttpQueryStringModelBinder.cs | using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
namespace Umbraco.Web.WebApi.Filters
{
/// <summary>
/// Allows an Action to execute with an arbitrary number of QueryStrings
/// </summary>
/// <remarks>
/// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number
/// but this will allow you to do it
/// </remarks>
public sealed class HttpQueryStringModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//get the query strings from the request properties
if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs"))
{
if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings)
{
var queryStringKeys = queryStrings.Select(kvp => kvp.Key).ToArray();
var additionalParameters = new Dictionary<string, string>();
if(queryStringKeys.Contains("culture") == false) {
additionalParameters["culture"] = actionContext.Request.ClientCulture();
}
var formData = new FormDataCollection(queryStrings.Union(additionalParameters));
bindingContext.Model = formData;
return true;
}
}
return false;
}
}
}
| using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
namespace Umbraco.Web.WebApi.Filters
{
/// <summary>
/// Allows an Action to execute with an arbitrary number of QueryStrings
/// </summary>
/// <remarks>
/// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number
/// but this will allow you to do it
/// </remarks>
public sealed class HttpQueryStringModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//get the query strings from the request properties
if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs"))
{
if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings)
{
var formData = new FormDataCollection(queryStrings);
bindingContext.Model = formData;
return true;
}
}
return false;
}
}
} | mit | C# |
7d1a8a286f022e4e1e58c070cae1a30f6b028a6f | Update comment. | CountrySideEngineer/Ev3Controller | dev/src/Ev3Controller/Ev3Command/Command_20.cs | dev/src/Ev3Controller/Ev3Command/Command_20.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ev3Controller.Ev3Command
{
public abstract class Command_20 : ACommand_ResLenFlex
{
#region Constructors and the Finalizer
/// <summary>
/// Constructor
/// </summary>
/// <param name="CommandParam"></param>
public Command_20(ICommandParam CommandParam) : base(CommandParam) { }
#endregion
#region Other methods and private properties in calling order
/// <summary>
/// Initialize command and response code, and its command name.
/// </summary>
protected override void Init()
{
this.Name = "GetSonicSensor";
this.Cmd = 0x20;
this.Res = 0x21;
base.Init();
}
/// <summary>
/// Check parameters.
/// </summary>
protected override void CheckParam()
{
int DataIndex = (int)RESPONSE_BUFF_INDEX.RESPONSE_BUFF_INDEX_RES_DATA_TOP;
int DevNum = this.ResData[DataIndex++];
for (int DevIndex = 0; DevIndex < DevNum; DevIndex++)
{
base.CheckPort(DataIndex);
DataIndex += this.OneDataLen;
}
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ev3Controller.Ev3Command
{
public abstract class Command_20 : ACommand_ResLenFlex
{
#region Constructors and the Finalizer
public Command_20(ICommandParam CommandParam) : base(CommandParam) { }
#endregion
#region Other methods and private properties in calling order
/// <summary>
/// Initialize command and response code, and its command name.
/// </summary>
protected override void Init()
{
this.Name = "GetSonicSensor";
this.Cmd = 0x20;
this.Res = 0x21;
base.Init();
}
/// <summary>
/// Check parameters.
/// </summary>
protected override void CheckParam()
{
int DataIndex = (int)RESPONSE_BUFF_INDEX.RESPONSE_BUFF_INDEX_RES_DATA_TOP;
int DevNum = this.ResData[DataIndex++];
for (int DevIndex = 0; DevIndex < DevNum; DevIndex++)
{
base.CheckPort(DataIndex);
DataIndex += this.OneDataLen;
}
}
#endregion
}
}
| mit | C# |
6ff3497c693f3c2231217a2b0ae662f52a32367b | Update Metrics.cs to support Sets metrics | goncalopereira/statsd-csharp-client,Pereingo/statsd-csharp-client,agileharbor/telegraf-client,bilal-fazlani/statsd-csharp-client,circleback/statsd-csharp-client,Kyle2123/statsd-csharp-client,DarrellMozingo/statsd-csharp-client | src/StatsdClient/Metrics.cs | src/StatsdClient/Metrics.cs | using System;
namespace StatsdClient
{
public static class Metrics
{
private static Statsd _statsD;
private static string _prefix;
public static void Configure(MetricsConfig config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_prefix = config.Prefix;
_statsD = string.IsNullOrEmpty(config.StatsdServerName)
? null
: new Statsd(new StatsdUDP(config.StatsdServerName, config.StatsdServerPort, config.StatsdMaxUDPPacketSize));
}
public static void Counter(string statName, int value = 1, double sampleRate = 1)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Counting>(BuildNamespacedStatName(statName), value, sampleRate);
}
public static void Gauge(string statName, double value)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Gauge>(BuildNamespacedStatName(statName), value);
}
public static void Timer(string statName, int value, double sampleRate = 1)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Timing>(BuildNamespacedStatName(statName), value, sampleRate);
}
public static IDisposable StartTimer(string name)
{
return new MetricsTimer(name);
}
public static void Time(Action action, string statName, double sampleRate=1)
{
if (_statsD == null)
{
action();
return;
}
_statsD.Send(action, BuildNamespacedStatName(statName), sampleRate);
}
public static T Time<T>(Func<T> func, string statName)
{
if (_statsD == null)
{
return func();
}
using (StartTimer(statName))
{
return func();
}
}
public static void Set(string statName, string value)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Set>(BuildNamespacedStatName(statName), value);
}
private static string BuildNamespacedStatName(string statName)
{
if (string.IsNullOrEmpty(_prefix))
{
return statName;
}
return _prefix + "." + statName;
}
}
}
| using System;
namespace StatsdClient
{
public static class Metrics
{
private static Statsd _statsD;
private static string _prefix;
public static void Configure(MetricsConfig config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_prefix = config.Prefix;
_statsD = string.IsNullOrEmpty(config.StatsdServerName)
? null
: new Statsd(new StatsdUDP(config.StatsdServerName, config.StatsdServerPort, config.StatsdMaxUDPPacketSize));
}
public static void Counter(string statName, int value = 1, double sampleRate = 1)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Counting>(BuildNamespacedStatName(statName), value, sampleRate);
}
public static void Gauge(string statName, double value)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Gauge>(BuildNamespacedStatName(statName), value);
}
public static void Timer(string statName, int value, double sampleRate = 1)
{
if (_statsD == null)
{
return;
}
_statsD.Send<Statsd.Timing>(BuildNamespacedStatName(statName), value, sampleRate);
}
public static IDisposable StartTimer(string name)
{
return new MetricsTimer(name);
}
public static void Time(Action action, string statName, double sampleRate=1)
{
if (_statsD == null)
{
action();
return;
}
_statsD.Send(action, BuildNamespacedStatName(statName), sampleRate);
}
public static T Time<T>(Func<T> func, string statName)
{
if (_statsD == null)
{
return func();
}
using (StartTimer(statName))
{
return func();
}
}
private static string BuildNamespacedStatName(string statName)
{
if (string.IsNullOrEmpty(_prefix))
{
return statName;
}
return _prefix + "." + statName;
}
}
}
| mit | C# |
a88d922654707b6912b75cc14fbe0c14e70d0f3c | fix unit tests | aritters/Ritter,arsouza/Aritter,arsouza/Aritter | src/Aritter.Infra.Crosscutting.Tests/Logging/LoggerTest.cs | src/Aritter.Infra.Crosscutting.Tests/Logging/LoggerTest.cs | using Aritter.Infra.Crosscutting.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Aritter.Infra.Crosscutting.Tests.Logging
{
[TestClass]
public class LoggerTest
{
[TestMethod]
public void SetLoggerFactorySuccessfully()
{
LoggerFactory.SetCurrent(new TestLoggerFactory());
ILoggerFactory factory = LoggerFactory.Current();
Assert.IsNotNull(factory);
Assert.IsInstanceOfType(factory, typeof(TestLoggerFactory));
}
[TestMethod]
public void CreateLoggerSuccessfully()
{
LoggerFactory.SetCurrent(new TestLoggerFactory());
ILoggerFactory factory = LoggerFactory.Current();
Assert.IsNotNull(factory);
Assert.IsInstanceOfType(factory, typeof(TestLoggerFactory));
ILogger logger = LoggerFactory.CreateLogger();
Assert.IsNotNull(logger);
Assert.IsInstanceOfType(logger, typeof(TestLogger));
}
[TestMethod]
public void CreateLoggerMustReturnNull()
{
LoggerFactory.SetCurrent(null);
ILoggerFactory factory = LoggerFactory.Current();
Assert.IsNull(factory);
ILogger logger = LoggerFactory.CreateLogger();
Assert.IsNull(logger);
}
}
} | using Aritter.Infra.Crosscutting.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Aritter.Infra.Crosscutting.Tests.Logging
{
[TestClass]
public class LoggerTest
{
[TestMethod]
public void SetTypeAdpterFactorySuccessfully()
{
LoggerFactory.SetCurrent(new TestLoggerFactory());
ILoggerFactory factory = LoggerFactory.Current();
Assert.IsNotNull(factory);
Assert.IsInstanceOfType(factory, typeof(TestLoggerFactory));
ILogger logger = LoggerFactory.CreateLogger();
Assert.IsNotNull(logger);
Assert.IsInstanceOfType(logger, typeof(TestLogger));
}
}
} | mit | C# |
26e80c3e4dd4c8518952061f2c8b04994531da8b | Fix rename which monodevelop missed. | rubenv/tripod,rubenv/tripod | src/Core/Tripod.Core/Tripod.Model/ICacheablePhotoSource.cs | src/Core/Tripod.Core/Tripod.Model/ICacheablePhotoSource.cs | //
// ICacheablePhotoSource.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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 Tripod.Model
{
public interface ICacheablePhotoSource : IPhotoSource
{
void Initialize (string data);
string InitializationData { get; }
}
}
| //
// IRegisterablePhotoSource.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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 Tripod.Model
{
public interface ICacheablePhotoSource : IPhotoSource
{
void Initialize (string data);
string InitializationData { get; }
}
}
| mit | C# |
2542aa85cfd8aee70ee2e2804ffe90ceaf0f1413 | Remove old test | noobot/SlackConnector | src/SlackConnector.Tests.Unit/SlackConnectionTests/InboundMessageTests/PongTests.cs | src/SlackConnector.Tests.Unit/SlackConnectionTests/InboundMessageTests/PongTests.cs | using System;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Should;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Inbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests.InboundMessageTests
{
internal class PongTests
{
[Test, AutoMoqData]
public async Task should_raise_event(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object };
await slackConnection.Initialise(connectionInfo);
DateTime lastTimestamp = DateTime.MinValue;
slackConnection.OnPong += timestamp =>
{
lastTimestamp = timestamp;
return Task.CompletedTask;
};
var inboundMessage = new PongMessage
{
Timestamp = DateTime.Now
};
// when
webSocket.Raise(x => x.OnMessage += null, null, inboundMessage);
// then
lastTimestamp.ShouldEqual(inboundMessage.Timestamp);
}
}
} | using System;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Should;
using SlackConnector.Connections.Models;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Inbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests.InboundMessageTests
{
internal class PongTests
{
[Test, AutoMoqData]
public async Task should_raise_event(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object };
await slackConnection.Initialise(connectionInfo);
DateTime lastTimestamp = DateTime.MinValue;
slackConnection.OnPong += timestamp =>
{
lastTimestamp = timestamp;
return Task.CompletedTask;
};
var inboundMessage = new PongMessage
{
Timestamp = DateTime.Now
};
// when
webSocket.Raise(x => x.OnMessage += null, null, inboundMessage);
// then
lastTimestamp.ShouldEqual(inboundMessage.Timestamp);
}
}
internal class given_pong : BaseTest<PongMessage>
{
private DateTime _timestamp;
protected override void Given()
{
base.Given();
SUT.OnPong += timestamp =>
{
_timestamp = timestamp;
return Task.CompletedTask;
};
InboundMessage = new PongMessage
{
Timestamp = DateTime.Now
};
}
[Test]
public void then_should_raised_event_with_expected_timestamp()
{
Assert.That(_timestamp, Is.EqualTo(InboundMessage.Timestamp));
}
}
} | mit | C# |
a4c37b6510391ead0b9a9aac95fd3211a1bba3ca | move Base32 alphabets behind properties | ssg/SimpleBase,ssg/SimpleBase32,ssg/SimpleBase | src/Base32Alphabet.cs | src/Base32Alphabet.cs | /*
Copyright 2014-2016 Sedat Kapanoglu
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;
namespace SimpleBase
{
internal class Base32Alphabet
{
public const int Length = 32;
const char highestAsciiCharSupported = 'z';
private static Base32Alphabet crockford = new CrockfordBase32Alphabet();
private static Base32Alphabet rfc4648 =
new Base32Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");
private static Base32Alphabet extendedHex =
new Base32Alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV");
public static Base32Alphabet Crockford { get { return crockford; } }
public static Base32Alphabet Rfc4648 { get { return rfc4648; } }
public static Base32Alphabet ExtendedHex { get { return extendedHex; } }
public char[] EncodingTable { get; private set; }
public byte[] DecodingTable { get; protected set; }
public Base32Alphabet(string chars)
{
this.EncodingTable = chars.ToCharArray();
createDecodingTable(chars);
}
private void createDecodingTable(string chars)
{
var bytes = new byte[highestAsciiCharSupported + 1];
int len = chars.Length;
for (int n = 0; n < len; n++)
{
char c = chars[n];
byte b = (byte)(n + 1);
bytes[c] = b;
bytes[Char.ToLowerInvariant(c)] = b;
}
this.DecodingTable = bytes;
}
}
} | /*
Copyright 2014-2016 Sedat Kapanoglu
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;
namespace SimpleBase
{
internal class Base32Alphabet
{
public const int Length = 32;
const char highestAsciiCharSupported = 'z';
public static Base32Alphabet Crockford = new CrockfordBase32Alphabet();
public static Base32Alphabet Rfc4648 = new Base32Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");
public static Base32Alphabet ExtendedHex = new Base32Alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV");
public char[] EncodingTable { get; private set; }
public byte[] DecodingTable { get; protected set; }
public Base32Alphabet(string chars)
{
this.EncodingTable = chars.ToCharArray();
createDecodingTable(chars);
}
private void createDecodingTable(string chars)
{
var bytes = new byte[highestAsciiCharSupported + 1];
int len = chars.Length;
for (int n = 0; n < len; n++)
{
char c = chars[n];
byte b = (byte)(n + 1);
bytes[c] = b;
bytes[Char.ToLowerInvariant(c)] = b;
}
this.DecodingTable = bytes;
}
}
} | apache-2.0 | C# |
af44fed5204737674647b541aabc12cf6b7aab5b | Fix printer container name | larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl | MatterControlLib/Library/Providers/SDCard/PrinterContainer.cs | MatterControlLib/Library/Providers/SDCard/PrinterContainer.cs | /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
using System.IO;
using MatterHackers.Agg.Platform;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterHackers.MatterControl.Library
{
// Printer specific containers
public class PrinterContainer : LibraryContainer
{
private PrinterConfig printer;
public PrinterContainer(PrinterConfig printer)
{
this.printer = printer;
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>();
this.Name = printer.Settings.GetValue(SettingsKey.printer_name);
}
public override void Load()
{
this.Items.Clear();
this.ChildContainers.Clear();
this.ChildContainers.Add(
new DynamicContainerLink(
() => "SD Card".Localize(),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "sd_20x20.png")),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "sd_folder.png")),
() => new SDCardContainer(printer),
() =>
{
return printer.Settings.GetValue<bool>(SettingsKey.has_sd_card_reader);
})
{
IsReadOnly = true
});
this.ChildContainers.Add(
new DynamicContainerLink(
() => "Calibration Parts".Localize(),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "folder_20x20.png")),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "folder.png")),
() => new CalibrationPartsContainer())
{
IsReadOnly = true
});
// TODO: An enumerable list of serialized container paths (or some other markup) to construct for this printer
// printer.Settings.GetValue(SettingsKey.library_containers);
}
}
}
| /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
using System.IO;
using MatterHackers.Agg.Platform;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterHackers.MatterControl.Library
{
// Printer specific containers
public class PrinterContainer : LibraryContainer
{
private PrinterConfig printer;
public PrinterContainer(PrinterConfig printer)
{
this.printer = printer;
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>();
this.Name = "Printers".Localize();
}
public override void Load()
{
this.Items.Clear();
this.ChildContainers.Clear();
this.ChildContainers.Add(
new DynamicContainerLink(
() => "SD Card".Localize(),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "sd_20x20.png")),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "sd_folder.png")),
() => new SDCardContainer(printer),
() =>
{
return printer.Settings.GetValue<bool>(SettingsKey.has_sd_card_reader);
})
{
IsReadOnly = true
});
this.ChildContainers.Add(
new DynamicContainerLink(
() => "Calibration Parts".Localize(),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "folder_20x20.png")),
AggContext.StaticData.LoadIcon(Path.Combine("Library", "folder.png")),
() => new CalibrationPartsContainer())
{
IsReadOnly = true
});
// TODO: An enumerable list of serialized container paths (or some other markup) to construct for this printer
// printer.Settings.GetValue(SettingsKey.library_containers);
}
}
}
| bsd-2-clause | C# |
652c529f8f0baa2c4504c377bf0d17a1c7ca69cf | Fix ServerShutsDownWhenMainExits test (#1120) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/IISExpress.FunctionalTests/InProcess/ShutdownTests.cs | test/IISExpress.FunctionalTests/InProcess/ShutdownTests.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Server.IISIntegration.FunctionalTests
{
public class ShutdownTests : IISFunctionalTestBase
{
public ShutdownTests(ITestOutputHelper output) : base(output)
{
}
[ConditionalFact]
public async Task ServerShutsDownWhenMainExits()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
var result = await DeployAsync(parameters);
try
{
await result.HttpClient.GetAsync("/Shutdown");
}
catch (HttpRequestException ex) when (ex.InnerException is IOException)
{
// Server might close a connection before request completes
}
Assert.True(result.HostShutdownToken.WaitHandle.WaitOne(TimeoutExtensions.DefaultTimeout));
}
[ConditionalFact]
public async Task GracefulShutdown_DoesNotCrashProcess()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
parameters.GracefulShutdown = true;
var result = await DeployAsync(parameters);
var response = await result.RetryingHttpClient.GetAsync("/HelloWorld");
StopServer();
Assert.True(result.HostProcess.ExitCode == 0);
}
[ConditionalFact]
public async Task ForcefulShutdown_DoesrashProcess()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
var result = await DeployAsync(parameters);
var response = await result.RetryingHttpClient.GetAsync("/HelloWorld");
StopServer();
Assert.True(result.HostProcess.ExitCode == 1);
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Server.IISIntegration.FunctionalTests
{
public class ShutdownTests : IISFunctionalTestBase
{
public ShutdownTests(ITestOutputHelper output) : base(output)
{
}
[ConditionalFact]
public async Task ServerShutsDownWhenMainExits()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
var result = await DeployAsync(parameters);
var response = await result.RetryingHttpClient.GetAsync("/Shutdown");
Assert.True(result.HostShutdownToken.WaitHandle.WaitOne(TimeoutExtensions.DefaultTimeout));
}
[ConditionalFact]
public async Task GracefulShutdown_DoesNotCrashProcess()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
parameters.GracefulShutdown = true;
var result = await DeployAsync(parameters);
var response = await result.RetryingHttpClient.GetAsync("/HelloWorld");
StopServer();
Assert.True(result.HostProcess.ExitCode == 0);
}
[ConditionalFact]
public async Task ForcefulShutdown_DoesrashProcess()
{
var parameters = Helpers.GetBaseDeploymentParameters(publish: true);
var result = await DeployAsync(parameters);
var response = await result.RetryingHttpClient.GetAsync("/HelloWorld");
StopServer();
Assert.True(result.HostProcess.ExitCode == 1);
}
}
}
| apache-2.0 | C# |
84ede13d104f98749ff856d0f48b26542e3f30a0 | add UseJSNLog overload for IApplicationBuilder | mperdeck/jsnlog | jsnlog/PublicFacing/AspNet5/Configuration/Middleware/ApplicationBuilderExtensions.cs | jsnlog/PublicFacing/AspNet5/Configuration/Middleware/ApplicationBuilderExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
namespace JSNLog
{
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Normally, an ASP.NET 5 app would simply call this to insert JSNLog middleware into the pipeline.
/// Note that the loggingAdapter is required, otherwise JSNLog can't hand off log messages.
/// It can live without a configuration though (it will use default settings).
/// </summary>
/// <param name="builder"></param>
/// <param name="loggingAdapter"></param>
/// <param name="jsnlogConfiguration">
/// Note that if jsnlogConfiguration is set to null, the script tag and JavaScript config code will
/// automatically be inserted in html responses.
/// </param>
public static void UseJSNLog(this IApplicationBuilder builder,
ILoggingAdapter loggingAdapter, JsnlogConfiguration jsnlogConfiguration = null)
{
JavascriptLogging.SetJsnlogConfiguration(jsnlogConfiguration, loggingAdapter);
builder.UseMiddleware<JSNLogMiddleware>();
}
public static void UseJSNLog(this IApplicationBuilder builder,
ILoggerFactory loggerFactory, JsnlogConfiguration jsnlogConfiguration = null)
{
var loggingAdapter = new LoggingAdapter(loggerFactory);
UseJSNLog(builder, loggingAdapter, jsnlogConfiguration);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Builder;
namespace JSNLog
{
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Normally, an ASP.NET 5 app would simply call this to insert JSNLog middleware into the pipeline.
/// Note that the loggingAdapter is required, otherwise JSNLog can't hand off log messages.
/// It can live without a configuration though (it will use default settings).
/// </summary>
/// <param name="builder"></param>
/// <param name="loggingAdapter"></param>
/// <param name="jsnlogConfiguration"></param>
public static void UseJSNLog(this IApplicationBuilder builder,
ILoggingAdapter loggingAdapter, JsnlogConfiguration jsnlogConfiguration = null)
{
JavascriptLogging.SetJsnlogConfiguration(jsnlogConfiguration, loggingAdapter);
builder.UseMiddleware<JSNLogMiddleware>();
}
}
}
| mit | C# |
4b7cbe87b5e8e02286466d325d8b5a0db1030ddb | Allow settings custom command line params. | ngs-doo/revenj,ngs-doo/revenj,tferega/revenj,tferega/revenj,ngs-doo/revenj,tferega/revenj,tferega/revenj,ngs-doo/revenj,ngs-doo/revenj | Code/Server/Revenj.Http/Program.cs | Code/Server/Revenj.Http/Program.cs | using System;
using System.Configuration;
using DSL;
namespace Revenj.Http
{
static class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
var i = arg.IndexOf('=');
if (i != -1)
{
var name = arg.Substring(0, i);
var value = arg.Substring(i + 1);
ConfigurationManager.AppSettings[name] = value;
}
}
var server = Platform.Start<HttpServer>();
Console.WriteLine("Starting server");
server.Run();
}
}
}
| using System;
using DSL;
namespace Revenj.Http
{
static class Program
{
static void Main(string[] args)
{
var server = Platform.Start<HttpServer>();
Console.WriteLine("Starting server");
server.Run();
}
}
}
| bsd-3-clause | C# |
c1023b873c17624e5822281f2e26e7aafa812751 | Use BenchmarkRunner | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | tests/AdventOfCode.Benchmarks/Program.cs | tests/AdventOfCode.Benchmarks/Program.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Benchmarks
{
using BenchmarkDotNet.Running;
/// <summary>
/// A console application that runs performance benchmarks for the puzzles. This class cannot be inherited.
/// </summary>
internal static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
internal static void Main(string[] args)
=> BenchmarkRunner.Run<PuzzleBenchmarks>(args: args);
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Benchmarks
{
using BenchmarkDotNet.Running;
/// <summary>
/// A console application that runs performance benchmarks for the puzzles. This class cannot be inherited.
/// </summary>
internal static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
internal static void Main(string[] args)
{
var switcher = BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly);
if (args?.Length == 0)
{
switcher.RunAll();
}
else
{
switcher.Run(args);
}
}
}
}
| apache-2.0 | C# |
3879bb4f02ed85686f17962211f272baf66e4f6d | Fix menu entry name | bartlomiejwolk/AnimatorController | Editor/AnimatorControllerEditor.cs | Editor/AnimatorControllerEditor.cs | using UnityEngine;
using System.Collections;
using UnityEditor;
using Rotorz.ReorderableList;
namespace AnimatorControllerEx {
[CustomEditor(typeof(AnimatorController))]
public sealed class AnimatorControllerEditor: Editor {
#region SERIALIZED PROPERTIES
private SerializedProperty animator;
private SerializedProperty animatorParams;
private SerializedProperty description;
#endregion
#region UNITY MESSAGES
private void OnEnable() {
animator = serializedObject.FindProperty("animator");
animatorParams = serializedObject.FindProperty("animatorParams");
description = serializedObject.FindProperty("description");
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawVersionLabel();
DrawDescriptionTextArea();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(animator);
ReorderableListGUI.Title("Animator Params");
ReorderableListGUI.ListField(animatorParams);
serializedObject.ApplyModifiedProperties();
}
#endregion
#region INSPECTOR CONTROLS
private void DrawVersionLabel() {
EditorGUILayout.LabelField(
string.Format(
"{0} ({1})",
AnimatorController.Version,
AnimatorController.Extension));
}
private void DrawDescriptionTextArea() {
description.stringValue = EditorGUILayout.TextArea(
description.stringValue);
}
#endregion INSPECTOR
#region METHODS
[MenuItem("Component/AnimatorController")]
private static void AddAnimatorControllerComponent() {
if (Selection.activeGameObject != null) {
Selection.activeGameObject.AddComponent(typeof(AnimatorController));
}
}
#endregion METHODS
}
}
| using UnityEngine;
using System.Collections;
using UnityEditor;
using Rotorz.ReorderableList;
namespace AnimatorControllerEx {
[CustomEditor(typeof(AnimatorController))]
public sealed class AnimatorControllerEditor: Editor {
#region SERIALIZED PROPERTIES
private SerializedProperty animator;
private SerializedProperty animatorParams;
private SerializedProperty description;
#endregion
#region UNITY MESSAGES
private void OnEnable() {
animator = serializedObject.FindProperty("animator");
animatorParams = serializedObject.FindProperty("animatorParams");
description = serializedObject.FindProperty("description");
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawVersionLabel();
DrawDescriptionTextArea();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(animator);
ReorderableListGUI.Title("Animator Params");
ReorderableListGUI.ListField(animatorParams);
serializedObject.ApplyModifiedProperties();
}
#endregion
#region INSPECTOR CONTROLS
private void DrawVersionLabel() {
EditorGUILayout.LabelField(
string.Format(
"{0} ({1})",
AnimatorController.Version,
AnimatorController.Extension));
}
private void DrawDescriptionTextArea() {
description.stringValue = EditorGUILayout.TextArea(
description.stringValue);
}
#endregion INSPECTOR
#region METHODS
[MenuItem("Component/MyNamespace/AnimatorController")]
private static void AddAnimatorControllerComponent() {
if (Selection.activeGameObject != null) {
Selection.activeGameObject.AddComponent(typeof(AnimatorController));
}
}
#endregion METHODS
}
}
| mit | C# |
5da53425294ad8c7742cd85848cedf22211da378 | remove MultimodalDistributionAnalyzer hint introduced in #763 | alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet | src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs | src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs | using System.Collections.Generic;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Mathematics;
using BenchmarkDotNet.Reports;
using JetBrains.Annotations;
namespace BenchmarkDotNet.Analysers
{
public class MultimodalDistributionAnalyzer : AnalyserBase
{
public static readonly IAnalyser Default = new MultimodalDistributionAnalyzer();
private MultimodalDistributionAnalyzer() { }
public override string Id => "MultimodalDistribution";
public override IEnumerable<Conclusion> AnalyseReport(BenchmarkReport report, Summary summary)
{
var statistics = report.ResultStatistics;
if (statistics == null || statistics.N < EngineResolver.DefaultMinTargetIterationCount)
yield break;
double mValue = MathHelper.CalculateMValue(statistics);
if (mValue > 4.2)
yield return Create("is multimodal", mValue, report);
else if (mValue > 3.2)
yield return Create("is bimodal", mValue, report);
else if (mValue > 2.8)
yield return Create("can have several modes", mValue, report);
}
[NotNull]
private Conclusion Create([NotNull] string kind, double mValue, [CanBeNull] BenchmarkReport report)
=> CreateWarning($"It seems that the distribution {kind} (mValue = {mValue.ToStr()})", report);
}
} | using System.Collections.Generic;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Mathematics;
using BenchmarkDotNet.Reports;
using JetBrains.Annotations;
namespace BenchmarkDotNet.Analysers
{
public class MultimodalDistributionAnalyzer : AnalyserBase
{
public static readonly IAnalyser Default = new MultimodalDistributionAnalyzer();
private MultimodalDistributionAnalyzer() { }
public override string Id => "MultimodalDistribution";
public override IEnumerable<Conclusion> AnalyseReport(BenchmarkReport report, Summary summary)
{
var statistics = report.ResultStatistics;
if (statistics == null)
yield break;
if (statistics.N < EngineResolver.DefaultMinTargetIterationCount)
yield return CreateHint($"The number of iterations was set to less than {EngineResolver.DefaultMinTargetIterationCount}, " +
$"{nameof(MultimodalDistributionAnalyzer)} needs at least {EngineResolver.DefaultMinTargetIterationCount} iterations to work.");
double mValue = MathHelper.CalculateMValue(statistics);
if (mValue > 4.2)
yield return Create("is multimodal", mValue, report);
else if (mValue > 3.2)
yield return Create("is bimodal", mValue, report);
else if (mValue > 2.8)
yield return Create("can have several modes", mValue, report);
}
[NotNull]
private Conclusion Create([NotNull] string kind, double mValue, [CanBeNull] BenchmarkReport report)
=> CreateWarning($"It seems that the distribution {kind} (mValue = {mValue.ToStr()})", report);
}
} | mit | C# |
6de2a740a9a81ecfca1d7e0c0b70fbc9368c5e18 | Add SynchronizerBaseTest | Ackara/Daterpillar | src/Tests.Daterpillar/UnitTest/SynchronizerBaseTest.cs | src/Tests.Daterpillar/UnitTest/SynchronizerBaseTest.cs | using ApprovalTests;
using ApprovalTests.Namers;
using ApprovalTests.Reporters;
using Gigobyte.Daterpillar;
using Gigobyte.Daterpillar.Aggregation;
using Gigobyte.Daterpillar.Migration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;
namespace Tests.Daterpillar.UnitTest
{
[TestClass]
[UseApprovalSubdirectory(nameof(ApprovalTests))]
[UseReporter(typeof(DiffReporter), typeof(ClipboardReporter))]
public class SynchronizerBaseTest
{
[TestMethod]
[Owner(Test.Dev.Ackara)]
public void GenerateScript_should_return_an_empty_byte_array_when_both_schemas_are_equal()
{
// Arrange
var source = GetOldSchema();
var target = GetOldSchema();
var sut = new FakeSynchronizer();
// Act
var actual = sut.GenerateScript(source, target);
// Assert
Approvals.VerifyBinaryFile(actual, "sql");
}
[TestMethod]
[Owner(Test.Dev.Ackara)]
public void GenerateScript_should_return_the_bytes_of_the_update_script_when_the_schemas_passed_are_not_equal()
{
// Arrange
var source = Mock.Create<ISchemaAggregator>();
source.Arrange(x => x.FetchSchema())
.Returns(GetNewSchema())
.OccursOnce();
var target = Mock.Create<ISchemaAggregator>();
target.Arrange(x => x.FetchSchema())
.Returns(GetOldSchema())
.OccursOnce();
var sut = new FakeSynchronizer();
// Act
var result = sut.GenerateScript(source, target);
// Assert
Approvals.VerifyBinaryFile(result, "sql");
source.Assert();
target.Assert();
}
#region Private Members
private static Schema GetOldSchema()
{
var schema = new Schema();
return schema;
}
public static Schema GetNewSchema()
{
var schema = new Schema();
return schema;
}
private class FakeSynchronizer : SynchronizerBase
{
}
#endregion Private Members
}
} | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests.Daterpillar.UnitTest
{
[TestClass]
public class SynchronizerBaseTest
{
[TestMethod]
[Owner(Test.Dev.Ackara)]
public void TestMethod1()
{
}
}
}
| mit | C# |
2eff47d56df3743cfc14050e1c1c6307147d6f0a | update UpdateInfo() | yasokada/unity-160820-Inventory-UI | Assets/InventoryCS.cs | Assets/InventoryCS.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using NS_SampleData;
using NS_MyStringUtil;
/*
* v0.2 2016 Aug. 21
* - add UpdateInfo()
* - add [MyStringUtil.cs]
* - add OpenURL()
* v0.1 2016 Aug. 21
* - add MoveColumn()
* - add MoveRow()
* - add SampleData.cs
* - add UI components (unique ID, Case No, Row, Column, About, DataSheet)
*/
public class InventoryCS : MonoBehaviour {
public InputField ID_uniqueID;
public Text T_caseNo;
public Text T_row;
public Text T_column;
public InputField IF_name;
public Text T_about;
public Text T_datasheetURL;
// TOOD: 0m > put other place to declear
const int kIndex_caseNo = 0;
const int kIndex_row = 1;
const int kIndex_column = 2;
const int kIndex_name = 3;
const int kIndex_about = 4;
const int kIndex_dataSheetURL = 5;
void Start () {
T_about.text = NS_SampleData.SampleData.GetDataOfRow (0);
}
void Update () {
}
private void UpdateInfo(string datstr) {
T_caseNo.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_caseNo);
T_row.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_row);
T_column.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_column);
IF_name.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_name);
T_about.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_about);
T_datasheetURL.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_dataSheetURL);
}
public void MoveRow(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfRow (0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfRow (1);
UpdateInfo (dtstr);
}
}
public void MoveColumn(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfColumn(0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfColumn (1);
UpdateInfo (dtstr);
T_caseNo.text = MyStringUtil.ExtractCsvColumn (dtstr, kIndex_caseNo);
T_about.text = dtstr;
}
}
public void OpenURL() {
Application.OpenURL (T_datasheetURL.text);
}
} | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using NS_SampleData;
using NS_MyStringUtil;
/*
* - add UpdateInfo()
* - add [MyStringUtil.cs]
* - add OpenURL()
* v0.1 2016 Aug. 21
* - add MoveColumn()
* - add MoveRow()
* - add SampleData.cs
* - add UI components (unique ID, Case No, Row, Column, About, DataSheet)
*/
public class InventoryCS : MonoBehaviour {
public InputField ID_uniqueID;
public Text T_caseNo;
public Text T_row;
public Text T_column;
public InputField IF_name;
public Text T_about;
public Text T_datasheetURL;
const int kIndex_caseNo = 0;
const int kIndex_row = 1;
const int kIndex_column = 2;
const int kIndex_dataSheetURL = 5; // TODO: put other place to declare
void Start () {
T_about.text = NS_SampleData.SampleData.GetDataOfRow (0);
}
void Update () {
}
private void UpdateInfo(string datstr) {
T_caseNo.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_caseNo);
T_row.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_row);
T_column.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_column);
T_about.text = datstr;
T_datasheetURL.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_dataSheetURL);
}
public void MoveRow(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfRow (0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfRow (1);
UpdateInfo (dtstr);
}
}
public void MoveColumn(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfColumn(0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfColumn (1);
UpdateInfo (dtstr);
T_caseNo.text = MyStringUtil.ExtractCsvColumn (dtstr, kIndex_caseNo);
T_about.text = dtstr;
}
}
public void OpenURL() {
Application.OpenURL (T_datasheetURL.text);
}
} | mit | C# |
ff945873b6caffa0f8991a92b2507b7e9fa32a5c | Add back argument check for TypeForwardedFromAttribute (#16680) | wtgodbe/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx,ptoonen/corefx,Jiayili1/corefx,mmitche/corefx,BrennanConroy/corefx,wtgodbe/corefx,ptoonen/corefx,shimingsg/corefx,ericstj/corefx,Jiayili1/corefx,ericstj/corefx,Jiayili1/corefx,mmitche/corefx,ericstj/corefx,BrennanConroy/corefx,ptoonen/corefx,Jiayili1/corefx,ptoonen/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,ericstj/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ViktorHofer/corefx,mmitche/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,wtgodbe/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,mmitche/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx | src/Common/src/CoreLib/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs | src/Common/src/CoreLib/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
public sealed class TypeForwardedFromAttribute : Attribute
{
public TypeForwardedFromAttribute(string assemblyFullName)
{
if (string.IsNullOrEmpty(assemblyFullName))
throw new ArgumentNullException(nameof(assemblyFullName));
AssemblyFullName = assemblyFullName;
}
public string AssemblyFullName { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
public sealed class TypeForwardedFromAttribute : Attribute
{
public TypeForwardedFromAttribute(string assemblyFullName)
{
AssemblyFullName = assemblyFullName;
}
public string AssemblyFullName { get; }
}
}
| mit | C# |
9ae369d6596485763dee715ab80925d5dd0b2c00 | Update DownloadInfo | witoong623/TirkxDownloader,witoong623/TirkxDownloader | Framework/DownloadInfo.cs | Framework/DownloadInfo.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework
{
public enum DownloadStatus { Queue, Complete, Downloading, Error }
public class DownloadInfo
{
public string FileName { get; set; }
public string DownloadLink { get; set; }
public string SaveLocation { get; set; }
public DateTime AddDate { get; set; }
public DateTime? CompleteDate { get; set; }
public DownloadStatus Status { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework
{
public enum DownloadStatus { Queue, Complete, Error }
public class DownloadInfo
{
public string FileName { get; set; }
public string DownloadLink { get; set; }
public string SaveDestination { get; set; }
public DateTime AddDate { get; set; }
public DateTime CompleteDate { get; set; }
public DownloadStatus Status { get; set; }
}
}
| mit | C# |
85b46b9999adb92d9c02b0cdc7338db9562f24ce | Fix warnings. | JohanLarsson/Gu.Reactive | Gu.Reactive.Demo/Converters/BooleanToVisibilityConverter.cs | Gu.Reactive.Demo/Converters/BooleanToVisibilityConverter.cs | namespace Gu.Reactive.Demo.Converters
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
[MarkupExtensionReturnType(typeof(BooleanToVisibilityConverter))]
[ValueConversion(typeof(bool?), typeof(Visibility))]
public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
public Visibility WhenTrue { get; set; } = Visibility.Visible;
public Visibility WhenFalse { get; set; } = Visibility.Hidden;
public Visibility WhenNull { get; set; } = Visibility.Hidden;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value switch
{
true => this.WhenTrue,
false => this.WhenTrue,
null => this.WhenNull,
_ => throw new ArgumentException("Expected bool?"),
};
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
public override object ProvideValue(IServiceProvider serviceProvider) => this;
}
}
| namespace Gu.Reactive.Demo.Converters
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
[MarkupExtensionReturnType(typeof(BooleanToVisibilityConverter))]
[ValueConversion(typeof(bool?), typeof(Visibility))]
public class BooleanToVisibilityConverter : MarkupExtension, IValueConverter
{
public Visibility WhenTrue { get; set; } = Visibility.Visible;
public Visibility WhenFalse { get; set; } = Visibility.Hidden;
public Visibility WhenNull { get; set; } = Visibility.Hidden;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var meh = value as bool?;
if (meh is null)
{
return this.WhenNull;
}
return meh == true
? this.WhenTrue
: this.WhenFalse;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
public override object ProvideValue(IServiceProvider serviceProvider) => this;
}
}
| mit | C# |
3928e82c2d586b52e7d33f2085c5afdec6f592cf | Check that a particular replacement is working well | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib.Tests/Variables/ValSimpleTest.cs | LINQToTTree/LINQToTTreeLib.Tests/Variables/ValSimpleTest.cs | // <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Variables
{
/// <summary>This class contains parameterized unit tests for ValSimple</summary>
[TestClass]
public partial class ValSimpleTest
{
#if false
/// <summary>Test stub for .ctor(String)</summary>
[PexMethod]
internal ValSimple Constructor(string v)
{
ValSimple target = new ValSimple(v, typeof(int));
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
return target;
}
[PexMethod]
internal ValSimple TestCTorWithType(string v, Type t)
{
ValSimple target = new ValSimple(v, t);
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
Assert.IsNotNull(target.Type, "Expected some value for the type!");
return target;
}
#endif
[TestMethod]
public void RenameMethodCall()
{
var target = new ValSimple("(*aNTH1F_1233).Fill(((double)aInt32_326),1.0*((1.0*1.0)*1.0))", typeof(int));
target.RenameRawValue("aInt32_326", "aInt32_37");
Assert.AreEqual("(*aNTH1F_1233).Fill(((double)aInt32_37),1.0*((1.0*1.0)*1.0))", target.RawValue);
}
}
}
| // <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Variables
{
/// <summary>This class contains parameterized unit tests for ValSimple</summary>
[TestClass]
public partial class ValSimpleTest
{
#if false
/// <summary>Test stub for .ctor(String)</summary>
[PexMethod]
internal ValSimple Constructor(string v)
{
ValSimple target = new ValSimple(v, typeof(int));
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
return target;
}
[PexMethod]
internal ValSimple TestCTorWithType(string v, Type t)
{
ValSimple target = new ValSimple(v, t);
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
Assert.IsNotNull(target.Type, "Expected some value for the type!");
return target;
}
#endif
}
}
| lgpl-2.1 | C# |
cab6283c5d53e497a2f9a9f784ef6ce8a3329f7a | Bump version | klesta490/BTDB,karasek/BTDB,Bobris/BTDB | BTDB/Properties/AssemblyInfo.cs | BTDB/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("3.3.0.0")]
[assembly: AssemblyFileVersion("3.3.0.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("3.2.3.0")]
[assembly: AssemblyFileVersion("3.2.3.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
| mit | C# |
c0a773f1f9e9a93454b6382d18829db166930e4c | reset GlobalAssemblyInfo | michael-wolfenden/TypeScanner | src/GlobalAssemblyInfo.cs | src/GlobalAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyDescription("Fluent interface for scanning for types")]
[assembly: AssemblyProduct("TypeScanner")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0")]
[assembly: AssemblyCopyright("Copyright © Michael Wolfenden 2015")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| using System.Reflection;
[assembly: AssemblyDescription("Fluent interface for scanning for types")]
[assembly: AssemblyProduct("TypeScanner")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+2.Branch.master.Sha.73d8674464f3ce3aa4b1e6dff757a4753c9dd11c")]
[assembly: AssemblyCopyright("Copyright © Michael Wolfenden 2015")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| bsd-3-clause | C# |
5b5080de1d41b346399f9346cc191599c88cd590 | clone CsvOptions | RobertGiesecke/PlainCsv | src/Library/CsvOptions.cs | src/Library/CsvOptions.cs | using System;
namespace RGiesecke.PlainCsv
{
[Flags]
public enum CsvFlags
{
None = 0,
UseHeaderRow = 1,
QuoteFormulars = 2,
}
public sealed class CsvOptions
{
public static readonly CsvOptions Default = new CsvOptions();
public static readonly CsvOptions Excel = new CsvOptions('"', ',', CsvFlags.QuoteFormulars | CsvFlags.UseHeaderRow);
public char QuoteChar { get; private set; }
public char Delimiter { get; private set; }
public CsvFlags CsvFlags { get; private set; }
public bool QuoteFormulars
{
get
{
return (CsvFlags & CsvFlags.QuoteFormulars) == CsvFlags.QuoteFormulars;
}
}
public bool UseHeaderRow
{
get
{
return (CsvFlags & CsvFlags.UseHeaderRow) == CsvFlags.UseHeaderRow;
}
}
public CsvOptions(char quoteChar, char delimiter, CsvFlags? csvFlags = null)
{
QuoteChar = quoteChar;
Delimiter = delimiter;
CsvFlags = csvFlags ?? Default.CsvFlags;
}
public CsvOptions()
: this('"', ',', CsvFlags.UseHeaderRow)
{ }
public CsvOptions(CsvOptions source, char? quoteChar = null, char? delimiter = null, CsvFlags? csvFlags = null)
:this(quoteChar ?? source.QuoteChar,
delimiter ?? source.Delimiter,
csvFlags ?? source.CsvFlags)
{}
}
} | using System;
namespace RGiesecke.PlainCsv
{
[Flags]
public enum CsvFlags
{
None = 0,
UseHeaderRow = 1,
QuoteFormulars = 2,
}
public sealed class CsvOptions
{
public static readonly CsvOptions Default = new CsvOptions();
public static readonly CsvOptions Excel = new CsvOptions('"', ',', CsvFlags.QuoteFormulars | CsvFlags.UseHeaderRow);
public char QuoteChar { get; private set; }
public char Delimiter { get; private set; }
public CsvFlags CsvFlags { get; private set; }
public bool QuoteFormulars
{
get
{
return (CsvFlags & CsvFlags.QuoteFormulars) == CsvFlags.QuoteFormulars;
}
}
public bool UseHeaderRow
{
get
{
return (CsvFlags & CsvFlags.UseHeaderRow) == CsvFlags.UseHeaderRow;
}
}
public CsvOptions(char quoteChar, char delimiter, CsvFlags? csvFlags = null)
{
QuoteChar = quoteChar;
Delimiter = delimiter;
CsvFlags = csvFlags ?? Default.CsvFlags;
}
public CsvOptions()
: this('"', ',', CsvFlags.UseHeaderRow)
{ }
}
} | mit | C# |
e3cec9cf6c7251c16d075bf0b27a8546f7ca0692 | Simplify column assignment | NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu | osu.Game.Rulesets.Mania/Edit/Blueprints/ManiaPlacementBlueprint.cs | osu.Game.Rulesets.Mania/Edit/Blueprints/ManiaPlacementBlueprint.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.Input;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Input;
namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
public abstract class ManiaPlacementBlueprint<T> : PlacementBlueprint,
IRequireHighFrequencyMousePosition // the playfield could be moving behind us
where T : ManiaHitObject
{
protected new T HitObject => (T)base.HitObject;
private Column column;
public Column Column
{
get => column;
set
{
if (value == column)
return;
column = value;
HitObject.Column = column.Index;
}
}
protected ManiaPlacementBlueprint(T hitObject)
: base(hitObject)
{
RelativeSizeAxes = Axes.None;
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (e.Button != MouseButton.Left)
return false;
if (Column == null)
return false;
BeginPlacement(true);
return true;
}
public override void UpdatePosition(SnapResult result)
{
if (!PlacementActive)
Column = (result as ManiaSnapResult)?.Column;
}
}
}
| // 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.Input;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Input;
namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
public abstract class ManiaPlacementBlueprint<T> : PlacementBlueprint,
IRequireHighFrequencyMousePosition // the playfield could be moving behind us
where T : ManiaHitObject
{
protected new T HitObject => (T)base.HitObject;
protected Column Column;
protected ManiaPlacementBlueprint(T hitObject)
: base(hitObject)
{
RelativeSizeAxes = Axes.None;
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (e.Button != MouseButton.Left)
return false;
if (Column == null)
return base.OnMouseDown(e);
HitObject.Column = Column.Index;
BeginPlacement(true);
return true;
}
public override void UpdatePosition(SnapResult result)
{
if (!PlacementActive)
Column = (result as ManiaSnapResult)?.Column;
}
}
}
| mit | C# |
09f105083e4a8f2343b8905d77940807ffebd84b | Add extension to decode a string from an ArraySegment<byte>. | mysql-net/MySqlConnector,mysql-net/MySqlConnector,gitsno/MySqlConnector,gitsno/MySqlConnector | src/MySql.Data/Utility.cs | src/MySql.Data/Utility.cs | using System;
using System.Text;
namespace MySql.Data
{
internal static class Utility
{
public static void Dispose<T>(ref T disposable)
where T : class, IDisposable
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
}
}
public static string GetString(this Encoding encoding, ArraySegment<byte> arraySegment)
=> encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
}
}
| using System;
namespace MySql.Data
{
internal static class Utility
{
public static void Dispose<T>(ref T disposable)
where T : class, IDisposable
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
}
}
}
}
| mit | C# |
f05e79616dffa6cefe61d038d9ec885d55449596 | Add Table<T>(Expression<Func<T, object>>) method | apemost/Newq,apemost/Newq | src/Newq/Customization.cs | src/Newq/Customization.cs | namespace Newq
{
using System;
/// <summary>
///
/// </summary>
public abstract class Customization
{
/// <summary>
///
/// </summary>
protected Context context;
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public Customization(Context context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
this.context = context;
}
/// <summary>
/// Returns a string that represents the current customization.
/// </summary>
/// <returns></returns>
public abstract string GetCustomization();
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr"></param>
/// <returns></returns>
public Column Table<T>(Expression<Func<T, object>> expr)
{
var split = expr.Body.ToString().Split("(.)".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var columnName = split[split.Length - 1];
return context[typeof(T).Name, columnName];
}
}
}
| namespace Newq
{
using System;
/// <summary>
///
/// </summary>
public abstract class Customization
{
/// <summary>
///
/// </summary>
protected Context context;
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public Customization(Context context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
this.context = context;
}
/// <summary>
/// Returns a string that represents the current customization.
/// </summary>
/// <returns></returns>
public abstract string GetCustomization();
}
}
| mit | C# |
8710ddeb6e58d1d0a1588af27c76f404848274cc | bump version | chinaboard/PureCat | PureCat/Properties/AssemblyInfo.cs | PureCat/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("PureCat")]
[assembly: AssemblyDescription("Cat.Net Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PureCat")]
[assembly: AssemblyCopyright("Copyright © chinaboard 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("df6be1db-4713-4456-9a2a-6e3c8af94a24")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.1.9.0")]
[assembly: AssemblyVersion("0.1.9.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("PureCat")]
[assembly: AssemblyDescription("Cat.Net Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PureCat")]
[assembly: AssemblyCopyright("Copyright © chinaboard 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("df6be1db-4713-4456-9a2a-6e3c8af94a24")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("0.1.8.0")]
[assembly: AssemblyVersion("0.1.8.*")]
| mit | C# |
967238e2694127b2bdd50e1f4f3a1efd59d2fb0b | Add comment explaining scale | UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu | osu.Game.Rulesets.Mania/Mods/ManiaModHidden.cs | osu.Game.Rulesets.Mania/Mods/ManiaModHidden.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModHidden : ModHidden, IApplicableToDrawableRuleset<ManiaHitObject>
{
public override string Description => @"Keys fade out before you hit them!";
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new[] { typeof(ModFlashlight<ManiaHitObject>) };
public virtual void ApplyToDrawableRuleset(DrawableRuleset<ManiaHitObject> drawableRuleset)
{
ManiaPlayfield maniaPlayfield = (ManiaPlayfield)drawableRuleset.Playfield;
foreach (Column column in maniaPlayfield.Stages.SelectMany(stage => stage.Columns))
{
HitObjectContainer hoc = column.HitObjectArea.HitObjectContainer;
Container hocParent = (Container)hoc.Parent;
hocParent.Remove(hoc);
hocParent.Add(CreateCover().WithChild(hoc).With(c =>
{
c.RelativeSizeAxes = Axes.Both;
c.Coverage = 0.5f;
}));
}
}
protected virtual PlayfieldCoveringContainer CreateCover() => new ModHiddenCoveringContainer();
private class ModHiddenCoveringContainer : PlayfieldCoveringContainer
{
public ModHiddenCoveringContainer()
{
// This cover extends outwards from the hit position.
Cover.Scale = new Vector2(1, -1);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModHidden : ModHidden, IApplicableToDrawableRuleset<ManiaHitObject>
{
public override string Description => @"Keys fade out before you hit them!";
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new[] { typeof(ModFlashlight<ManiaHitObject>) };
public virtual void ApplyToDrawableRuleset(DrawableRuleset<ManiaHitObject> drawableRuleset)
{
ManiaPlayfield maniaPlayfield = (ManiaPlayfield)drawableRuleset.Playfield;
foreach (Column column in maniaPlayfield.Stages.SelectMany(stage => stage.Columns))
{
HitObjectContainer hoc = column.HitObjectArea.HitObjectContainer;
Container hocParent = (Container)hoc.Parent;
hocParent.Remove(hoc);
hocParent.Add(CreateCover().WithChild(hoc).With(c =>
{
c.RelativeSizeAxes = Axes.Both;
c.Coverage = 0.5f;
}));
}
}
protected virtual PlayfieldCoveringContainer CreateCover() => new ModHiddenCoveringContainer();
private class ModHiddenCoveringContainer : PlayfieldCoveringContainer
{
public ModHiddenCoveringContainer()
{
Cover.Scale = new Vector2(1, -1);
}
}
}
}
| mit | C# |
b3efe50ba3da0eca80b53e45f2199166e30bfaf4 | Refactor incorrectly named method. | mrward/monodevelop-paket-addin | src/MonoDevelop.Paket/MonoDevelop.Paket.NodeBuilders/NuGetPackageReferenceNodeCommandHandler.cs | src/MonoDevelop.Paket/MonoDevelop.Paket.NodeBuilders/NuGetPackageReferenceNodeCommandHandler.cs | //
// NuGetPackageReferenceNodeCommandHandler.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (c) 2015 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
using MonoDevelop.Ide.Commands;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.Paket.NodeBuilders
{
public class NuGetPackageReferenceNodeCommandHandler : NodeCommandHandler
{
[CommandUpdateHandler (EditCommands.Delete)]
public void UpdateRemoveItem (CommandInfo info)
{
info.Enabled = CanDeleteMultipleItems ();
info.Text = GettextCatalog.GetString ("Remove");
}
public override bool CanDeleteMultipleItems ()
{
return !MultipleSelectedNodes;
}
public override void DeleteItem ()
{
ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateRemoveNuGetPackageMessage (ReferenceNode.Id);
try {
RemovePackageReference (progressMessage);
} catch (Exception ex) {
PaketServices.ActionRunner.ShowError (progressMessage, ex);
}
}
NuGetPackageReferenceNode ReferenceNode {
get { return (NuGetPackageReferenceNode)CurrentNode.DataItem; }
}
void RemovePackageReference (ProgressMonitorStatusMessage progressMessage)
{
var action = new RemoveNuGetFromProjectPaketAction (
ReferenceNode.Id,
ReferenceNode.Project);
PaketServices.ActionRunner.Run (progressMessage, action);
}
}
}
| //
// NuGetPackageReferenceNodeCommandHandler.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (c) 2015 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
using MonoDevelop.Ide.Commands;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.Paket.NodeBuilders
{
public class NuGetPackageReferenceNodeCommandHandler : NodeCommandHandler
{
[CommandUpdateHandler (EditCommands.Delete)]
public void UpdateRemoveItem (CommandInfo info)
{
info.Enabled = CanDeleteMultipleItems ();
info.Text = GettextCatalog.GetString ("Remove");
}
public override bool CanDeleteMultipleItems ()
{
return !MultipleSelectedNodes;
}
public override void DeleteItem ()
{
ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateRemoveNuGetPackageMessage (ReferenceNode.Id);
try {
RemoveDependency (progressMessage);
} catch (Exception ex) {
PaketServices.ActionRunner.ShowError (progressMessage, ex);
}
}
NuGetPackageReferenceNode ReferenceNode {
get { return (NuGetPackageReferenceNode)CurrentNode.DataItem; }
}
void RemoveDependency (ProgressMonitorStatusMessage progressMessage)
{
var action = new RemoveNuGetFromProjectPaketAction (
ReferenceNode.Id,
ReferenceNode.Project);
PaketServices.ActionRunner.Run (progressMessage, action);
}
}
}
| mit | C# |
1e71a6fda42e80c4a3e52154ad73b14fb93ccc64 | Move to iPhone X | MarcinHoppe/AspNetCore.Csrf.Sample,MarcinHoppe/AspNetCore.Csrf.Sample | AspNetCore.Csrf.EvilSite/Views/Home/Index.cshtml | AspNetCore.Csrf.EvilSite/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<h1>Want to win an iPhone X?</h1>
<h2>Your brand new iPhone X is just one click away!</h2>
<iframe style="display: none;" name="evil-iframe"></iframe>
<form id="evilform" action="http://web.local:57082/profile/update" method="post" target="evil-iframe">
<input type="hidden" name="BankAccount" value="999999999999" />
</form>
<input type="button" value="Win an iPhone!" onclick="submitEvilForm()" />
<script>
var submitEvilForm = function() {
$("#evilform").submit();
alert("Thanks for entering the contest! Good luck!");
};
</script> | @{
ViewData["Title"] = "Home Page";
}
<h1>Want to win an iPhone?</h1>
<h2>Your brand new iPhone is just one click away!</h2>
<iframe style="display: none;" name="evil-iframe"></iframe>
<form id="evilform" action="http://web.local:57082/profile/update" method="post" target="evil-iframe">
<input type="hidden" name="BankAccount" value="999999999999" />
</form>
<input type="button" value="Win an iPhone!" onclick="submitEvilForm()" />
<script>
var submitEvilForm = function() {
$("#evilform").submit();
alert("Thanks for entering the contest! Good luck!");
};
</script> | mit | C# |
4b0ca781769a417a1cd832ad71eff251c92b625b | accelerate when the speedPercentage is below 0 | enormand/cyber-space-shooter | Assets/Scripts/Objects/Managers/EngineManager.cs | Assets/Scripts/Objects/Managers/EngineManager.cs | using UnityEngine;
using System.Collections;
public class EngineManager : MonoBehaviour {
public float minSpeed, maxSpeed, accelerationFactor, brakeFactor;
// Called after the speed has been updated.
public delegate void SpeedUpdatedDelegate();
public event SpeedUpdatedDelegate OnSpeedUpdated;
private float speed, speedPercentage;
private Rigidbody rigidBody;
private bool speedUpdated = false;
public const float MIN_PERCENTAGE = 0, MAX_PERCENTAGE = 100;
void Awake () {
rigidBody = GetComponent<Rigidbody> ();
ConfigurateSpeed ();
}
void LateUpdate () {
if (OnSpeedUpdated != null && speedUpdated == true) {
speedUpdated = false;
OnSpeedUpdated ();
}
}
/*
* Getters / Setters.
*/
public float SpeedPercentage {
get { return speedPercentage; }
set { AdjustSpeed (value); }
}
/*
* Return the measured speed of the rigidbody.
*/
public float RealSpeedPercentage (bool showNegativeValues = false) {
float realSpeed = rigidBody.velocity.magnitude / Time.fixedDeltaTime;
float realSpeedPercentage = Mathf.Ceil((realSpeed - minSpeed) / (maxSpeed - minSpeed) * MAX_PERCENTAGE);
if (!showNegativeValues) {
realSpeedPercentage = Mathf.Max (realSpeedPercentage, MIN_PERCENTAGE);
}
return realSpeedPercentage;
}
/*
* Apply a force on the rigidbody to adjust its speed on the desired speed.
*/
public void Move () {
float realSpeedPercentage = RealSpeedPercentage (true);
float speedPercentageCeil = Mathf.Ceil (speedPercentage);
if (realSpeedPercentage == speedPercentageCeil) {
return;
}
Vector3 engineForce = transform.forward * speed * Time.fixedDeltaTime;
if (realSpeedPercentage < speedPercentageCeil) {
rigidBody.AddForce (engineForce * accelerationFactor, ForceMode.Force);
} else if (realSpeedPercentage > speedPercentageCeil) {
rigidBody.AddForce (-engineForce * brakeFactor, ForceMode.Force);
}
speedUpdated = true;
}
/*
* Init the speed at its minimum.
*/
void ConfigurateSpeed () {
if (minSpeed > maxSpeed) {
Debug.LogError (name + " (EngineController): Min Speed is greater than Max Speed. Please set Min Speed lower than Max Speed.");
}
speed = minSpeed;
speedPercentage = MIN_PERCENTAGE;
}
/*
* Recompute the speed.
*/
void AdjustSpeed (float speedPercentage) {
if (speedPercentage < MIN_PERCENTAGE || speedPercentage > MAX_PERCENTAGE) {
Debug.LogError (name + " (EngineController::AjustSpeed): speedPercentage should be set within the interval of 0 to 100.");
return;
}
this.speedPercentage = speedPercentage;
speed = speedPercentage * (maxSpeed - minSpeed) / MAX_PERCENTAGE + minSpeed;
speedUpdated = true;
}
}
| using UnityEngine;
using System.Collections;
public class EngineManager : MonoBehaviour {
public float minSpeed, maxSpeed, accelerationFactor, brakeFactor;
// Called after the speed has been updated.
public delegate void SpeedUpdatedDelegate();
public event SpeedUpdatedDelegate OnSpeedUpdated;
private float speed, speedPercentage;
private Rigidbody rigidBody;
private bool speedUpdated = false;
public const float MIN_PERCENTAGE = 0, MAX_PERCENTAGE = 100;
void Awake () {
rigidBody = GetComponent<Rigidbody> ();
ConfigurateSpeed ();
}
void LateUpdate () {
if (OnSpeedUpdated != null && speedUpdated == true) {
speedUpdated = false;
OnSpeedUpdated ();
}
}
/*
* Getters / Setters.
*/
public float SpeedPercentage {
get { return speedPercentage; }
set { AdjustSpeed (value); }
}
/*
* Return the measured speed of the rigidbody.
*/
public float RealSpeedPercentage () {
float realSpeed = rigidBody.velocity.magnitude / Time.fixedDeltaTime;
float realSpeedPercentage = (realSpeed - minSpeed) / (maxSpeed - minSpeed) * MAX_PERCENTAGE;
realSpeedPercentage = Mathf.Ceil(Mathf.Max(realSpeedPercentage, MIN_PERCENTAGE));
return realSpeedPercentage;
}
/*
* Apply a force on the rigidbody to adjust its speed on the desired speed.
*/
public void Move () {
float realSpeedPercentage = RealSpeedPercentage ();
float speedPercentageCeil = Mathf.Ceil (speedPercentage);
if (realSpeedPercentage == speedPercentageCeil) {
return;
}
Vector3 engineForce = transform.forward * speed * Time.fixedDeltaTime;
if (realSpeedPercentage < speedPercentageCeil) {
rigidBody.AddForce (engineForce * accelerationFactor, ForceMode.Force);
} else if (realSpeedPercentage > speedPercentageCeil) {
rigidBody.AddForce (-engineForce * brakeFactor, ForceMode.Force);
}
speedUpdated = true;
}
/*
* Init the speed at its minimum.
*/
void ConfigurateSpeed () {
if (minSpeed > maxSpeed) {
Debug.LogError (name + " (EngineController): Min Speed is greater than Max Speed. Please set Min Speed lower than Max Speed.");
}
speed = minSpeed;
speedPercentage = MIN_PERCENTAGE;
}
/*
* Recompute the speed.
*/
void AdjustSpeed (float speedPercentage) {
if (speedPercentage < MIN_PERCENTAGE || speedPercentage > MAX_PERCENTAGE) {
Debug.LogError (name + " (EngineController::AjustSpeed): speedPercentage should be set within the interval of 0 to 100.");
return;
}
this.speedPercentage = speedPercentage;
speed = speedPercentage * (maxSpeed - minSpeed) / MAX_PERCENTAGE + minSpeed;
speedUpdated = true;
}
}
| mit | C# |
259bc31b495ef2dd2ee2d917c7380cac87908d33 | Add edit link | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Vehicles/List.cshtml | Battery-Commander.Web/Views/Vehicles/List.cshtml | @model IEnumerable<Vehicle>
@{
ViewBag.Title = "Vehicle Tracker";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Count()</span> @Html.ActionLink("Add New", "New", "Vehicles", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Bumper)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Seats)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var vehicle in Model)
{
<tr>
<td>@Html.DisplayFor(_ => vehicle.Bumper)</td>
<td>@Html.DisplayFor(_ => vehicle.Type)</td>
<td>@Html.DisplayFor(_ => vehicle.Status)</td>
<td>@Html.DisplayFor(_ => vehicle.Seats)</td>
<td>@Html.DisplayFor(_ => vehicle.Unit)</td>
<td>@Html.ActionLink("Edit", "Edit", new { vehicle.Id })
</tr>
}
</tbody>
</table>
| @model IEnumerable<Vehicle>
@{
ViewBag.Title = "Vehicle Tracker";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Count()</span> @Html.ActionLink("Add New", "New", "Vehicles", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Bumper)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Seats)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
</tr>
</thead>
<tbody>
@foreach (var vehicle in Model)
{
<tr>
<td>@Html.DisplayFor(_ => vehicle.Bumper)</td>
<td>@Html.DisplayFor(_ => vehicle.Type)</td>
<td>@Html.DisplayFor(_ => vehicle.Status)</td>
<td>@Html.DisplayFor(_ => vehicle.Seats)</td>
<td>@Html.DisplayFor(_ => vehicle.Unit)</td>
</tr>
}
</tbody>
</table>
| mit | C# |
77ce2a8d1ca2f0ac9b5268696aa8aa885d494a0e | Update ZoomBorderTests.cs | PanAndZoom/PanAndZoom,wieslawsoltes/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,wieslawsoltes/PanAndZoom | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs | tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs | using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomBorderTests
{
[Fact]
public void ZoomBorder_Ctor()
{
var target = new ZoomBorder();
Assert.NotNull(target);
Assert.Equal(ButtonName.Middle, target.PanButton);
Assert.Equal(1.2, target.ZoomSpeed);
Assert.Equal(StretchMode.Uniform, target.Stretch);
Assert.Equal(1.0, target.ZoomX);
Assert.Equal(1.0, target.ZoomY);
Assert.Equal(0.0, target.OffsetX);
Assert.Equal(0.0, target.OffsetY);
Assert.True(target.EnableConstrains);
Assert.Equal(double.NegativeInfinity, target.MinZoomX);
Assert.Equal(double.PositiveInfinity, target.MaxZoomX);
Assert.Equal(double.NegativeInfinity, target.MinZoomY);
Assert.Equal(double.PositiveInfinity, target.MaxZoomY);
Assert.Equal(double.NegativeInfinity, target.MinOffsetX);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetX);
Assert.Equal(double.NegativeInfinity, target.MinOffsetY);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetY);
Assert.True(target.EnablePan);
Assert.True(target.EnableZoom);
Assert.True(target.EnableGestureZoom);
Assert.True(target.EnableGestureRotation);
Assert.True(target.EnableGestureTranslation);
}
}
}
| using Xunit;
namespace Avalonia.Controls.PanAndZoom.UnitTests
{
public class ZoomBorderTests
{
[Fact]
public void ZoomBorder_Ctor()
{
var target = new ZoomBorder();
Assert.NotNull(target);
Assert.Equal(ButtonName.Middle, target.PanButton);
Assert.Equal(1.2, target.ZoomSpeed);
Assert.Equal(StretchMode.Uniform, target.Stretch);
Assert.Equal(1.0, target.ZoomX);
Assert.Equal(1.0, target.ZoomY);
Assert.Equal(0.0, target.OffsetX);
Assert.Equal(0.0, target.OffsetY);
Assert.Equal(true, target.EnableConstrains);
Assert.Equal(double.NegativeInfinity, target.MinZoomX);
Assert.Equal(double.PositiveInfinity, target.MaxZoomX);
Assert.Equal(double.NegativeInfinity, target.MinZoomY);
Assert.Equal(double.PositiveInfinity, target.MaxZoomY);
Assert.Equal(double.NegativeInfinity, target.MinOffsetX);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetX);
Assert.Equal(double.NegativeInfinity, target.MinOffsetY);
Assert.Equal(double.PositiveInfinity, target.MaxOffsetY);
Assert.Equal(true, target.EnablePan);
Assert.Equal(true, target.EnableZoom);
Assert.Equal(true, target.EnableGestureZoom);
Assert.Equal(true, target.EnableGestureRotation);
Assert.Equal(true, target.EnableGestureTranslation);
}
}
}
| mit | C# |
c74d80d0afcf8d07398860a411d19b208ed0f4b2 | use separate tasks to prevent deadlock | andy-kohne/BuildLight | BuildLight.UWP/MainPage.xaml.cs | BuildLight.UWP/MainPage.xaml.cs | using BuildLight.Common.Extensions;
using BuildLight.Common.Models;
using BuildLight.Common.Services;
using BuildLight.Common.Services.BuildMonitor;
using BuildLight.Common.Services.TeamCity;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
namespace BuildLight.UWP
{
public sealed partial class MainPage : Page
{
readonly IBuildMonitorService _buildMonitorService;
readonly IVisualizationService _visualizationService;
readonly CancellationToken _cancellationToken;
public MainPage()
{
InitializeComponent();
_cancellationToken = new CancellationToken();
var settingsTask = Task.Run(GetSettingsAsync);
var pwmcontrollerTask = Task.Run(PwmControllerProxy.GetGontroller);
var pwmController =pwmcontrollerTask.Result;
var settings = settingsTask.Result;
var tcApiClient = new TeamCityApiClient(settings.Host, settings.UserName, settings.Password);
_visualizationService = new VisualizationService(settings.Visualizations, pwmController);
_visualizationService.Run(_cancellationToken);
_buildMonitorService = new BuildMonitorService(tcApiClient, settings);
_buildMonitorService.BuildStatusEvent += _visualizationService.HandleBuildEvent;
_buildMonitorService.MonitorAsync(_cancellationToken);
}
private async Task<Settings> GetSettingsAsync()
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.json");
var text = await FileIO.ReadTextAsync(file);
return text.ConvertJsonTo<Settings>();
}
}
}
| using BuildLight.Common.Extensions;
using BuildLight.Common.Models;
using BuildLight.Common.Services;
using BuildLight.Common.Services.BuildMonitor;
using BuildLight.Common.Services.TeamCity;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
namespace BuildLight.UWP
{
public sealed partial class MainPage : Page
{
readonly IBuildMonitorService _buildMonitorService;
readonly IVisualizationService _visualizationService;
readonly CancellationToken _cancellationToken;
public MainPage()
{
InitializeComponent();
_cancellationToken = new CancellationToken();
var settings = GetSettingsAsync().Result;
var tcApiClient = new TeamCityApiClient(settings.Host, settings.UserName, settings.Password);
var pwmController = PwmControllerProxy.GetGontroller().Result;
_visualizationService = new VisualizationService(settings.Visualizations, pwmController);
_visualizationService.Run(_cancellationToken);
_buildMonitorService = new BuildMonitorService(tcApiClient, settings);
_buildMonitorService.BuildStatusEvent += _visualizationService.HandleBuildEvent;
_buildMonitorService.MonitorAsync(_cancellationToken);
}
private async Task<Settings> GetSettingsAsync()
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.json");
var text = await FileIO.ReadTextAsync(file);
return text.ConvertJsonTo<Settings>();
}
}
}
| mit | C# |
1de7c61fc2bf71dafd112446141fa2c07c87c0c5 | reduce framerate | pako1337/raim,pako1337/raim,pako1337/raim | PaCode.Raim/Home/ArenaTicker.cs | PaCode.Raim/Home/ArenaTicker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace PaCode.Raim.Home
{
public class ArenaTicker
{
private readonly static ArenaTicker _instance = new ArenaTicker(GlobalHost.ConnectionManager.GetHubContext<RaimHub>().Clients);
private const int _updateInterval = 1000 / 30;
private readonly IHubConnectionContext<dynamic> _clients;
private readonly Timer _timer;
public static ArenaTicker Instance { get { return _instance; } }
private ArenaTicker(IHubConnectionContext<dynamic> clients)
{
_clients = clients;
_timer = new Timer(UpdateArena, null, _updateInterval, _updateInterval);
}
private void UpdateArena(object state)
{
var go = RaimHub.arena.UpdatePositions(DateTime.Now);
_clients.All.PlayerMoved(go);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace PaCode.Raim.Home
{
public class ArenaTicker
{
private readonly static ArenaTicker _instance = new ArenaTicker(GlobalHost.ConnectionManager.GetHubContext<RaimHub>().Clients);
private const int _updateInterval = 1000 / 60;
private readonly IHubConnectionContext<dynamic> _clients;
private readonly Timer _timer;
public static ArenaTicker Instance { get { return _instance; } }
private ArenaTicker(IHubConnectionContext<dynamic> clients)
{
_clients = clients;
_timer = new Timer(UpdateArena, null, _updateInterval, _updateInterval);
}
private void UpdateArena(object state)
{
var go = RaimHub.arena.UpdatePositions(DateTime.Now);
_clients.All.PlayerMoved(go);
}
}
} | mit | C# |
cbeabdcfd455c82b2fb27967ff85016ffbf68dc6 | Remove explicit context initialization. | os2kitos/kitos,os2kitos/kitos,miracle-as/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos | Presentation.Web/Global.asax.cs | Presentation.Web/Global.asax.cs | using System.Data.Entity;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Infrastructure.DataAccess;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Presentation.Web
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
// Turns off self reference looping when serializing models in API controlllers
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Support polymorphism in web api JSON output
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#)
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Convert all dates to UTC
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
}
}
}
| using System.Data.Entity;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Infrastructure.DataAccess;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Presentation.Web
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
// Turns off self reference looping when serializing models in API controlllers
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Support polymorphism in web api JSON output
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#)
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Convert all dates to UTC
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
// Create and seed database
var context = new KitosContext();
context.Database.Initialize(false);
}
}
}
| mpl-2.0 | C# |
c443238ee17068473dcd97ca133b5db78c4b29eb | Update AndroidBuildPostProcessor.cs | googleads/googleads-mobile-unity,googleads/googleads-mobile-unity | source/plugin/Assets/GoogleMobileAds/Editor/AndroidBuildPostProcessor.cs | source/plugin/Assets/GoogleMobileAds/Editor/AndroidBuildPostProcessor.cs | #if UNITY_ANDROID
using System;
using UnityEditor;
using UnityEditor.Callbacks;
using GoogleMobileAds.Editor;
public static class AndroidBuildPostProcessor
{
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget buildTarget, string path)
{
if (!GoogleMobileAdsSettings.Instance.IsAdManagerEnabled && !GoogleMobileAdsSettings.Instance.IsAdMobEnabled)
{
NotifyBuildFailure("Neither Ad Manager nor AdMob is enabled yet.");
}
if (GoogleMobileAdsSettings.Instance.IsAdMobEnabled && GoogleMobileAdsSettings.Instance.AdMobAndroidAppId.Length == 0)
{
NotifyBuildFailure(
"Android AdMob app ID is empty. Please enter a valid app ID to run ads properly.");
}
}
private static void NotifyBuildFailure(string message)
{
string prefix = "[GoogleMobileAds] ";
bool openSettings = EditorUtility.DisplayDialog(
"Google Mobile Ads", "Error: " + message, "Open Settings", "Close");
if (openSettings)
{
GoogleMobileAdsSettingsEditor.OpenInspector();
}
#if UNITY_2017_1_OR_NEWER
throw new BuildPlayerWindow.BuildMethodException(prefix + message);
#else
throw new OperationCanceledException(prefix + message);
#endif
}
}
#endif
| #if UNITY_ANDROID
using UnityEditor;
using UnityEditor.Callbacks;
using GoogleMobileAds.Editor;
public static class AndroidBuildPostProcessor
{
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget buildTarget, string path)
{
if (!GoogleMobileAdsSettings.Instance.IsAdManagerEnabled && !GoogleMobileAdsSettings.Instance.IsAdMobEnabled)
{
NotifyBuildFailure("Neither Ad Manager nor AdMob is enabled yet.");
}
if (GoogleMobileAdsSettings.Instance.IsAdMobEnabled && GoogleMobileAdsSettings.Instance.AdMobAndroidAppId.Length == 0)
{
NotifyBuildFailure(
"Android AdMob app ID is empty. Please enter a valid app ID to run ads properly.");
}
}
private static void NotifyBuildFailure(string message)
{
string prefix = "[GoogleMobileAds] ";
bool openSettings = EditorUtility.DisplayDialog(
"Google Mobile Ads", "Error: " + message, "Open Settings", "Close");
if (openSettings)
{
GoogleMobileAdsSettingsEditor.OpenInspector();
}
#if UNITY_2017_1_OR_NEWER
throw new BuildPlayerWindow.BuildMethodException(prefix + message);
#else
throw new OperationCanceledException(prefix + message);
#endif
}
}
#endif
| apache-2.0 | C# |
312646e5ebb61404a82bfbe6c7a5a0b033202d9c | Add Create Methods to Device Extenstion Model | cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings | DynThings.Data.Models/Device.cs | DynThings.Data.Models/Device.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DynThings.Data.Models
{
using System;
using System.Collections.Generic;
public partial class Device
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Device()
{
this.DeviceCommands = new HashSet<DeviceCommand>();
this.DeviceIOs = new HashSet<DeviceIO>();
this.Endpoints = new HashSet<Endpoint>();
}
public long ID { get; set; }
public string Title { get; set; }
public Nullable<long> StatusID { get; set; }
public Nullable<System.Guid> GUID { get; set; }
public Nullable<System.Guid> KeyPass { get; set; }
public string PinCode { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<DeviceCommand> DeviceCommands { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<DeviceIO> DeviceIOs { get; set; }
public virtual DeviceStatu DeviceStatu { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Endpoint> Endpoints { get; set; }
}
}
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DynThings.Data.Models
{
using System;
using System.Collections.Generic;
public partial class Device
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Device()
{
this.DeviceCommands = new HashSet<DeviceCommand>();
this.DeviceIOs = new HashSet<DeviceIO>();
this.Endpoints = new HashSet<Endpoint>();
}
public long ID { get; set; }
public string Title { get; set; }
public Nullable<long> StatusID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<DeviceCommand> DeviceCommands { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<DeviceIO> DeviceIOs { get; set; }
public virtual DeviceStatu DeviceStatu { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Endpoint> Endpoints { get; set; }
}
}
| mit | C# |
443d99977ec5f5c2de3e207331b9afa7b3dbe94b | Add configuration extensions for HttpRequestClientHostIPEnricher | serilog-web/classic | src/SerilogWeb.Classic/SerilogWebClassicLoggerConfigurationExtensions.cs | src/SerilogWeb.Classic/SerilogWebClassicLoggerConfigurationExtensions.cs | using Serilog.Configuration;
using SerilogWeb.Classic.Enrichers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serilog
{
/// <summary>
/// Extends <see cref="LoggerConfiguration"/> to add enrichers for SerilogWeb.Classic's logging module
/// </summary>
public static class SerilogWebClassicLoggerConfigurationExtensions
{
/// <summary>
/// Enrich log events with the named Claim Value.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithClaimValue(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
string claimProperty)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With(new ClaimValueEnricher(claimProperty));
}
/// <summary>
/// Enrich log events with the named Claim Value.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
/// <param name="logEventProperty">The property name added to enriched log events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithClaimValue(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
string claimProperty,
string logEventProperty)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With(new ClaimValueEnricher(claimProperty, logEventProperty));
}
/// <summary>
/// Enrich log events with the Client IP Address.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <param name="checkForHttpProxies">if set to <c>true</c> this Enricher also checks for HTTP proxies and their X-FORWARDED-FOR header.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithHttpRequestClientHostIP(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
bool checkForHttpProxies = true)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With(new HttpRequestClientHostIPEnricher(checkForHttpProxies));
}
}
}
| using Serilog.Configuration;
using SerilogWeb.Classic.Enrichers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serilog
{
/// <summary>
/// Extends <see cref="LoggerConfiguration"/> to add enrichers for SerilogWeb.Classic's logging module
/// </summary>
public static class SerilogWebClassicLoggerConfigurationExtensions
{
/// <summary>
/// Enrich log events with the named Claim Value.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithClaimValue(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
string claimProperty)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With(new ClaimValueEnricher(claimProperty));
}
/// <summary>
/// Enrich log events with the named Claim Value.
/// </summary>
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
/// <param name="logEventProperty">The property name added to enriched log events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration WithClaimValue(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
string claimProperty,
string logEventProperty)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With(new ClaimValueEnricher(claimProperty, logEventProperty));
}
}
}
| apache-2.0 | C# |
e5c0f851994725db549eb9cf44c85f8607e561d2 | Reorder SiteFactory register for ISiteplugin | lunet-io/lunet,lunet-io/lunet | src/Lunet.Core/SiteFactory.cs | src/Lunet.Core/SiteFactory.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.IO;
using System.Reflection;
using Autofac;
using Lunet.Core;
using Microsoft.Extensions.Logging;
namespace Lunet
{
public class SiteFactory
{
private readonly ContainerBuilder _containerBuilder;
public SiteFactory()
{
_containerBuilder = new ContainerBuilder();
// Pre-register some type
_containerBuilder.RegisterInstance(this);
_containerBuilder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
_containerBuilder.RegisterType<SiteObject>().SingleInstance();
}
public ContainerBuilder ContainerBuilder => _containerBuilder;
public SiteFactory Register<TPlugin>() where TPlugin : ISitePlugin
{
Register(typeof(TPlugin));
return this;
}
public SiteFactory Register(Type pluginType)
{
if (pluginType == null) throw new ArgumentNullException(nameof(pluginType));
if (!typeof(ISitePlugin).GetTypeInfo().IsAssignableFrom(pluginType))
{
throw new ArgumentException("Expecting a plugin type inheriting from ISitePlugin", nameof(pluginType));
}
_containerBuilder.RegisterType(pluginType).As<ISitePlugin>().AsSelf().SingleInstance();
return this;
}
public SiteObject Build()
{
var container = _containerBuilder.Build();
return container.Resolve<SiteObject>();
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.IO;
using System.Reflection;
using Autofac;
using Lunet.Core;
using Microsoft.Extensions.Logging;
namespace Lunet
{
public class SiteFactory
{
private readonly ContainerBuilder _containerBuilder;
public SiteFactory()
{
_containerBuilder = new ContainerBuilder();
// Pre-register some type
_containerBuilder.RegisterInstance(this);
_containerBuilder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
_containerBuilder.RegisterType<SiteObject>().SingleInstance();
}
public ContainerBuilder ContainerBuilder => _containerBuilder;
public SiteFactory Register<TPlugin>() where TPlugin : ISitePlugin
{
Register(typeof(TPlugin));
return this;
}
public SiteFactory Register(Type pluginType)
{
if (pluginType == null) throw new ArgumentNullException(nameof(pluginType));
if (!typeof(ISitePlugin).GetTypeInfo().IsAssignableFrom(pluginType))
{
throw new ArgumentException("Expecting a plugin type inheriting from ISitePlugin", nameof(pluginType));
}
_containerBuilder.RegisterType(pluginType).SingleInstance().AsSelf().As<ISitePlugin>();
return this;
}
public SiteObject Build()
{
var container = _containerBuilder.Build();
return container.Resolve<SiteObject>();
}
}
} | bsd-2-clause | C# |
e11aecae612ea263ed39666f27b32122aeb67552 | Update DataGridViewExtenders.cs | CanadianBeaver/DataViewExtenders | Source/DataGridViewExtenders.cs | Source/DataGridViewExtenders.cs | using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace CBComponents
{
using CBComponents.DataDescriptors;
public static partial class DataGridViewExtenders
{
/// <summary>
/// Columns generator that works on column data descriptions (Column Data Descriptor)
/// </summary>
/// <param name="viewGrid">this DataGridView</param>
/// <param name="DataSource">Data Source to support data-binding</param>
/// <param name="Columns">Column data descriptors</param>
public static void AddColumns(this DataGridView viewGrid, object DataSource, params ColumnDataDescriptor[] Columns)
{
}
/// <summary>
/// Adding a drawing of the changes tracking for changed or inserted rows
/// </summary>
/// <param name="viewGrid">this DataGridView</param>
/// <param name="cColor">Color for changed rows or null for using the default yellow color</param>
/// <param name="iColor">Color for inserted rows or null for using the default red color</param>
public static void AddCellPainting(this DataGridView viewGrid, Color? cColor = null, Color? iColor = null, bool IsGradient = true)
{
if (cColor == null) cColor = Color.FromArgb(0x99, 0xFF, 0xCC, 0x33);
if (iColor == null) iColor = Color.FromArgb(0x99, 0xFF, 0x33, 0x33);
viewGrid.CellPainting += delegate (object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 && e.RowIndex >= 0)
{
var dbItem = viewGrid.Rows[e.RowIndex].DataBoundItem as DataRowView;
if (dbItem != null)
{
var rowState = dbItem.Row.RowState;
if (rowState == DataRowState.Added || rowState == DataRowState.Modified)
{
Color _color = rowState == DataRowState.Modified ? cColor.Value : iColor.Value;
Brush _brush;
if (IsGradient) _brush = new LinearGradientBrush(e.CellBounds, Color.Transparent, _color, LinearGradientMode.Horizontal);
else _brush = new SolidBrush(_color);
e.Paint(e.ClipBounds, DataGridViewPaintParts.Background);
e.Graphics.FillRectangle(_brush, e.CellBounds);
e.Paint(e.ClipBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Background);
e.Handled = true;
}
}
}
};
}
}
}
| using System;
using System.Data;
using System.Windows.Forms;
namespace CBComponents
{
public static partial class DataGridViewExtenders
{
public static void AddColumns(this DataGridView viewGrid, object DataSource)
{
}
}
}
| mit | C# |
90391ea58c85e5a4a5667ff272e33c1c70a5ae94 | Change of method signature. | antmicro/AntShell | AntShellDemo/AntCalc.cs | AntShellDemo/AntCalc.cs | /*
Copyright (c) 2013 Ant Micro <www.antmicro.com>
Authors:
* Mateusz Holenko (mholenko@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using AntShell;
using System.IO;
using AntShell.Terminal;
namespace AntShellDemo
{
public class AntCalc
{
private Shell shell;
public AntCalc(Stream stream)
{
var sett = new ShellSettings {
NormalPrompt = new Prompt("ant-calc ", ConsoleColor.DarkBlue),
Banner = "Welcome to AntCalc - AntShell Demo!"
};
shell = new Shell(new DetachableIO(new StreamIOSource(stream)), null, sett);
shell.RegisterCommand(new AddCommand());
shell.RegisterCommand(new AskCommand());
shell.RegisterCommand(new PrintCommand());
}
public void Start()
{
shell.Start();
}
}
}
| /*
Copyright (c) 2013 Ant Micro <www.antmicro.com>
Authors:
* Mateusz Holenko (mholenko@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using AntShell;
using System.IO;
namespace AntShellDemo
{
public class AntCalc
{
private Shell shell;
public AntCalc(Stream stream)
{
var sett = new ShellSettings {
NormalPrompt = new Prompt("ant-calc ", ConsoleColor.DarkBlue),
Banner = "Welcome to AntCalc - AntShell Demo!"
};
shell = new Shell(stream, sett);
shell.RegisterCommand(new AddCommand());
shell.RegisterCommand(new AskCommand());
shell.RegisterCommand(new PrintCommand());
}
public void Start()
{
shell.Start();
}
}
}
| apache-2.0 | C# |
3e81333c455a9792fe104ee00eea134ee593a9b9 | Make EntityLumpKeyLookup thread-safe | SteamDatabase/ValveResourceFormat | ValveResourceFormat/Utils/EntityLumpKeyLookup.cs | ValveResourceFormat/Utils/EntityLumpKeyLookup.cs | using System.Collections.Concurrent;
using ValveResourceFormat.ThirdParty;
namespace ValveResourceFormat.Utils
{
public static class EntityLumpKeyLookup
{
public const uint MURMUR2SEED = 0x31415926; // It's pi!
private static readonly ConcurrentDictionary<string, uint> Lookup = new();
public static uint Get(string key)
{
return Lookup.GetOrAdd(key, s => MurmurHash2.Hash(s, MURMUR2SEED));
}
}
}
| using System.Collections.Generic;
using ValveResourceFormat.ThirdParty;
namespace ValveResourceFormat.Utils
{
public static class EntityLumpKeyLookup
{
public const uint MURMUR2SEED = 0x31415926; // It's pi!
private static Dictionary<string, uint> Lookup = new Dictionary<string, uint>();
public static uint Get(string key)
{
if (Lookup.ContainsKey(key))
{
return Lookup[key];
}
var hash = MurmurHash2.Hash(key, MURMUR2SEED);
Lookup[key] = hash;
return hash;
}
}
}
| mit | C# |
1885d9fe62bed70028303e129066abe058f88e3e | Fix IRC Manager disconnect command | samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays | TwitchPlaysAssembly/Src/Commands/IRCConnectionManagerCommands.cs | TwitchPlaysAssembly/Src/Commands/IRCConnectionManagerCommands.cs | using System;
using System.Collections;
/// <summary>Commands for the IRC Connection Holdable.</summary>
public static class IRCConnectionManagerCommands
{
[Command(@"disconnect")]
public static IEnumerator Disconnect(TwitchHoldable holdable, string user, bool isWhisper) =>
holdable.RespondToCommand(user, string.Empty, isWhisper, Disconnect(holdable.Holdable.GetComponent<IRCConnectionManagerHoldable>()));
private static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable)
{
bool allowed = false;
yield return null;
yield return new object[]
{
"streamer",
new Action(() =>
{
allowed = true;
holdable.ConnectButton.OnInteract();
holdable.ConnectButton.OnInteractEnded();
}),
new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform))
};
if (!allowed)
yield return "sendtochaterror only the streamer may use the IRC disconnect button.";
}
}
| using System;
using System.Collections;
/// <summary>Commands for the IRC Connection Holdable.</summary>
public static class IRCConnectionManagerCommands
{
[Command(@"disconnect")]
public static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable)
{
bool allowed = false;
yield return null;
yield return new object[]
{
"streamer",
new Action(() =>
{
allowed = true;
holdable.ConnectButton.OnInteract();
holdable.ConnectButton.OnInteractEnded();
}),
new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform))
};
if (!allowed)
yield return "sendtochaterror only the streamer may use the IRC disconnect button.";
}
}
| mit | C# |
c742390a3c5630303738bc6b157a99036109931b | Remove redundant AddOptions which is now a default hosting service | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Routing/DependencyInjection/RoutingServiceCollectionExtensions.cs | src/Microsoft.AspNet.Routing/DependencyInjection/RoutingServiceCollectionExtensions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Encodings.Web;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="IServiceCollection"/>.
/// </summary>
public static class RoutingServiceCollectionExtensions
{
public static IServiceCollection AddRouting(this IServiceCollection services)
{
return AddRouting(services, configureOptions: null);
}
public static IServiceCollection AddRouting(
this IServiceCollection services,
Action<RouteOptions> configureOptions)
{
services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>();
services.TryAddSingleton(UrlEncoder.Default);
services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider());
services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s =>
{
var provider = s.GetRequiredService<ObjectPoolProvider>();
var encoder = s.GetRequiredService<UrlEncoder>();
return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder));
});
if (configureOptions != null)
{
services.Configure(configureOptions);
}
return services;
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Encodings.Web;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="IServiceCollection"/>.
/// </summary>
public static class RoutingServiceCollectionExtensions
{
public static IServiceCollection AddRouting(this IServiceCollection services)
{
return AddRouting(services, configureOptions: null);
}
public static IServiceCollection AddRouting(
this IServiceCollection services,
Action<RouteOptions> configureOptions)
{
services.AddOptions();
services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>();
services.TryAddSingleton(UrlEncoder.Default);
services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider());
services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s =>
{
var provider = s.GetRequiredService<ObjectPoolProvider>();
var encoder = s.GetRequiredService<UrlEncoder>();
return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder));
});
if (configureOptions != null)
{
services.Configure(configureOptions);
}
return services;
}
}
} | apache-2.0 | C# |
4f90124b5b8d9c647163142b39870938fec11552 | Increment version | felipegtx/RestSharp,benfo/RestSharp,amccarter/RestSharp,dgreenbean/RestSharp,wparad/RestSharp,RestSharp-resurrected/RestSharp,haithemaraissia/RestSharp,periface/RestSharp,KraigM/RestSharp,lydonchandra/RestSharp,wparad/RestSharp,chengxiaole/RestSharp,SaltyDH/RestSharp,kouweizhong/RestSharp,jiangzm/RestSharp,cnascimento/RestSharp,fmmendo/RestSharp,uQr/RestSharp,mwereda/RestSharp,rucila/RestSharp,eamonwoortman/RestSharp.Unity,rivy/RestSharp,huoxudong125/RestSharp,restsharp/RestSharp,mattleibow/RestSharp,dyh333/RestSharp,PKRoma/RestSharp,mattwalden/RestSharp,dmgandini/RestSharp,who/RestSharp | RestSharp/SharedAssemblyInfo.cs | RestSharp/SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// 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: AssemblyDescription("Simple REST and HTTP API Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("John Sheehan, RestSharp Community")]
[assembly: AssemblyProduct("RestSharp")]
[assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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(SharedAssembylInfo.Version + ".0")]
[assembly: AssemblyInformationalVersion(SharedAssembylInfo.Version)]
[assembly: AssemblyFileVersion(SharedAssembylInfo.Version + ".0")]
class SharedAssembylInfo
{
public const string Version = "104.3.0";
}
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// 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: AssemblyDescription("Simple REST and HTTP API Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("John Sheehan, RestSharp Community")]
[assembly: AssemblyProduct("RestSharp")]
[assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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(SharedAssembylInfo.Version + ".0")]
[assembly: AssemblyInformationalVersion(SharedAssembylInfo.Version)]
[assembly: AssemblyFileVersion(SharedAssembylInfo.Version + ".0")]
class SharedAssembylInfo
{
public const string Version = "104.2.0";
}
| apache-2.0 | C# |
535dfd585eb6a6a9b14a0b81740d6959fbe12a02 | Fix trial_end parameter on create customer REST method. | ChadBurggraf/stripe-dotnet,nberardi/stripe-dotnet | src/StripeClient.Customers.cs | src/StripeClient.Customers.cs | using System;
using System.Linq;
using RestSharp;
using RestSharp.Validation;
using Stripe.Models;
namespace Stripe
{
public partial class StripeClient
{
public StripeCustomer CreateCustomer(ICreditCard card = null, string coupon = null, string email = null, string description = null, string plan = null, DateTimeOffset? trialEnd = null)
{
if (card != null) card.Validate();
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "customers";
if (card != null) card.AddParametersToRequest(request);
if (coupon.HasValue()) request.AddParameter("coupon", coupon);
if (email.HasValue()) request.AddParameter("email", email);
if (description.HasValue()) request.AddParameter("description", description);
if (plan.HasValue()) request.AddParameter("plan", plan);
if (trialEnd.HasValue) request.AddParameter("trial_end", trialEnd.Value.ToUnixEpoch());
return Execute<StripeCustomer>(request);
}
public StripeCustomer RetrieveCustomer(string customerId)
{
Require.Argument("customerId", customerId);
var request = new RestRequest();
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
return Execute<StripeCustomer>(request);
}
public StripeCustomer UpdateCustomer(string customerId, ICreditCard card = null, string coupon = null, string email = null, string description = null)
{
if (card != null) card.Validate();
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
if (card != null) card.AddParametersToRequest(request);
if (coupon.HasValue()) request.AddParameter("coupon", coupon);
if (email.HasValue()) request.AddParameter("email", email);
if (description.HasValue()) request.AddParameter("description", description);
return Execute<StripeCustomer>(request);
}
public StripeCustomer DeleteCustomer(string customerId)
{
Require.Argument("customerId", customerId);
var request = new RestRequest();
request.Method = Method.DELETE;
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
return Execute<StripeCustomer>(request);
}
public StripeList<StripeCustomer> ListCustomers(int? count = null, int? offset = null)
{
var request = new RestRequest();
request.Resource = "customers";
if (count.HasValue) request.AddParameter("count", count.Value);
if (offset.HasValue) request.AddParameter("offset", offset.Value);
return Execute<StripeList<StripeCustomer>>(request);
}
}
} | using System;
using System.Linq;
using RestSharp;
using RestSharp.Validation;
using Stripe.Models;
namespace Stripe
{
public partial class StripeClient
{
public StripeCustomer CreateCustomer(ICreditCard card = null, string coupon = null, string email = null, string description = null, string plan = null, DateTimeOffset? trialEnd = null)
{
if (card != null) card.Validate();
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "customers";
if (card != null) card.AddParametersToRequest(request);
if (coupon.HasValue()) request.AddParameter("coupon", coupon);
if (email.HasValue()) request.AddParameter("email", email);
if (description.HasValue()) request.AddParameter("description", description);
if (plan.HasValue()) request.AddParameter("plan", plan);
if (trialEnd.HasValue) request.AddParameter("trialEnd", trialEnd.Value.ToUnixEpoch());
return Execute<StripeCustomer>(request);
}
public StripeCustomer RetrieveCustomer(string customerId)
{
Require.Argument("customerId", customerId);
var request = new RestRequest();
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
return Execute<StripeCustomer>(request);
}
public StripeCustomer UpdateCustomer(string customerId, ICreditCard card = null, string coupon = null, string email = null, string description = null)
{
if (card != null) card.Validate();
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
if (card != null) card.AddParametersToRequest(request);
if (coupon.HasValue()) request.AddParameter("coupon", coupon);
if (email.HasValue()) request.AddParameter("email", email);
if (description.HasValue()) request.AddParameter("description", description);
return Execute<StripeCustomer>(request);
}
public StripeCustomer DeleteCustomer(string customerId)
{
Require.Argument("customerId", customerId);
var request = new RestRequest();
request.Method = Method.DELETE;
request.Resource = "customers/{customerId}";
request.AddUrlSegment("customerId", customerId);
return Execute<StripeCustomer>(request);
}
public StripeList<StripeCustomer> ListCustomers(int? count = null, int? offset = null)
{
var request = new RestRequest();
request.Resource = "customers";
if (count.HasValue) request.AddParameter("count", count.Value);
if (offset.HasValue) request.AddParameter("offset", offset.Value);
return Execute<StripeList<StripeCustomer>>(request);
}
}
} | mit | C# |
1735ca4c4db0c29294eceb6424d56da6eafc48af | Update WebApiOptions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Web/WebApiOptions.cs | TIKSN.Core/Web/WebApiOptions.cs | using System;
namespace TIKSN.Web
{
public class WebApiOptions
{
public Guid ApiKey { get; set; }
public Uri BaseAddress { get; set; }
}
public class WebApiOptions<T> : WebApiOptions
{
}
}
| using System;
namespace TIKSN.Web
{
public class WebApiOptions
{
public Guid ApiKey { get; set; }
public Uri BaseAddress { get; set; }
}
public class WebApiOptions<T> : WebApiOptions
{
}
} | mit | C# |
f0e9ed463627284e1cae8cf52e180a22cea7c958 | Fix regression in TrianglesPiece. | Damnae/osu,NeoAdonis/osu,RedNesto/osu,ppy/osu,Drezi126/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,naoey/osu,ppy/osu,UselessToucan/osu,naoey/osu,EVAST9919/osu,nyaamara/osu,ppy/osu,peppy/osu,ZLima12/osu,peppy/osu,naoey/osu,EVAST9919/osu,DrabWeb/osu,Nabile-Rahmani/osu,DrabWeb/osu,theguii/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,2yangk23/osu,osu-RP/osu-RP,smoogipoo/osu,NotKyon/lolisu,DrabWeb/osu,tacchinotacchi/osu,smoogipooo/osu,UselessToucan/osu,Frontear/osuKyzer,ZLima12/osu | osu.Game.Modes.Osu/Objects/Drawables/Pieces/TrianglesPiece.cs | osu.Game.Modes.Osu/Objects/Drawables/Pieces/TrianglesPiece.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.Graphics.Backgrounds;
namespace osu.Game.Modes.Osu.Objects.Drawables.Pieces
{
public class TrianglesPiece : Triangles
{
protected override bool ExpireOffScreenTriangles => false;
protected override bool CreateNewTriangles => false;
protected override float SpawnRatio => 0.5f;
public TrianglesPiece()
{
TriangleScale = 1.2f;
HideAlphaDiscrepancies = false;
}
protected override void Update()
{
if (IsPresent)
base.Update();
}
}
} | // 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.Graphics.Backgrounds;
namespace osu.Game.Modes.Osu.Objects.Drawables.Pieces
{
public class TrianglesPiece : Triangles
{
protected override bool ExpireOffScreenTriangles => false;
protected override bool CreateNewTriangles => false;
protected override float SpawnRatio => 0.5f;
public TrianglesPiece()
{
TriangleScale = 1.2f;
}
protected override void Update()
{
if (IsPresent)
base.Update();
}
}
} | mit | C# |
408e8d57109ed44498601f02c829d6b4faa8c05d | Fix null reference causing crash in `KiaiFlashingDrawable` | NeoAdonis/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game.Rulesets.Osu/Skinning/Legacy/KiaiFlashingDrawable.cs | osu.Game.Rulesets.Osu/Skinning/Legacy/KiaiFlashingDrawable.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
#nullable enable
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
internal class KiaiFlashingDrawable : BeatSyncedContainer
{
private readonly Drawable flashingDrawable;
private const float flash_opacity = 0.3f;
public KiaiFlashingDrawable(Func<Drawable?> creationFunc)
{
AutoSizeAxes = Axes.Both;
Children = new[]
{
(creationFunc.Invoke() ?? Empty()).With(d =>
{
d.Anchor = Anchor.Centre;
d.Origin = Anchor.Centre;
}),
flashingDrawable = (creationFunc.Invoke() ?? Empty()).With(d =>
{
d.Anchor = Anchor.Centre;
d.Origin = Anchor.Centre;
d.Alpha = 0;
d.Blending = BlendingParameters.Additive;
})
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
flashingDrawable
.FadeTo(flash_opacity)
.Then()
.FadeOut(timingPoint.BeatLength * 0.75f);
}
}
}
| // 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.Audio.Track;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
internal class KiaiFlashingDrawable : BeatSyncedContainer
{
private readonly Drawable flashingDrawable;
private const float flash_opacity = 0.3f;
public KiaiFlashingDrawable(Func<Drawable> creationFunc)
{
AutoSizeAxes = Axes.Both;
Children = new[]
{
creationFunc.Invoke().With(d =>
{
d.Anchor = Anchor.Centre;
d.Origin = Anchor.Centre;
}),
flashingDrawable = creationFunc.Invoke().With(d =>
{
d.Anchor = Anchor.Centre;
d.Origin = Anchor.Centre;
d.Alpha = 0;
d.Blending = BlendingParameters.Additive;
})
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
flashingDrawable
.FadeTo(flash_opacity)
.Then()
.FadeOut(timingPoint.BeatLength * 0.75f);
}
}
}
| mit | C# |
955836916b340c3400efac07e4e385fbb6b4b744 | Fix timeline tick display test making two instances of the component | peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu | osu.Game.Tests/Visual/Editing/TestSceneTimelineTickDisplay.cs | osu.Game.Tests/Visual/Editing/TestSceneTimelineTickDisplay.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimelineTickDisplay : TimelineTestScene
{
public override Drawable CreateTestComponent() => Empty(); // tick display is implicitly inside the timeline.
[BackgroundDependencyLoader]
private void load()
{
BeatDivisor.Value = 4;
Add(new BeatDivisorControl(BeatDivisor)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding(30),
Size = new Vector2(90)
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Edit.Compose.Components.Timeline;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimelineTickDisplay : TimelineTestScene
{
public override Drawable CreateTestComponent() => new TimelineTickDisplay();
[BackgroundDependencyLoader]
private void load()
{
BeatDivisor.Value = 4;
Add(new BeatDivisorControl(BeatDivisor)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding(30),
Size = new Vector2(90)
});
}
}
}
| mit | C# |
e3ab12f8ddd383d263f754a51c40716e3c6e6457 | Simplify the editor to work for any object | madsbangh/EasyButtons | Assets/EasyButtons/Editor/ButtonEditor.cs | Assets/EasyButtons/Editor/ButtonEditor.cs | using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Custom inspector for Object including derived classes.
/// </summary>
[CustomEditor(typeof(Object), true)]
public class ObjectEditor : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
{
method.Invoke(target, null);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
}
| using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Base class for making EasyButtons work
/// </summary>
public abstract class ButtonEditorBase : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
{
method.Invoke(target, null);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
/// <summary>
/// Custom inspector for MonoBehaviour including derived classes.
/// </summary>
[CustomEditor(typeof(MonoBehaviour), true)]
public class MonoBehaviourEditor : ButtonEditorBase { }
/// <summary>
/// Custom inspector for ScriptableObject including derived classes.
/// </summary>
[CustomEditor(typeof(ScriptableObject), true)]
public class ScriptableObjectEditor : ButtonEditorBase { }
}
| mit | C# |
5e97633171a022e608ba86d9fd996dbd04df9efa | make load model without name | tobyclh/UnityCNTK,tobyclh/UnityCNTK | Assets/UnityCNTK/Scripts/Models/_Model.cs | Assets/UnityCNTK/Scripts/Models/_Model.cs | using System;
using System.Collections.Generic;
using UnityEngine;
using CNTK;
using UnityEngine.Events;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
/// <summary>
/// the non-generic base class for all model
/// only meant to be used for model management and GUI scripting, not in-game
/// </summary>
public class _Model : MonoBehaviour{
public UnityEvent OnModelLoaded;
public string relativeModelPath;
public Function function;
private bool _isReady = false;
public bool isReady { get; protected set; }
/// <summary>
/// Load the model automatically on start
/// </summary>
public bool LoadOnStart = true;
protected Thread thread;
public virtual void LoadModel()
{
Assert.IsNotNull(relativeModelPath);
var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath);
Thread loadThread = new Thread(() =>
{
Debug.Log("Started thread");
try
{
function = Function.Load(absolutePath, CNTKManager.device);
}
catch (Exception e)
{
Debug.LogError(e);
}
if (OnModelLoaded != null)
OnModelLoaded.Invoke();
isReady = true;
Debug.Log("Model Loaded");
});
loadThread.Start();
}
public void UnloadModel()
{
if (function != null)
{
function.Dispose();
}
}
}
}
| using System;
using System.Collections.Generic;
using UnityEngine;
using CNTK;
using UnityEngine.Events;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
/// <summary>
/// the non-generic base class for all model
/// only meant to be used for model management and GUI scripting, not in-game
/// </summary>
public class _Model : MonoBehaviour{
public UnityEvent OnModelLoaded;
public string relativeModelPath;
public Function function;
private bool _isReady = false;
public bool isReady { get; protected set; }
/// <summary>
/// Load the model automatically on start
/// </summary>
public bool LoadOnStart = true;
protected Thread thread;
public virtual void LoadModel()
{
Assert.IsNotNull(relativeModelPath);
var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath);
Thread loadThread = new Thread(() =>
{
Debug.Log("Started thread");
try
{
function = Function.Load(absolutePath, CNTKManager.device);
}
catch (Exception e)
{
Debug.LogError(e);
}
if (OnModelLoaded != null)
OnModelLoaded.Invoke();
isReady = true;
Debug.Log("Model Loaded" + name);
});
loadThread.Start();
}
public void UnloadModel()
{
if (function != null)
{
function.Dispose();
}
}
}
}
| mit | C# |
26bbedb5f529584cacb94fb8f5825b34b60531c1 | update AuditHelper | saturn72/saturn72 | src/Core/Saturn72.Core.Impl/AuditHelper.cs | src/Core/Saturn72.Core.Impl/AuditHelper.cs | using System;
using Saturn72.Core.Audit;
using Saturn72.Extensions;
namespace Saturn72.Core.Services.Impl
{
public class AuditHelper
{
private readonly IWorkContext _workContext;
public AuditHelper(IWorkContext workContext)
{
_workContext = workContext;
}
public virtual void PrepareForCreateAudity(ICreatedAudit audit)
{
if (audit.IsNull())
return;
if (audit.CreatedOnUtc != default(DateTime) || audit.CreatedByUserId != 0)
throw new InvalidOperationException("Create audit already initialized.");
audit.CreatedOnUtc = DateTime.UtcNow;
audit.CreatedByUserId = _workContext.CurrentUserId;
}
public virtual void PrepareForUpdateAudity(IUpdatedAudit audit)
{
if (audit.IsNull())
return;
if (audit.CreatedOnUtc == default(DateTime))
PrepareForCreateAudity(audit);
audit.UpdatedOnUtc = DateTime.UtcNow;
audit.UpdatedByUserId = _workContext.CurrentUserId;
}
public virtual void PrepareForDeleteAudity(IDeletedAudit audit)
{
if (audit.IsNull())
return;
if (audit.DeletedOnUtc.NotNull() || audit.DeletedByUserId != 0 || audit.Deleted)
throw new InvalidOperationException("DeletedAudit already deleted.");
audit.DeletedOnUtc = DateTime.UtcNow;
audit.DeletedByUserId = _workContext.CurrentUserId;
audit.Deleted = true;
}
}
} | using System;
using Saturn72.Core.Audit;
using Saturn72.Extensions;
namespace Saturn72.Core.Services.Impl
{
public class AuditHelper
{
private readonly IWorkContext _workContext;
public AuditHelper(IWorkContext workContext)
{
_workContext = workContext;
}
public void PrepareForCreateAudity(ICreatedAudit audit)
{
if (audit.IsNull())
return;
if (audit.CreatedOnUtc != default(DateTime) || audit.CreatedByUserId != 0)
throw new InvalidOperationException("Create audit already initialized.");
audit.CreatedOnUtc = DateTime.UtcNow;
audit.CreatedByUserId = _workContext.CurrentUserId;
}
public void PrepareForUpdateAudity(IUpdatedAudit audit)
{
if (audit.IsNull())
return;
if (audit.CreatedOnUtc == default(DateTime))
PrepareForCreateAudity(audit);
audit.UpdatedOnUtc = DateTime.UtcNow;
audit.UpdatedByUserId = _workContext.CurrentUserId;
}
public void PrepareForDeleteAudity(IDeletedAudit audit)
{
if (audit.IsNull())
return;
if (audit.DeletedOnUtc.NotNull() || audit.DeletedByUserId != 0 || audit.Deleted)
throw new InvalidOperationException("DeletedAudit already deleted.");
audit.DeletedOnUtc = DateTime.UtcNow;
audit.DeletedByUserId = _workContext.CurrentUserId;
audit.Deleted = true;
}
}
} | mit | C# |
7b6b53672aaf42b57965997f9af38f73560480f7 | Update assembly version to 1.0 | mdavid/SuperSocket,mdavid/SuperSocket,mdavid/SuperSocket | SocketServiceCore/GlobalAssemblyInfo.cs | SocketServiceCore/GlobalAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")] | apache-2.0 | C# |
f4fb2c157f4ba657d3c932879ade4351821a1d7a | Remove mouse move override | Esri/coordinate-tool-addin-dotnet | source/CoordinateTool/ProAppCoordToolModule/CoordinateMapTool.cs | source/CoordinateTool/ProAppCoordToolModule/CoordinateMapTool.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using System.Windows.Documents;
namespace ProAppCoordToolModule
{
internal class CoordinateMapTool : MapTool
{
protected override Task OnToolActivateAsync(bool active)
{
return base.OnToolActivateAsync(active);
}
protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
{
var mp = QueuedTask.Run(() =>
{
MapPoint temp = null;
if (MapView.Active != null)
{
temp = MapView.Active.ClientToMap(e.ClientPoint);
}
return temp;
}).Result;
if (mp != null)
{
var vm = FrameworkApplication.DockPaneManager.Find("ProAppCoordToolModule_CoordinateToolDockpane") as CoordinateToolDockpaneViewModel;
if (vm != null)
{
vm.InputCoordinate = string.Format("{0:0.0####} {1:0.0####}", mp.Y, mp.X);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using System.Windows.Documents;
namespace ProAppCoordToolModule
{
internal class CoordinateMapTool : MapTool
{
protected override Task OnToolActivateAsync(bool active)
{
return base.OnToolActivateAsync(active);
}
protected override void OnToolMouseMove(MapViewMouseEventArgs e)
{
base.OnToolMouseMove(e);
var mp = QueuedTask.Run(() =>
{
MapPoint temp = null;
if (MapView.Active != null)
{
temp = MapView.Active.ClientToMap(e.ClientPoint);
}
return temp;
}).Result;
// get adorner layer
//var alayer = AdornerLayer.GetAdornerLayer(MapView.Active.);
}
protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
{
var mp = QueuedTask.Run(() =>
{
MapPoint temp = null;
if (MapView.Active != null)
{
temp = MapView.Active.ClientToMap(e.ClientPoint);
}
return temp;
}).Result;
if (mp != null)
{
var vm = FrameworkApplication.DockPaneManager.Find("ProAppCoordToolModule_CoordinateToolDockpane") as CoordinateToolDockpaneViewModel;
if (vm != null)
{
vm.InputCoordinate = string.Format("{0:0.0####} {1:0.0####}", mp.Y, mp.X);
}
}
}
}
}
| apache-2.0 | C# |
b68f52db7494936c3709d935850b7f93eb74062d | Fix 0x02 Patch Welcome Packet | HelloKitty/Booma.Proxy | src/Booma.Packet.Patch/Payloads/Server/PatchingWelcomePayload.cs | src/Booma.Packet.Patch/Payloads/Server/PatchingWelcomePayload.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Booma.Proxy
{
/* The Welcome packet for setting up encryption keys.
typedef struct patch_welcome
{
pkt_header_t hdr;
char copyright[44]; //Copyright message, see below.
uint8_t padding[20]; //all zeroes
uint32_t server_vector;
uint32_t client_vector;
}
PACKED patch_welcome_pkt;*/
//Syl sent: LOGIN_93_TYPE https://github.com/Sylverant/login_server/blob/master/src/bblogin.c#L121
//Syl struct: https://github.com/Sylverant/patch_server/blob/1616d93cc653703e3787c246dfb7aaa8ef3044b1/src/patch_packets.c#L102
/// <summary>
/// The welcome message the patch server sends when you connect
/// initially.
/// </summary>
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCode.PATCH_WELCOME_TYPE)]
public sealed partial class PatchingWelcomePayload : PSOBBPatchPacketPayloadServer
{
/// <summary>
/// Copyright message sent down from the patch server.
/// Always the same message.
/// </summary>
[DontTerminate]
[KnownSize(44)]
[WireMember(1)]
public string PatchCopyrightMessage { get; internal set; } //I don't think this is null terminated?
//TODO: Why?
[KnownSize(20)]
[WireMember(2)]
internal byte[] Padding { get; set; } = new byte[20];
//TODO: What is this?
/// <summary>
/// Server IV (?)
/// </summary>
[WireMember(3)]
public uint ServerVector { get; internal set; }
/// <summary>
/// Client IV (?)
/// </summary>
[WireMember(4)]
public uint ClientVector { get; internal set; }
public PatchingWelcomePayload([NotNull] string patchCopyrightMessage, uint serverVector, uint clientVector)
: this()
{
if(string.IsNullOrWhiteSpace(patchCopyrightMessage)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(patchCopyrightMessage));
PatchCopyrightMessage = patchCopyrightMessage;
ServerVector = serverVector;
ClientVector = clientVector;
}
/// <summary>
/// serializer ctor.
/// </summary>
public PatchingWelcomePayload()
: base(PatchNetworkOperationCode.PATCH_WELCOME_TYPE)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Booma.Proxy
{
/* The Welcome packet for setting up encryption keys.
typedef struct patch_welcome
{
pkt_header_t hdr;
char copyright[44]; //Copyright message, see below.
uint8_t padding[20]; //all zeroes
uint32_t server_vector;
uint32_t client_vector;
}
PACKED patch_welcome_pkt;*/
//Syl sent: LOGIN_93_TYPE https://github.com/Sylverant/login_server/blob/master/src/bblogin.c#L121
//Syl struct: https://github.com/Sylverant/patch_server/blob/1616d93cc653703e3787c246dfb7aaa8ef3044b1/src/patch_packets.c#L102
/// <summary>
/// The welcome message the patch server sends when you connect
/// initially.
/// </summary>
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCode.PATCH_WELCOME_TYPE)]
public sealed partial class PatchingWelcomePayload : PSOBBPatchPacketPayloadServer
{
/// <summary>
/// Copyright message sent down from the patch server.
/// Always the same message.
/// </summary>
[KnownSize(44)]
[WireMember(1)]
public string PatchCopyrightMessage { get; internal set; } //I don't think this is null terminated?
//TODO: Why?
[KnownSize(20)]
[WireMember(2)]
internal byte[] Padding { get; set; }
//TODO: What is this?
/// <summary>
/// Server IV (?)
/// </summary>
[WireMember(3)]
public uint ServerVector { get; internal set; }
/// <summary>
/// Client IV (?)
/// </summary>
[WireMember(4)]
public uint ClientVector { get; internal set; }
public PatchingWelcomePayload([NotNull] string patchCopyrightMessage, uint serverVector, uint clientVector)
: this()
{
if(string.IsNullOrWhiteSpace(patchCopyrightMessage)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(patchCopyrightMessage));
PatchCopyrightMessage = patchCopyrightMessage;
ServerVector = serverVector;
ClientVector = clientVector;
}
/// <summary>
/// serializer ctor.
/// </summary>
public PatchingWelcomePayload()
: base(PatchNetworkOperationCode.PATCH_WELCOME_TYPE)
{
}
}
}
| agpl-3.0 | C# |
e7bad92e777e5017b76890f9e99fe4c81255feea | Make GetWarmerResponseConverter internal | adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,UdiBen/elasticsearch-net,jonyadamit/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,RossLieberman/NEST,elastic/elasticsearch-net,azubanov/elasticsearch-net,KodrAus/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,UdiBen/elasticsearch-net,jonyadamit/elasticsearch-net,azubanov/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,jonyadamit/elasticsearch-net | src/Nest/Indices/Warmers/GetWarmer/GetWarmerResponseConverter.cs | src/Nest/Indices/Warmers/GetWarmer/GetWarmerResponseConverter.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nest
{
internal class GetWarmerResponseConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override bool CanWrite => false;
public override bool CanRead => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var response = new GetWarmerResponse();
var warmersByIndex = JObject.Load(reader).Properties().ToDictionary(p => p.Name, p => p.Value);
if (!warmersByIndex.HasAny()) return response;
response.Indices = new Dictionary<string, Warmers>();
foreach (var warmerByIndex in warmersByIndex)
{
var index = warmerByIndex.Key;
var warmersObject = JObject.FromObject(warmerByIndex.Value).Properties()
.Where(p => p.Name == "warmers")
.Select(p => p.Value)
.FirstOrDefault();
var warmers = new Warmers();
if (warmersObject != null)
{
var warmersByName = JObject.FromObject(warmersObject).Properties()
.ToDictionary(p => p.Name, p => p.Value);
foreach (var warmerByName in warmersByName)
{
var name = warmerByName.Key;
var warmer = warmerByName.Value.ToObject<Warmer>();
warmers.Add(name, warmer);
}
}
response.Indices.Add(warmerByIndex.Key, warmers);
}
return response;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nest
{
public class GetWarmerResponseConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override bool CanWrite => false;
public override bool CanRead => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var response = new GetWarmerResponse();
var warmersByIndex = JObject.Load(reader).Properties().ToDictionary(p => p.Name, p => p.Value);
if (!warmersByIndex.HasAny()) return response;
response.Indices = new Dictionary<string, Warmers>();
foreach (var warmerByIndex in warmersByIndex)
{
var index = warmerByIndex.Key;
var warmersObject = JObject.FromObject(warmerByIndex.Value).Properties()
.Where(p => p.Name == "warmers")
.Select(p => p.Value)
.FirstOrDefault();
var warmers = new Warmers();
if (warmersObject != null)
{
var warmersByName = JObject.FromObject(warmersObject).Properties()
.ToDictionary(p => p.Name, p => p.Value);
foreach (var warmerByName in warmersByName)
{
var name = warmerByName.Key;
var warmer = warmerByName.Value.ToObject<Warmer>();
warmers.Add(name, warmer);
}
}
response.Indices.Add(warmerByIndex.Key, warmers);
}
return response;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
}
}
| apache-2.0 | C# |
223c7154ba47c3d342554c156bb10cff705a8a73 | Fix error message building when no specific errors defined | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Application/InvalidRequestException.cs | src/SFA.DAS.EmployerUsers.Application/InvalidRequestException.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerUsers.Application
{
public class InvalidRequestException : Exception
{
public Dictionary<string, string> ErrorMessages { get; private set; }
public InvalidRequestException(Dictionary<string, string> errorMessages)
: base(BuildErrorMessage(errorMessages))
{
this.ErrorMessages = errorMessages;
}
private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
{
if (errorMessages.Count == 0)
{
return "Request is invalid";
}
return "Request is invalid:\n"
+ errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerUsers.Application
{
public class InvalidRequestException : Exception
{
public Dictionary<string,string> ErrorMessages { get; private set; }
public InvalidRequestException(Dictionary<string,string> errorMessages)
: base(BuildErrorMessage(errorMessages))
{
this.ErrorMessages = errorMessages;
}
private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
{
return "Request is invalid:\n"
+ errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
}
}
}
| mit | C# |
189c3798e9776f77ab658856fe75f81b7cefb402 | Add missing ".dll" from DllImport | tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server | src/Tgstation.Server.Host/NativeMethods.cs | src/Tgstation.Server.Host/NativeMethods.cs | using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host
{
/// <summary>
/// Native methods used by the code
/// </summary>
static class NativeMethods
{
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid
/// </summary>
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage
/// </summary>
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/ms633493(v=VS.85).aspx
/// </summary>
public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumchildwindows
/// </summary>
[DllImport("user32.dll")]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
/// </summary>
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw
/// </summary>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
}
}
| using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host
{
/// <summary>
/// Native methods used by the code
/// </summary>
static class NativeMethods
{
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid
/// </summary>
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage
/// </summary>
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/ms633493(v=VS.85).aspx
/// </summary>
public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumchildwindows
/// </summary>
[DllImport("user32")]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
/// </summary>
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw
/// </summary>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
}
}
| agpl-3.0 | C# |
3c63e95a3d23ddd179dcfb6626dc2444350a0d63 | Integrate use of ViewModelStateHelper into BasicViewModel | wiyonoaten/XMvvmApp | XMvvmApp/Mvvm/BasicViewModel.cs | XMvvmApp/Mvvm/BasicViewModel.cs | using System.ComponentModel;
using System.Windows.Input;
using XMvvmApp.Mvvm.Helpers;
namespace XMvvmApp.Mvvm
{
public abstract class BasicViewModel : IViewModel
{
private readonly ViewModelStateHelper _viewModelStateHelper;
protected BasicViewModel()
{
this.WakeupCommand = new DelegateCommand(DoWakeup);
this.SleepCommand = new DelegateCommand(DoSleep);
_viewModelStateHelper = new ViewModelStateHelper(this);
}
#region Property Changed/Changing Events
public PropertyChangedEventHandler PropertyChangedEventHandler
{
get { return this.PropertyChanged; }
}
public PropertyChangingEventHandler PropertyChangingEventHandler
{
get { return this.PropertyChanging; }
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
#endregion
#region IViewModel Implementations
public ICommand SleepCommand { get; }
public ICommand WakeupCommand { get; }
public virtual object GetSavedState()
{
return _viewModelStateHelper.GetState();
}
public virtual void RestoreSavedState(object state)
{
_viewModelStateHelper.RestoreState(state);
}
#endregion
#region Abstracts
protected abstract void DoWakeup();
protected abstract void DoSleep();
#endregion
}
}
| using System.ComponentModel;
using System.Windows.Input;
namespace XMvvmApp.Mvvm
{
public abstract class BasicViewModel : IViewModel
{
protected BasicViewModel()
{
this.WakeupCommand = new DelegateCommand(DoWakeup);
this.SleepCommand = new DelegateCommand(DoSleep);
}
#region Property Changed/Changing Events
public PropertyChangedEventHandler PropertyChangedEventHandler
{
get { return this.PropertyChanged; }
}
public PropertyChangingEventHandler PropertyChangingEventHandler
{
get { return this.PropertyChanging; }
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
#endregion
#region IViewModel Abstracts
public abstract object GetSavedState();
public abstract void RestoreSavedState(object state);
#endregion
#region IViewModel Implementations
public ICommand SleepCommand { get; }
public ICommand WakeupCommand { get; }
#endregion
#region Abstracts
protected abstract void DoWakeup();
protected abstract void DoSleep();
#endregion
}
}
| apache-2.0 | C# |
a9780324afb4060fddc82a836119f8c3f5a0f674 | Change HTML table header generation to use the correct th HTML tag. | gilles-leblanc/Sniptaculous | SnippetsToMarkdown/SnippetsToMarkdown/Commands/WriteHeaderHtmlCommand.cs | SnippetsToMarkdown/SnippetsToMarkdown/Commands/WriteHeaderHtmlCommand.cs | using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<th>Shortcut</th>");
output.AppendLine("<th>Name</th>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
| using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<td>Shortcut</td>");
output.AppendLine("<td>Name</td>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
| mit | C# |
2b23f6a45800ce0c40a283966dabdc255d3c9db6 | 更新版本2.3.0.38 | Laforeta/KanColleCacher,Gizeta/KanColleCacher | KanColleCacher/Properties/AssemblyInfo.cs | KanColleCacher/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using d_f_32.KanColleCacher;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle(AssemblyInfo.Title)]
[assembly: AssemblyDescription(AssemblyInfo.Description)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(AssemblyInfo.Name)]
[assembly: AssemblyCopyright(AssemblyInfo.Copyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
//[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")]
[assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(AssemblyInfo.Version)]
[assembly: AssemblyFileVersion(AssemblyInfo.Version)]
namespace d_f_32.KanColleCacher
{
public static class AssemblyInfo
{
public const string Name = "KanColleCacher";
public const string Version = "2.3.0.38";
public const string Author = "d.f.32";
public const string Copyright = "©2014 - d.f.32";
#if DEBUG
public const string Title = "提督很忙!缓存工具 (DEBUG)";
#else
public const string Title = "提督很忙!缓存工具";
#endif
public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)";
}
} | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using d_f_32.KanColleCacher;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle(AssemblyInfo.Title)]
[assembly: AssemblyDescription(AssemblyInfo.Description)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(AssemblyInfo.Name)]
[assembly: AssemblyCopyright(AssemblyInfo.Copyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
//[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")]
[assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(AssemblyInfo.Version)]
[assembly: AssemblyFileVersion(AssemblyInfo.Version)]
namespace d_f_32.KanColleCacher
{
public static class AssemblyInfo
{
public const string Name = "KanColleCacher";
public const string Version = "2.2.2.34";
public const string Author = "d.f.32";
public const string Copyright = "©2014 - d.f.32";
#if DEBUG
public const string Title = "提督很忙!缓存工具 (DEBUG)";
#else
public const string Title = "提督很忙!缓存工具";
#endif
public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)";
}
} | mit | C# |
3dec37f8d4ba63dfa45b0ece4431b08e7c89a665 | Use random app name to avoid 409 conflict error | YOTOV-LIMITED/kudu,shibayan/kudu,barnyp/kudu,shibayan/kudu,EricSten-MSFT/kudu,badescuga/kudu,puneet-gupta/kudu,sitereactor/kudu,WeAreMammoth/kudu-obsolete,shibayan/kudu,juoni/kudu,EricSten-MSFT/kudu,kali786516/kudu,shanselman/kudu,shrimpy/kudu,chrisrpatterson/kudu,puneet-gupta/kudu,dev-enthusiast/kudu,YOTOV-LIMITED/kudu,kenegozi/kudu,oliver-feng/kudu,juoni/kudu,bbauya/kudu,dev-enthusiast/kudu,badescuga/kudu,chrisrpatterson/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,puneet-gupta/kudu,oliver-feng/kudu,juvchan/kudu,uQr/kudu,shrimpy/kudu,MavenRain/kudu,dev-enthusiast/kudu,MavenRain/kudu,mauricionr/kudu,MavenRain/kudu,kali786516/kudu,juoni/kudu,kenegozi/kudu,bbauya/kudu,barnyp/kudu,oliver-feng/kudu,juvchan/kudu,EricSten-MSFT/kudu,shrimpy/kudu,sitereactor/kudu,uQr/kudu,projectkudu/kudu,shanselman/kudu,shibayan/kudu,EricSten-MSFT/kudu,barnyp/kudu,uQr/kudu,MavenRain/kudu,duncansmart/kudu,barnyp/kudu,sitereactor/kudu,badescuga/kudu,WeAreMammoth/kudu-obsolete,YOTOV-LIMITED/kudu,shanselman/kudu,projectkudu/kudu,kenegozi/kudu,kali786516/kudu,sitereactor/kudu,projectkudu/kudu,badescuga/kudu,duncansmart/kudu,WeAreMammoth/kudu-obsolete,juvchan/kudu,bbauya/kudu,chrisrpatterson/kudu,puneet-gupta/kudu,duncansmart/kudu,duncansmart/kudu,juoni/kudu,juvchan/kudu,projectkudu/kudu,YOTOV-LIMITED/kudu,uQr/kudu,shibayan/kudu,kali786516/kudu,oliver-feng/kudu,kenegozi/kudu,dev-enthusiast/kudu,mauricionr/kudu,bbauya/kudu,mauricionr/kudu,sitereactor/kudu,projectkudu/kudu,mauricionr/kudu,chrisrpatterson/kudu,badescuga/kudu,shrimpy/kudu,juvchan/kudu | Kudu.FunctionalTests/GitStabilityTests.cs | Kudu.FunctionalTests/GitStabilityTests.cs | using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;
namespace Kudu.FunctionalTests
{
public class GitStabilityTests
{
[Fact]
public void NSimpleDeployments()
{
string repositoryName = "HelloKudu";
string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
using (Git.Clone(repositoryName, cloneUrl))
{
for (int i = 0; i < 5; i++)
{
string applicationName = KuduUtils.GetRandomWebsiteName(repositoryName + i);
ApplicationManager.Run(applicationName, appManager =>
{
// Act
appManager.AssertGitDeploy(repositoryName);
var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();
// Assert
Assert.Equal(1, results.Count);
Assert.Equal(DeployStatus.Success, results[0].Status);
KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
});
}
}
}
}
}
| using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;
namespace Kudu.FunctionalTests
{
public class GitStabilityTests
{
[Fact]
public void NSimpleDeployments()
{
string repositoryName = "HelloKudu";
string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
using (Git.Clone(repositoryName, cloneUrl))
{
for (int i = 0; i < 5; i++)
{
string applicationName = repositoryName + i;
ApplicationManager.Run(applicationName, appManager =>
{
// Act
appManager.AssertGitDeploy(repositoryName);
var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();
// Assert
Assert.Equal(1, results.Count);
Assert.Equal(DeployStatus.Success, results[0].Status);
KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
});
}
}
}
}
}
| apache-2.0 | C# |
d87b90f1d9ed7b9f833b83a1ba9b603b5a4a6cab | Update Main.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | LoginPasswordUtil/C-Sharp-Version/Main.cs | LoginPasswordUtil/C-Sharp-Version/Main.cs | /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This is my first draft of this (C# version), it may not pass the build.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ACLoginPasswordUtil;
using System.Diagnostics;
namespace ACLoginPasswordUtil
{
class Run
{
int decrypt(String[] originalArgs)
{
int first = Int32.Parse(originalArgs[0]);
int second = Int32.Parse(originalArgs[1]);
int result = first + second;
return result;
}
public static void Main(String[] a)
{
String sysPath = Environment.GetEnvironmentVariable("SystemRoot");
Run thisInstance = new Run();
Resources resClass = new Resources();
int pswInt = thisInstance.decrypt(a);
if (pswInt > 1 && !(pswInt > 5)) // The value check.
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append(sysPath);
sBuilder.Append("\\System32\\");
sBuilder.Append(resClass.baseCmd);
sBuilder.Append(resClass.netCmd);
String cmdText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(resClass.armv7a);
sBuilder.Append(pswInt);
String pswText = sBuilder.ToString();
sBuilder.Clear();
sBuilder.Append(cmdText);
sBuilder.Append(pswText);
Process.Start(sBuilder.ToString());
}
}
}
}
| /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This is my first draft of this (C# version), it may not pass the build.
*/
using System;
using System.Diagnostics.Process;
using System.Environment;
namespace ACLoginPasswordUtil{
class Main{
int decrypt(String[] originalArgs){
int first = Int32.Parse(originalArgs[0]);
int second = Int32.Parse(originalArgs[1]);
int result = first + second;
return result;
}
static void main(String[] a){
String sysPath = Environment.GetEnvironmentVariable("SystemRoot");
int pswInt = decrypt(a);
//Process.Start();
}
}
| apache-2.0 | C# |
a2d1c40ab0cfc0bf3acab7a66910f6f488800a29 | add atribute for DateTime | vknet/vk,vknet/vk | VkNet/Model/SubscriptionItem.cs | VkNet/Model/SubscriptionItem.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VkNet.Enums;
using VkNet.Utils;
namespace VkNet.Model
{
[Serializable]
public class SubscriptionItem
{
[JsonProperty(propertyName: "id")]
public ulong Id { get; set; }
[JsonProperty(propertyName: "item_id")]
public string ItemId { get; set; }
[JsonProperty(propertyName: "status")]
public string Status { get; set; }
[JsonProperty(propertyName: "price")]
public long Price { get; set; }
[JsonProperty(propertyName: "period")]
public int Period { get; set; }
[JsonProperty(propertyName: "create_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? CreateTime { get; set; }
[JsonProperty(propertyName: "update_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? UpdateTime { get; set; }
[JsonProperty(propertyName: "period_start_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? PeriodStartTime { get; set; }
private DateTime? _nextBillTime;
[JsonProperty(propertyName: "next_bill_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? NextBillTime
{
get
{
if (Status.Equals("active")) return _nextBillTime;
return null;
}
set
{
if (_nextBillTime == value) return;
if (Status.Equals("active"))
_nextBillTime = value;
}
}
[JsonProperty(propertyName: "trial_expire_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? TrialExpireTime { get; set; }
[JsonProperty(propertyName: "pending_cancel")]
public bool PendingCancel { get; set; }
[JsonProperty(propertyName: "cancel_reason")]
public CancelSubscriptionReason CancelReason { get; set; }
[JsonProperty(propertyName: "test_mode")]
public bool TestMode { get; set; }
}
} | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VkNet.Enums;
using VkNet.Utils;
namespace VkNet.Model
{
[Serializable]
public class SubscriptionItem
{
[JsonProperty(propertyName: "id")]
public ulong Id { get; set; }
[JsonProperty(propertyName: "item_id")]
public string ItemId { get; set; }
[JsonProperty(propertyName: "status")]
public string Status { get; set; }
[JsonProperty(propertyName: "price")]
public long Price { get; set; }
[JsonProperty(propertyName: "period")]
public int Period { get; set; }
[JsonProperty(propertyName: "create_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? CreateTime { get; set; }
[JsonProperty(propertyName: "update_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? UpdateTime { get; set; }
[JsonProperty(propertyName: "period_start_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? PeriodStartTime { get; set; }
private DateTime? _nextBillTime;
[JsonProperty(propertyName: "next_bill_time")]
[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
public DateTime? NextBillTime
{
get
{
if (Status.Equals("active")) return _nextBillTime;
return null;
}
set
{
if (_nextBillTime == value) return;
if (Status.Equals("active"))
_nextBillTime = value;
}
}
[JsonProperty(propertyName: "trial_expire_time")]
public DateTime? TrialExpireTime { get; set; }
[JsonProperty(propertyName: "pending_cancel")]
public bool PendingCancel { get; set; }
[JsonProperty(propertyName: "cancel_reason")]
public CancelSubscriptionReason CancelReason { get; set; }
[JsonProperty(propertyName: "test_mode")]
public bool TestMode { get; set; }
}
} | mit | C# |
75bf2fcb67e7f63b53aec383c89ad5e18bb0c742 | remove usings. | wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,akrisiun/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia | src/Avalonia.OpenGL/Angle/AngleEglInterface.cs | src/Avalonia.OpenGL/Angle/AngleEglInterface.cs | using System;
using System.Runtime.InteropServices;
namespace Avalonia.OpenGL.Angle
{
public class AngleEglInterface : EglInterface
{
[DllImport("avangle.dll", CharSet = CharSet.Ansi)]
static extern IntPtr EGL_GetProcAddress(string proc);
public AngleEglInterface() : base(LoadAngle())
{
}
static Func<string, IntPtr> LoadAngle()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var disp = EGL_GetProcAddress("eglGetPlatformDisplayEXT");
if (disp == IntPtr.Zero)
{
throw new OpenGlException("libegl.dll doesn't have eglGetPlatformDisplayEXT entry point");
}
return eglGetProcAddress;
}
throw new PlatformNotSupportedException();
}
}
}
| using System;
using System.Runtime.InteropServices;
using Avalonia.Platform;
using Avalonia.Platform.Interop;
namespace Avalonia.OpenGL.Angle
{
public class AngleEglInterface : EglInterface
{
[DllImport("avangle.dll", CharSet = CharSet.Ansi)]
static extern IntPtr EGL_GetProcAddress(string proc);
public AngleEglInterface() : base(LoadAngle())
{
}
static Func<string, IntPtr> LoadAngle()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var disp = EGL_GetProcAddress("eglGetPlatformDisplayEXT");
if (disp == IntPtr.Zero)
{
throw new OpenGlException("libegl.dll doesn't have eglGetPlatformDisplayEXT entry point");
}
return eglGetProcAddress;
}
throw new PlatformNotSupportedException();
}
}
}
| mit | C# |
9f0e9fd8e591bb289111a2260866bc0753f366ae | Remove comment | ahmetalpbalkan/Docker.DotNet | src/Docker.DotNet/DockerClientConfiguration.cs | src/Docker.DotNet/DockerClientConfiguration.cs | using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace Docker.DotNet
{
public class DockerClientConfiguration : IDisposable
{
public Uri EndpointBaseUri { get; internal set; }
public Credentials Credentials { get; internal set; }
public TimeSpan DefaultTimeout { get; internal set; } = TimeSpan.FromSeconds(100);
public TimeSpan NamedPipeConnectTimeout { get; set; } = TimeSpan.FromMilliseconds(100);
private static Uri LocalDockerUri()
{
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
return isWindows ? new Uri("npipe://./pipe/docker_engine") : new Uri("unix:/var/run/docker.sock");
}
public DockerClientConfiguration(Credentials credentials = null, TimeSpan defaultTimeout = default(TimeSpan))
: this(LocalDockerUri(), credentials, defaultTimeout)
{
}
public DockerClientConfiguration(Uri endpoint, Credentials credentials = null,
TimeSpan defaultTimeout = default(TimeSpan))
{
if (endpoint == null)
throw new ArgumentNullException(nameof(endpoint));
Credentials = credentials ?? new AnonymousCredentials();
EndpointBaseUri = endpoint;
if (defaultTimeout != TimeSpan.Zero)
{
if (defaultTimeout < Timeout.InfiniteTimeSpan)
// TODO: Should be a resource for localization.
// TODO: Is this a good message?
throw new ArgumentException("Timeout must be greater than Timeout.Infinite", nameof(defaultTimeout));
DefaultTimeout = defaultTimeout;
}
}
public DockerClient CreateClient()
{
return this.CreateClient(null);
}
public DockerClient CreateClient(Version requestedApiVersion)
{
return new DockerClient(this, requestedApiVersion);
}
public void Dispose()
{
Credentials.Dispose();
}
}
} | using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace Docker.DotNet
{
public class DockerClientConfiguration : IDisposable
{
public Uri EndpointBaseUri { get; internal set; }
public Credentials Credentials { get; internal set; }
public TimeSpan DefaultTimeout { get; internal set; } = TimeSpan.FromSeconds(100);
// NamedPipeClientStream handles file not found by polling until the server arrives. Use a short
// timeout so that the user doesn't get stuck waiting for a dockerd instance that is not running.
public TimeSpan NamedPipeConnectTimeout { get; set; } = TimeSpan.FromMilliseconds(100);
private static Uri LocalDockerUri()
{
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
return isWindows ? new Uri("npipe://./pipe/docker_engine") : new Uri("unix:/var/run/docker.sock");
}
public DockerClientConfiguration(Credentials credentials = null, TimeSpan defaultTimeout = default(TimeSpan))
: this(LocalDockerUri(), credentials, defaultTimeout)
{
}
public DockerClientConfiguration(Uri endpoint, Credentials credentials = null,
TimeSpan defaultTimeout = default(TimeSpan))
{
if (endpoint == null)
throw new ArgumentNullException(nameof(endpoint));
Credentials = credentials ?? new AnonymousCredentials();
EndpointBaseUri = endpoint;
if (defaultTimeout != TimeSpan.Zero)
{
if (defaultTimeout < Timeout.InfiniteTimeSpan)
// TODO: Should be a resource for localization.
// TODO: Is this a good message?
throw new ArgumentException("Timeout must be greater than Timeout.Infinite", nameof(defaultTimeout));
DefaultTimeout = defaultTimeout;
}
}
public DockerClient CreateClient()
{
return this.CreateClient(null);
}
public DockerClient CreateClient(Version requestedApiVersion)
{
return new DockerClient(this, requestedApiVersion);
}
public void Dispose()
{
Credentials.Dispose();
}
}
} | apache-2.0 | C# |
95268fb85e65375da5dd5dcddc9940e557e1c3aa | Update NewSellerListing.cs | viagogo/gogokit.net | src/GogoKit/Models/Request/NewSellerListing.cs | src/GogoKit/Models/Request/NewSellerListing.cs | using System;
using GogoKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Request
{
[DataContract]
public class NewSellerListing
{
[DataMember(Name = "number_of_tickets")]
public int? NumberOfTickets { get; set; }
[DataMember(Name = "display_number_of_tickets")]
public int? DisplayNumberOfTickets { get; set; }
[DataMember(Name = "seating")]
public Seating Seating { get; set; }
[DataMember(Name = "face_value")]
public Money FaceValue { get; set; }
[DataMember(Name = "ticket_price")]
public Money TicketPrice { get; set; }
[DataMember(Name = "ticket_proceeds")]
public Money TicketProceeds { get; set; }
[DataMember(Name = "ticket_type")]
public string TicketType { get; set; }
[DataMember(Name = "split_type")]
public string SplitType { get; set; }
[DataMember(Name = "listing_note_ids")]
public IList<int> ListingNoteIds { get; set; }
[DataMember(Name = "notes")]
public string Notes { get; set; }
[DataMember(Name = "ticket_location_address_id")]
public int? TicketLocationAddressId { get; set; }
[DataMember(Name = "guarantee_payment_method_id")]
public int? GuaranteePaymentMethodId { get; set; }
[DataMember(Name = "external_id")]
public string ExternalId { get; set; }
[DataMember(Name = "in_hand_at")]
public DateTimeOffset? InHandAt { get; set; }
[DataMember(Name = "instant_delivery")]
public bool? IsInstantDelivery { get; set; }
}
}
| using System;
using GogoKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Request
{
[DataContract]
public class NewSellerListing
{
[DataMember(Name = "number_of_tickets")]
public int? NumberOfTickets { get; set; }
[DataMember(Name = "display_number_of_tickets")]
public int? DisplayNumberOfTickets { get; set; }
[DataMember(Name = "seating")]
public Seating Seating { get; set; }
[DataMember(Name = "face_value")]
public Money FaceValue { get; set; }
[DataMember(Name = "ticket_price")]
public Money TicketPrice { get; set; }
[DataMember(Name = "ticket_proceeds")]
public Money TicketProceeds { get; set; }
[DataMember(Name = "ticket_type")]
public string TicketType { get; set; }
[DataMember(Name = "split_type")]
public string SplitType { get; set; }
[DataMember(Name = "listing_note_ids")]
public IList<int> ListingNoteIds { get; set; }
[DataMember(Name = "notes")]
public string Notes { get; set; }
[DataMember(Name = "ticket_location_address_id")]
public int? TicketLocationAddressId { get; set; }
[DataMember(Name = "guarantee_payment_method_id")]
public int? GuaranteePaymentMethodId { get; set; }
[DataMember(Name = "external_id")]
public string ExternalId { get; set; }
[DataMember(Name = "in_hand_date")]
public DateTimeOffset? InHandDate { get; set; }
[DataMember(Name = "instant_delivery")]
public bool? IsInstantDelivery { get; set; }
}
}
| mit | C# |
95d20648e416295758325dea372c9978816d6efc | Fix imgur middleware constructor | RockstarLabs/OwinOAuthProviders,nbelyh/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,yonglehou/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,Lorac/OwinOAuthProviders,Lorac/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,tparnell8/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,yonglehou/OwinOAuthProviders,qanuj/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,tparnell8/OwinOAuthProviders,RockstarLabs/OwinOAuthProviders,nbelyh/OwinOAuthProviders,nbelyh/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,yfann/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,Lorac/OwinOAuthProviders,yonglehou/OwinOAuthProviders,qanuj/OwinOAuthProviders,jmloeffler/OwinOAuthProviders,yfann/OwinOAuthProviders,qanuj/OwinOAuthProviders,qanuj/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,NewBoCo/OwinOAuthProviders,TerribleDev/OwinOAuthProviders,RockstarLabs/OwinOAuthProviders,CrustyJew/OwinOAuthProviders,tparnell8/OwinOAuthProviders,yfann/OwinOAuthProviders | Owin.Security.Providers/Imgur/ImgurAuthenticationMiddleware.cs | Owin.Security.Providers/Imgur/ImgurAuthenticationMiddleware.cs | namespace Owin.Security.Providers.Imgur
{
using Microsoft.Owin;
using Microsoft.Owin.Security.Infrastructure;
public class ImgurAuthenticationMiddleware : AuthenticationMiddleware<ImgurAuthenticationOptions>
{
public ImgurAuthenticationMiddleware(OwinMiddleware next, IAppBuilder appBuilder, ImgurAuthenticationOptions options) : base(next, options)
{
}
protected override AuthenticationHandler<ImgurAuthenticationOptions> CreateHandler()
{
return new ImgurAuthenticationHandler();
}
}
}
| namespace Owin.Security.Providers.Imgur
{
using Microsoft.Owin;
using Microsoft.Owin.Security.Infrastructure;
public class ImgurAuthenticationMiddleware : AuthenticationMiddleware<ImgurAuthenticationOptions>
{
public ImgurAuthenticationMiddleware(OwinMiddleware next, ImgurAuthenticationOptions options) : base(next, options)
{
}
protected override AuthenticationHandler<ImgurAuthenticationOptions> CreateHandler()
{
return new ImgurAuthenticationHandler();
}
}
}
| mit | C# |
a4a92d082106eaf6c78dd4ccedf441633da129f8 | Replace recursive file enumeration with a stack based approach | hal-ler/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,khellang/omnisharp-roslyn,jtbm37/omnisharp-roslyn,haled/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,khellang/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,hach-que/omnisharp-roslyn,hitesh97/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,nabychan/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,fishg/omnisharp-roslyn,sriramgd/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,sriramgd/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,sreal/omnisharp-roslyn,hach-que/omnisharp-roslyn,haled/omnisharp-roslyn,sreal/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,fishg/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,hal-ler/omnisharp-roslyn,nabychan/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,jtbm37/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,hitesh97/omnisharp-roslyn | src/OmniSharp/Utilities/DirectoryEnumerator.cs | src/OmniSharp/Utilities/DirectoryEnumerator.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
allFiles = allFiles.Concat(GetFiles(current, pattern));
foreach (var subdirectory in GetSubdirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
}
return allFiles;
}
private IEnumerable<string> GetFiles(string path, string pattern)
{
try
{
return Directory.EnumerateFiles(path, pattern, SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
private IEnumerable<string> GetSubdirectories(string path)
{
try
{
return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
{
yield break;
}
string[] files = null;
string[] directories = null;
try
{
// Get the files and directories now so we can get any exceptions up front
files = Directory.GetFiles(path, searchPattern);
directories = Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", path));
yield break;
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
yield break;
}
foreach (var file in files)
{
yield return file;
}
foreach (var file in directories.SelectMany(x => SafeEnumerateFiles(x, searchPattern)))
{
yield return file;
}
}
}
}
| mit | C# |
38feb7651cf32af4e323eb190dd40b84b8c24532 | Set text at updateTime | peppy/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,ppy/osu,naoey/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,ppy/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,UselessToucan/osu,naoey/osu,smoogipooo/osu,johnneijzen/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu | osu.Game/Graphics/DrawableDate.cs | osu.Game/Graphics/DrawableDate.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 Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class DrawableDate : OsuSpriteText, IHasTooltip
{
private readonly DateTimeOffset date;
public DrawableDate(DateTimeOffset date)
{
AutoSizeAxes = Axes.Both;
Font = "Exo2.0-RegularItalic";
this.date = date.ToLocalTime();
}
[BackgroundDependencyLoader]
private void load()
{
updateTime();
}
protected override void LoadComplete()
{
base.LoadComplete();
Scheduler.Add(updateTimeWithReschedule);
}
private void updateTimeWithReschedule()
{
updateTime();
var diffToNow = DateTimeOffset.Now.Subtract(date);
double timeUntilNextUpdate = 1000;
if (diffToNow.TotalSeconds > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalMinutes > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalHours > 24)
timeUntilNextUpdate *= 24;
}
}
Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate);
}
public override bool HandleMouseInput => true;
protected virtual string Format() => date.Humanize();
private void updateTime() => Text = Format();
public virtual string TooltipText => string.Format($"{date:MMMM d, yyyy h:mm tt \"UTC\"z}");
}
}
| // 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 Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class DrawableDate : OsuSpriteText, IHasTooltip
{
private readonly DateTimeOffset date;
public DrawableDate(DateTimeOffset date)
{
AutoSizeAxes = Axes.Both;
Font = "Exo2.0-RegularItalic";
this.date = date.ToLocalTime();
}
[BackgroundDependencyLoader]
private void load()
{
updateTime();
}
protected override void LoadComplete()
{
base.LoadComplete();
Scheduler.Add(updateTimeWithReschedule);
}
private void updateTimeWithReschedule()
{
updateTime();
var diffToNow = DateTimeOffset.Now.Subtract(date);
double timeUntilNextUpdate = 1000;
if (diffToNow.TotalSeconds > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalMinutes > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalHours > 24)
timeUntilNextUpdate *= 24;
}
}
Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate);
}
public override bool HandleMouseInput => true;
protected virtual string Format() => Text = date.Humanize();
private void updateTime() => Format();
public virtual string TooltipText => string.Format($"{date:MMMM d, yyyy h:mm tt \"UTC\"z}");
}
}
| mit | C# |
4385001d282c83eadb462d74fcab789af9d68538 | Fix solo leaderboard seeing imported score via realm subscription flow | peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game/Screens/Play/SoloPlayer.cs | osu.Game/Screens/Play/SoloPlayer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Online.Solo;
using osu.Game.Scoring;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Screens.Play
{
public class SoloPlayer : SubmittingPlayer
{
public SoloPlayer()
: this(null)
{
}
protected SoloPlayer(PlayerConfiguration configuration = null)
: base(configuration)
{
}
protected override APIRequest<APIScoreToken> CreateTokenRequest()
{
int beatmapId = Beatmap.Value.BeatmapInfo.OnlineID;
int rulesetId = Ruleset.Value.OnlineID;
if (beatmapId <= 0)
return null;
if (!Ruleset.Value.IsLegacyRuleset())
return null;
return new CreateSoloScoreRequest(Beatmap.Value.BeatmapInfo, rulesetId, Game.VersionHash);
}
public readonly BindableList<ScoreInfo> LeaderboardScores = new BindableList<ScoreInfo>();
protected override GameplayLeaderboard CreateGameplayLeaderboard() =>
new SoloGameplayLeaderboard(Score.ScoreInfo.User)
{
Scores = { BindTarget = LeaderboardScores }
};
protected override bool HandleTokenRetrievalFailure(Exception exception) => false;
protected override Task ImportScore(Score score)
{
// Before importing a score, stop binding the leaderboard with its score source.
// This avoids a case where the imported score may cause a leaderboard refresh
// (if the leaderboard's source is local).
LeaderboardScores.UnbindBindings();
return base.ImportScore(score);
}
protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token)
{
IBeatmapInfo beatmap = score.ScoreInfo.BeatmapInfo;
Debug.Assert(beatmap.OnlineID > 0);
return new SubmitSoloScoreRequest(score.ScoreInfo, token, beatmap.OnlineID);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Diagnostics;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Online.Solo;
using osu.Game.Scoring;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Screens.Play
{
public class SoloPlayer : SubmittingPlayer
{
public SoloPlayer()
: this(null)
{
}
protected SoloPlayer(PlayerConfiguration configuration = null)
: base(configuration)
{
}
protected override APIRequest<APIScoreToken> CreateTokenRequest()
{
int beatmapId = Beatmap.Value.BeatmapInfo.OnlineID;
int rulesetId = Ruleset.Value.OnlineID;
if (beatmapId <= 0)
return null;
if (!Ruleset.Value.IsLegacyRuleset())
return null;
return new CreateSoloScoreRequest(Beatmap.Value.BeatmapInfo, rulesetId, Game.VersionHash);
}
public readonly BindableList<ScoreInfo> LeaderboardScores = new BindableList<ScoreInfo>();
protected override GameplayLeaderboard CreateGameplayLeaderboard() =>
new SoloGameplayLeaderboard(Score.ScoreInfo.User)
{
Scores = { BindTarget = LeaderboardScores }
};
protected override bool HandleTokenRetrievalFailure(Exception exception) => false;
protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token)
{
IBeatmapInfo beatmap = score.ScoreInfo.BeatmapInfo;
Debug.Assert(beatmap.OnlineID > 0);
return new SubmitSoloScoreRequest(score.ScoreInfo, token, beatmap.OnlineID);
}
}
}
| mit | C# |
92375b3f54ce17ae6a7635e38865a40354cf321a | Fix up comment. | shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,khyperia/roslyn,brettfo/roslyn,AnthonyDGreen/roslyn,wvdd007/roslyn,heejaechang/roslyn,weltkante/roslyn,nguerrera/roslyn,mavasani/roslyn,aelij/roslyn,abock/roslyn,stephentoub/roslyn,kelltrick/roslyn,tvand7093/roslyn,tmeschter/roslyn,VSadov/roslyn,bartdesmet/roslyn,nguerrera/roslyn,brettfo/roslyn,jamesqo/roslyn,zooba/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,a-ctor/roslyn,a-ctor/roslyn,ErikSchierboom/roslyn,srivatsn/roslyn,VSadov/roslyn,xoofx/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,xoofx/roslyn,heejaechang/roslyn,jkotas/roslyn,KevinH-MS/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,dotnet/roslyn,Hosch250/roslyn,CaptainHayashi/roslyn,mattwar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mattscheffer/roslyn,wvdd007/roslyn,xasx/roslyn,aelij/roslyn,mavasani/roslyn,lorcanmooney/roslyn,AmadeusW/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,physhi/roslyn,jcouv/roslyn,paulvanbrenk/roslyn,panopticoncentral/roslyn,AArnott/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,weltkante/roslyn,CaptainHayashi/roslyn,KevinRansom/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,srivatsn/roslyn,davkean/roslyn,vslsnap/roslyn,KevinH-MS/roslyn,davkean/roslyn,DustinCampbell/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,ErikSchierboom/roslyn,xoofx/roslyn,cston/roslyn,yeaicc/roslyn,dotnet/roslyn,Giftednewt/roslyn,zooba/roslyn,paulvanbrenk/roslyn,dpoeschl/roslyn,TyOverby/roslyn,gafter/roslyn,MattWindsor91/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,DustinCampbell/roslyn,lorcanmooney/roslyn,VSadov/roslyn,mavasani/roslyn,KevinH-MS/roslyn,pdelvo/roslyn,AlekseyTs/roslyn,jcouv/roslyn,DustinCampbell/roslyn,a-ctor/roslyn,stephentoub/roslyn,jkotas/roslyn,vslsnap/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,robinsedlaczek/roslyn,genlu/roslyn,AlekseyTs/roslyn,bbarry/roslyn,bbarry/roslyn,robinsedlaczek/roslyn,eriawan/roslyn,orthoxerox/roslyn,yeaicc/roslyn,agocke/roslyn,AArnott/roslyn,drognanar/roslyn,gafter/roslyn,dpoeschl/roslyn,cston/roslyn,sharwell/roslyn,jmarolf/roslyn,bbarry/roslyn,drognanar/roslyn,diryboy/roslyn,eriawan/roslyn,zooba/roslyn,bkoelman/roslyn,jcouv/roslyn,TyOverby/roslyn,jkotas/roslyn,abock/roslyn,KevinRansom/roslyn,mattscheffer/roslyn,Giftednewt/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,yeaicc/roslyn,jmarolf/roslyn,khyperia/roslyn,amcasey/roslyn,xasx/roslyn,swaroop-sridhar/roslyn,tvand7093/roslyn,amcasey/roslyn,reaction1989/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,AArnott/roslyn,AmadeusW/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xasx/roslyn,diryboy/roslyn,aelij/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,Giftednewt/roslyn,AnthonyDGreen/roslyn,wvdd007/roslyn,diryboy/roslyn,jeffanders/roslyn,jeffanders/roslyn,vslsnap/roslyn,akrisiun/roslyn,dpoeschl/roslyn,akrisiun/roslyn,MichalStrehovsky/roslyn,jmarolf/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,mattwar/roslyn,tmat/roslyn,lorcanmooney/roslyn,AnthonyDGreen/roslyn,dotnet/roslyn,mattscheffer/roslyn,OmarTawfik/roslyn,bkoelman/roslyn,kelltrick/roslyn,pdelvo/roslyn,drognanar/roslyn,bartdesmet/roslyn,Hosch250/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,gafter/roslyn,sharwell/roslyn,jamesqo/roslyn,mmitche/roslyn,sharwell/roslyn,heejaechang/roslyn,cston/roslyn,jamesqo/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,nguerrera/roslyn,amcasey/roslyn,bartdesmet/roslyn,tmeschter/roslyn,reaction1989/roslyn,pdelvo/roslyn,KirillOsenkov/roslyn,tvand7093/roslyn,mmitche/roslyn,orthoxerox/roslyn,agocke/roslyn,abock/roslyn,TyOverby/roslyn,khyperia/roslyn,OmarTawfik/roslyn,mattwar/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,Hosch250/roslyn,MichalStrehovsky/roslyn,jeffanders/roslyn,genlu/roslyn,genlu/roslyn,agocke/roslyn,AmadeusW/roslyn,CaptainHayashi/roslyn,kelltrick/roslyn,mmitche/roslyn,akrisiun/roslyn,physhi/roslyn,bkoelman/roslyn | src/Workspaces/Core/Portable/AddImport/IAddImportService.cs | src/Workspaces/Core/Portable/AddImport/IAddImportService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddImport
{
internal interface IAddImportService : ILanguageService
{
SyntaxNode AddImports(
SyntaxNode root, SyntaxNode contextLocation,
IEnumerable<SyntaxNode> newImports, bool placeSystemNamespaceFirst);
/// <summary>
/// Given a context location in a provided syntax tree, returns the appropriate container
/// that <paramref name="import"/> should be added to.
/// </summary>
SyntaxNode GetImportContainer(SyntaxNode root, SyntaxNode contextLocation, SyntaxNode import);
}
internal static class IAddImportServiceExtensions
{
public static SyntaxNode AddImport(
this IAddImportService service, SyntaxNode root, SyntaxNode contextLocation,
SyntaxNode newImport, bool placeSystemNamespaceFirst)
{
return service.AddImports(root, contextLocation,
SpecializedCollections.SingletonEnumerable(newImport), placeSystemNamespaceFirst);
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddImport
{
internal interface IAddImportService : ILanguageService
{
SyntaxNode AddImports(
SyntaxNode root, SyntaxNode contextLocation,
IEnumerable<SyntaxNode> newImports, bool placeSystemNamespaceFirst);
/// <summary>
/// Given a context location in a provided syntax tree, returns the appropriate container
/// that <paramref name="import"/> should should be added to.
/// </summary>
SyntaxNode GetImportContainer(SyntaxNode root, SyntaxNode contextLocation, SyntaxNode import);
}
internal static class IAddImportServiceExtensions
{
public static SyntaxNode AddImport(
this IAddImportService service, SyntaxNode root, SyntaxNode contextLocation,
SyntaxNode newImport, bool placeSystemNamespaceFirst)
{
return service.AddImports(root, contextLocation,
SpecializedCollections.SingletonEnumerable(newImport), placeSystemNamespaceFirst);
}
}
} | mit | C# |
5578d30f9d8950b13f70a240b75f7a3eb81e5f4e | update version | zaverden/zerobased | Zerobased.Core/Properties/AssemblyInfo.cs | Zerobased.Core/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("Zerobased.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Zerobased.Core")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("980ba3ac-3f15-4f5d-8386-95062d8137db")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.4.0")]
[assembly: AssemblyFileVersion("1.0.4.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("Zerobased.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Zerobased.Core")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("980ba3ac-3f15-4f5d-8386-95062d8137db")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
| mit | C# |
0e27103cf0b118465842ad8117edc9afb8defc83 | Allow multiple rule instances in autofac activator | prashanthr/NRules,NRules/NRules | src/NRules.Integration/NRules.Integration.Autofac/NRules.Integration.Autofac/AutofacRuleActivator.cs | src/NRules.Integration/NRules.Integration.Autofac/NRules.Integration.Autofac/AutofacRuleActivator.cs | using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;
namespace NRules.Integration.Autofac
{
/// <summary>
/// Rule activator that uses Autofac DI container.
/// </summary>
public class AutofacRuleActivator : IRuleActivator
{
private readonly ILifetimeScope _container;
public AutofacRuleActivator(ILifetimeScope container)
{
_container = container;
}
public IEnumerable<Rule> Activate(Type type)
{
if (_container.IsRegistered(type))
{
var collectionType = typeof (IEnumerable<>).MakeGenericType(type);
return (IEnumerable<Rule>)_container.Resolve(collectionType);
}
return ActivateDefault(type);
}
private static IEnumerable<Rule> ActivateDefault(Type type)
{
yield return (Rule) Activator.CreateInstance(type);
}
}
} | using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;
namespace NRules.Integration.Autofac
{
/// <summary>
/// Rule activator that uses Autofac DI container.
/// </summary>
public class AutofacRuleActivator : IRuleActivator
{
private readonly ILifetimeScope _container;
public AutofacRuleActivator(ILifetimeScope container)
{
_container = container;
}
public IEnumerable<Rule> Activate(Type type)
{
if (_container.IsRegistered(type))
yield return (Rule) _container.Resolve(type);
yield return (Rule)Activator.CreateInstance(type);
}
}
} | mit | C# |
95b539f0a90cbbc469de975344244db9d59c89a6 | change wrong layout for SettingsActivity | ueman/CommitStripReader | CommitStrip/CommitStrip.Droid/Activities/SettingsActivity.cs | CommitStrip/CommitStrip.Droid/Activities/SettingsActivity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CommitStrip.Core.ViewModels;
namespace CommitStrip.Droid.Activities
{
[Activity(Label = "SettingsActivity", Theme = "@style/AppTheme")]
public class SettingsActivity : BaseActivity<SettingsViewModel>
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.view_settings);
SupportActionBar?.SetDisplayHomeAsUpEnabled(true);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
OnBackPressed();
return true;
}
return base.OnOptionsItemSelected(item);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CommitStrip.Core.ViewModels;
namespace CommitStrip.Droid.Activities
{
[Activity(Label = "SettingsActivity", Theme = "@style/AppTheme")]
public class SettingsActivity : BaseActivity<SettingsViewModel>
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.view_comic_detail);
SupportActionBar?.SetDisplayHomeAsUpEnabled(true);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
OnBackPressed();
return true;
}
return base.OnOptionsItemSelected(item);
}
}
} | apache-2.0 | C# |
d4306866a4145ad80176f6db9138b5612b89547e | Document UIActionBindings API. | PenguinF/sandra-three | Eutherion/Win/UIActions/UIActionBindings.cs | Eutherion/Win/UIActions/UIActionBindings.cs | #region License
/*********************************************************************************
* UIActionBindings.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.UIActions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Eutherion.Win.UIActions
{
/// <summary>
/// Enumerates a collection of handlers for a set of <see cref="UIAction"/> bindings.
/// Instances of this class can be declared with a collection initializer.
/// </summary>
public sealed class UIActionBindings : IEnumerable<UIActionBinding>
{
private readonly List<UIActionBinding> added = new List<UIActionBinding>();
/// <summary>
/// Initializes a new empty instance of <see cref="UIActionBindings"/>.
/// </summary>
public UIActionBindings() { }
/// <summary>
/// Initializes a new instance of <see cref="UIActionBindings"/> containing a collection of bindings.
/// </summary>
/// <param name="bindings">
/// The bindings to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="bindings"/> is null - or at least one of the elements of the enumeration is null.
/// </exception>
public UIActionBindings(IEnumerable<UIActionBinding> bindings)
=> AddRange(bindings);
/// <summary>
/// Adds a binding.
/// </summary>
/// <param name="binding">
/// The binding to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="binding"/> is null.
/// </exception>
public void Add(UIActionBinding binding)
=> added.Add(binding ?? throw new ArgumentNullException(nameof(binding)));
/// <summary>
/// Adds a binding.
/// </summary>
/// <param name="binding">
/// The <see cref="DefaultUIActionBinding"/> to add.
/// </param>
/// <param name="handler">
/// The handler to add for the binding.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="binding"/> and/or <paramref name="handler"/> are null.
/// </exception>
public void Add(DefaultUIActionBinding binding, UIActionHandlerFunc handler)
=> added.Add(new UIActionBinding(binding, handler));
/// <summary>
/// Adds a collection of bindings.
/// </summary>
/// <param name="bindings">
/// The bindings to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="bindings"/> is null - or at least one of the elements of the enumeration is null.
/// </exception>
public void AddRange(IEnumerable<UIActionBinding> bindings)
=> (bindings ?? throw new ArgumentNullException(nameof(bindings))).ForEach(Add);
/// <summary>
/// Gets an enumerator that iterates through the bindings of this collection.
/// </summary>
/// <returns>
/// The enumerator that iterates through the bindings of this collection.
/// </returns>
public IEnumerator<UIActionBinding> GetEnumerator() => added.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => added.GetEnumerator();
}
}
| #region License
/*********************************************************************************
* UIActionBindings.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
using Eutherion.UIActions;
using System.Collections;
using System.Collections.Generic;
namespace Eutherion.Win.UIActions
{
/// <summary>
/// Enumerates a collection of handlers for a set of <see cref="UIAction"/> bindings.
/// Instances of this class can be declared with a collection initializer.
/// </summary>
public sealed class UIActionBindings : IEnumerable<UIActionBinding>
{
private readonly List<UIActionBinding> added = new List<UIActionBinding>();
public void Add(DefaultUIActionBinding key, UIActionHandlerFunc value) => added.Add(new UIActionBinding(key, value));
IEnumerator IEnumerable.GetEnumerator() => added.GetEnumerator();
IEnumerator<UIActionBinding> IEnumerable<UIActionBinding>.GetEnumerator() => added.GetEnumerator();
}
}
| apache-2.0 | C# |
5f5d93beba6fb71ecf868e22df000434491578a6 | Use nameof operator instead of magic string. | Quickshot/DupImageLib,Quickshot/DupImage | DupImage/ImageStruct.cs | DupImage/ImageStruct.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(String pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public String ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException("file");
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(String pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public String ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
| unknown | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.