doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
7c3d0af6-8507-4a54-a262-720c494501f1 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind>
{
protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } =
ImmutableArray.Create(
SyntaxKind.VariableDeclarator,
SyntaxKind.ForEachStatement,
SyntaxKind.CatchDeclaration,
SyntaxKind.SingleVariableDesignation,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.Parameter,
SyntaxKind.TypeParameter);
// Parameters of positional record declarations should be ignored because they also
// considered properties, and that naming style makes more sense
protected override bool ShouldIgnore(ISymbol symbol)
=> (symbol.IsKind(SymbolKind.Parameter)
&& IsParameterOfRecordDeclaration(symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax()))
|| !symbol.CanBeReferencedByName;
private static bool IsParameterOfRecordDeclaration(SyntaxNode? node)
=> node is ParameterSyntax
{
Parent: ParameterListSyntax
{
Parent: RecordDeclarationSyntax
}
};
}
}
```
Expand and add comment for ShouldIgnore. | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpNamingStyleDiagnosticAnalyzer : NamingStyleDiagnosticAnalyzerBase<SyntaxKind>
{
protected override ImmutableArray<SyntaxKind> SupportedSyntaxKinds { get; } =
ImmutableArray.Create(
SyntaxKind.VariableDeclarator,
SyntaxKind.ForEachStatement,
SyntaxKind.CatchDeclaration,
SyntaxKind.SingleVariableDesignation,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.Parameter,
SyntaxKind.TypeParameter);
protected override bool ShouldIgnore(ISymbol symbol)
{
if (symbol.IsKind(SymbolKind.Parameter)
&& symbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is ParameterSyntax
{
Parent: ParameterListSyntax
{
Parent: RecordDeclarationSyntax
}
})
{
// Parameters of positional record declarations should be ignored because they also
// considered properties, and that naming style makes more sense
return true;
}
if (!symbol.CanBeReferencedByName)
{
// Explicit interface implementation falls into here, as they don't own their names
// Two symbols are involved here, and symbol.ExplicitInterfaceImplementations only applies for one
return true;
}
return false;
}
}
}
``` |
55de7bee-5f2d-4aaa-aada-df96b27d95eb | {
"language": "C#"
} | ```c#
using System;
namespace FractionCalculator.Class
{
public struct Fraction
{
private long numerator;
private long denominator;
public Fraction(long numerator, long denominator) : this()
{
this.Numerator = numerator;
this.Denominator = denominator;
}
public long Denominator
{
get { return this.denominator; }
set
{
if (value <= 0)
throw new DivideByZeroException("Denominator cannot be zero or negative");
this.denominator = value;
}
}
public long Numerator
{
get { return this.numerator; }
set
{
if (value <= 0)
throw new ArgumentException("numerator", "Numerator cannot be zero or negative!");
this.numerator = value;
}
}
public override string ToString()
{
return string.Format();
}
}
}
```
Create method for overload operator + and - | ```c#
using System;
namespace FractionCalculator.Class
{
public struct Fraction
{
private long numerator;
private long denominator;
public Fraction(long numerator, long denominator) : this()
{
this.Numerator = numerator;
this.Denominator = denominator;
}
public long Denominator
{
get { return this.denominator; }
set
{
if (value <= 0)
throw new DivideByZeroException("Denominator cannot be zero or negative");
this.denominator = value;
}
}
public long Numerator
{
get { return this.numerator; }
set
{
if (value <= 0)
throw new ArgumentException("numerator", "Numerator cannot be zero or negative!");
this.numerator = value;
}
}
public static Fraction operator +(Fraction fraction1, Fraction fraction2)
{
return new Fraction(fraction1.Numerator + fraction2.Numerator, fraction1.Denominator + fraction2.Denominator);
}
public static Fraction operator -(Fraction fraction1, Fraction fraction2)
{
return new Fraction(fraction1.Numerator - fraction2.Numerator, fraction1.Denominator - fraction2.Denominator);
}
//public override string ToString()
//{
// return string.Format();
//}
}
}
``` |
f1d69fdc-765d-441a-8f73-cd021d400cba | {
"language": "C#"
} | ```c#
// 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.
/*=============================================================================
**
** File: ExceptionNotification.cs
**
**
** Purpose: Contains definitions for supporting Exception Notifications.
**
** Created: 10/07/2008
**
** <owner>gkhanna</owner>
**
=============================================================================*/
#if FEATURE_EXCEPTION_NOTIFICATIONS
namespace System.Runtime.ExceptionServices {
using System;
// Definition of the argument-type passed to the FirstChanceException event handler
public class FirstChanceExceptionEventArgs : EventArgs
{
// Constructor
public FirstChanceExceptionEventArgs(Exception exception)
{
m_Exception = exception;
}
// Returns the exception object pertaining to the first chance exception
public Exception Exception
{
get { return m_Exception; }
}
// Represents the FirstChance exception instance
private Exception m_Exception;
}
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS```
Remove FirstChanceExceptionEventArgs from BCL folder. The file has been moved into mscorlib folder | ```c#
// 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.
/*=============================================================================
**
** File: ExceptionNotification.cs
**
**
** Purpose: Contains definitions for supporting Exception Notifications.
**
** Created: 10/07/2008
**
** <owner>gkhanna</owner>
**
=============================================================================*/
#if FEATURE_EXCEPTION_NOTIFICATIONS
namespace System.Runtime.ExceptionServices {
using System;
using System.Runtime.ConstrainedExecution;
// Definition of the argument-type passed to the FirstChanceException event handler
public class FirstChanceExceptionEventArgs : EventArgs
{
// Constructor
public FirstChanceExceptionEventArgs(Exception exception)
{
m_Exception = exception;
}
// Returns the exception object pertaining to the first chance exception
public Exception Exception
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return m_Exception; }
}
// Represents the FirstChance exception instance
private Exception m_Exception;
}
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS``` |
66b37e9d-9fa9-4a17-ada1-5010a04d1fb8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// An unimplemented or unknown subcommand for the 0x6D packets.
/// </summary>
[WireDataContract]
public sealed class UnknownSubCommand6DCommand : BaseSubCommand6D, IUnknownPayloadType
{
/// <inheritdoc />
public short OperationCode => (short)base.CommandOperationCode;
/// <inheritdoc />
[ReadToEnd]
[WireMember(1)]
public byte[] UnknownBytes { get; } = new byte[0]; //readtoend requires at least an empty array init
private UnknownSubCommand6DCommand()
{
}
/// <inheritdoc />
public override string ToString()
{
if(Enum.IsDefined(typeof(SubCommand6DOperationCode), (byte)OperationCode))
return $"Unknown Subcommand6D OpCode: {OperationCode:X} Name: {((SubCommand6DOperationCode)OperationCode).ToString()} Type: {GetType().Name} CommandSize: {CommandSize * 4 - 2} (bytes size)";
else
return $"Unknown Subcommand6D OpCode: {OperationCode:X} Type: {GetType().Name} CommandSize: {CommandSize * 4 - 2} (bytes size)";
}
}
}
```
Fix unknown 0x6D size logging | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// An unimplemented or unknown subcommand for the 0x6D packets.
/// </summary>
[WireDataContract]
public sealed class UnknownSubCommand6DCommand : BaseSubCommand6D, IUnknownPayloadType
{
/// <inheritdoc />
public short OperationCode => (short)base.CommandOperationCode;
/// <inheritdoc />
[ReadToEnd]
[WireMember(1)]
public byte[] UnknownBytes { get; } = new byte[0]; //readtoend requires at least an empty array init
private UnknownSubCommand6DCommand()
{
}
/// <inheritdoc />
public override string ToString()
{
if(Enum.IsDefined(typeof(SubCommand6DOperationCode), (byte)OperationCode))
return $"Unknown Subcommand6D OpCode: {OperationCode:X} Name: {((SubCommand6DOperationCode)OperationCode).ToString()} Type: {GetType().Name} CommandSize: {CommandSize} (bytes size)";
else
return $"Unknown Subcommand6D OpCode: {OperationCode:X} Type: {GetType().Name} CommandSize: {CommandSize} (bytes size)";
}
}
}
``` |
1d8c7bab-c442-49ba-8a16-489758df57da | {
"language": "C#"
} | ```c#
using Microsoft.AspNet.Identity;
using SendGrid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
namespace VotingApplication.Web.Api.Services
{
public class SendMailEmailSender : IMailSender
{
private NetworkCredential credentials;
private string hostEmail;
public SendMailEmailSender(NetworkCredential credentials, string hostEmail)
{
this.credentials = credentials;
this.hostEmail = hostEmail;
}
public Task SendMail(string to, string subject, string message)
{
SendGridMessage mail = new SendGridMessage();
mail.From = new MailAddress(this.hostEmail, "Voting App");
mail.AddTo(to);
mail.Subject = subject;
mail.Html = message;
var transportWeb = new SendGrid.Web(this.credentials);
return transportWeb.DeliverAsync(mail);
}
}
}```
Fix email sender to 'vote on' | ```c#
using SendGrid;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace VotingApplication.Web.Api.Services
{
public class SendMailEmailSender : IMailSender
{
private NetworkCredential credentials;
private string hostEmail;
public SendMailEmailSender(NetworkCredential credentials, string hostEmail)
{
this.credentials = credentials;
this.hostEmail = hostEmail;
}
public Task SendMail(string to, string subject, string message)
{
SendGridMessage mail = new SendGridMessage();
mail.From = new MailAddress(this.hostEmail, "Vote On");
mail.AddTo(to);
mail.Subject = subject;
mail.Html = message;
var transportWeb = new SendGrid.Web(this.credentials);
return transportWeb.DeliverAsync(mail);
}
}
}``` |
aa592245-58ed-40dd-9b9e-ce11ee743a80 | {
"language": "C#"
} | ```c#
// 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.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class CodeAnalysisService : IRemoteNavigateToSearchService
{
public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync(
DocumentId documentId, string searchPattern)
{
var solution = await GetSolutionAsync().ConfigureAwait(false);
var project = solution.GetDocument(documentId);
var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync(
project, searchPattern, CancellationToken).ConfigureAwait(false);
return Convert(result);
}
public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync(
ProjectId projectId, string searchPattern)
{
var solution = await GetSolutionAsync().ConfigureAwait(false);
var project = solution.GetProject(projectId);
var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync(
project, searchPattern, CancellationToken).ConfigureAwait(false);
return Convert(result);
}
private SerializableNavigateToSearchResult[] Convert(
ImmutableArray<INavigateToSearchResult> result)
{
return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray();
}
}
}```
Boost priority of NavigateTo when running in OOP server. | ```c#
// 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.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class CodeAnalysisService : IRemoteNavigateToSearchService
{
public async Task<SerializableNavigateToSearchResult[]> SearchDocumentAsync(
DocumentId documentId, string searchPattern)
{
using (UserOperationBooster.Boost())
{
var solution = await GetSolutionAsync().ConfigureAwait(false);
var project = solution.GetDocument(documentId);
var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync(
project, searchPattern, CancellationToken).ConfigureAwait(false);
return Convert(result);
}
}
public async Task<SerializableNavigateToSearchResult[]> SearchProjectAsync(
ProjectId projectId, string searchPattern)
{
using (UserOperationBooster.Boost())
{
var solution = await GetSolutionAsync().ConfigureAwait(false);
var project = solution.GetProject(projectId);
var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync(
project, searchPattern, CancellationToken).ConfigureAwait(false);
return Convert(result);
}
}
private SerializableNavigateToSearchResult[] Convert(
ImmutableArray<INavigateToSearchResult> result)
{
return result.Select(SerializableNavigateToSearchResult.Dehydrate).ToArray();
}
}
}``` |
f8d4c559-b9c6-4df5-8227-a9b9876ec1a0 | {
"language": "C#"
} | ```c#
@model IEnumerable<Tag>
@{
ViewBag.Title = "Tag Index";
}
<h2>Tag Index</h2>
@if (User.Identity.IsAuthenticated)
{
<p>
<a asp-action="Create">Create new Tag</a>
</p>
}
<h3>@Model.Count() tags</h3>
<ul class="tag-buttons">
@Html.Partial("_TagButtons", Model)
</ul>
```
Update tag button container markup | ```c#
@model IEnumerable<Tag>
@{
ViewBag.Title = "Tag Index";
}
<h2>Tag Index</h2>
@if (User.Identity.IsAuthenticated)
{
<p>
<a asp-action="Create">Create new Tag</a>
</p>
}
<h3>@Model.Count() tags</h3>
<div>
@Html.Partial("_TagButtons", Model)
</div>``` |
551f0013-fc13-48a2-ae32-1e0898d1c06c | {
"language": "C#"
} | ```c#
using System;
namespace Terrajobst.Pns.Scanner
{
public struct PnsResult
{
public static readonly PnsResult DoesNotThrow = new PnsResult(-1);
private PnsResult(int level)
{
Level = level;
}
public static PnsResult ThrowsAt(int level)
{
return new PnsResult(level);
}
public PnsResult Combine(PnsResult other)
{
if (!Throws)
return other;
return ThrowsAt(Math.Min(Level, other.Level));
}
public bool Throws => Level >= 0;
public int Level { get; }
public override string ToString()
{
return Level.ToString();
}
}
}
```
Fix bug in properties and event detection | ```c#
using System;
namespace Terrajobst.Pns.Scanner
{
public struct PnsResult
{
public static readonly PnsResult DoesNotThrow = new PnsResult(-1);
private PnsResult(int level)
{
Level = level;
}
public static PnsResult ThrowsAt(int level)
{
return new PnsResult(level);
}
public PnsResult Combine(PnsResult other)
{
if (!Throws)
return other;
if (!other.Throws)
return this;
return ThrowsAt(Math.Min(Level, other.Level));
}
public bool Throws => Level >= 0;
public int Level { get; }
public override string ToString()
{
return Level.ToString();
}
}
}
``` |
76f45d5a-0828-44e3-8c94-374135b80def | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lokad.Cqrs.Properties;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using NUnit.Framework;
namespace Lokad.Cqrs.Feature.TapeStorage
{
[TestFixture]
public class BlobTapeStorageTests : TapeStorageTests
{
const string ContainerName = "blob-tape-test";
CloudBlobClient _cloudBlobClient;
ISingleThreadTapeWriterFactory _writerFactory;
ITapeReaderFactory _readerFactory;
protected override void SetUp()
{
CloudStorageAccount.SetConfigurationSettingPublisher(
(configName, configSetter) => configSetter((string) Settings.Default[configName]));
var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
_cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
_writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName);
_writerFactory.Init();
_readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName);
}
protected override void TearDown()
{
_cloudBlobClient.GetContainerReference(ContainerName).Delete();
}
protected override TestConfiguration GetConfiguration()
{
return new TestConfiguration
{
Name = "test",
WriterFactory = _writerFactory,
ReaderFactory = _readerFactory
};
}
}
}
```
Abort test if test container exists. | ```c#
using System;
using Lokad.Cqrs.Properties;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using NUnit.Framework;
namespace Lokad.Cqrs.Feature.TapeStorage
{
[TestFixture]
public class BlobTapeStorageTests : TapeStorageTests
{
const string ContainerName = "blob-tape-test";
CloudBlobClient _cloudBlobClient;
ISingleThreadTapeWriterFactory _writerFactory;
ITapeReaderFactory _readerFactory;
protected override void SetUp()
{
CloudStorageAccount.SetConfigurationSettingPublisher(
(configName, configSetter) => configSetter((string) Settings.Default[configName]));
var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
_cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
try
{
_cloudBlobClient.GetContainerReference(ContainerName).FetchAttributes();
throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
}
catch (StorageClientException e)
{
if (e.ErrorCode != StorageErrorCode.ResourceNotFound)
throw new InvalidOperationException("Container '" + ContainerName + "' already exists!");
}
_writerFactory = new BlobTapeWriterFactory(_cloudBlobClient, ContainerName);
_writerFactory.Init();
_readerFactory = new BlobTapeReaderFactory(_cloudBlobClient, ContainerName);
}
protected override void TearDown()
{
_cloudBlobClient.GetContainerReference(ContainerName).Delete();
}
protected override TestConfiguration GetConfiguration()
{
return new TestConfiguration
{
Name = "test",
WriterFactory = _writerFactory,
ReaderFactory = _readerFactory
};
}
}
}
``` |
df54a43d-b0bf-4b3c-9b66-641acf587f2c | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Steeltoe.Extensions.Configuration.CloudFoundry;
namespace CloudFoundry
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
// Lab01 - Lab04 Start
.AddCloudFoundry()
// Lab01 - Lab04 End
.Build();
}
}
```
Fix startup problem on windows | ```c#
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Steeltoe.Extensions.Configuration.CloudFoundry;
namespace CloudFoundry
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
// Lab01 - Lab04 Start
var configuration = new ConfigurationBuilder().AddCommandLine(args).Build();
// Lab01 - Lab04 End
return WebHost.CreateDefaultBuilder(args)
// Lab01 - Lab04 Start
.UseConfiguration(configuration)
// Lab01 - Lab04 End
.UseStartup<Startup>()
// Lab01 - Lab04 Start
.AddCloudFoundry()
// Lab01 - Lab04 End
.Build();
}
}
}
``` |
a4125871-8edd-4229-aa5f-876fd2e1458b | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
Refresh();
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
}```
Reset page number to 1 when perform a new search. Work items: 569 | ```c#
using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;
namespace NuGet.Dialog.Providers {
internal class PackagesSearchNode : PackagesTreeNodeBase {
private string _searchText;
private readonly PackagesTreeNodeBase _baseNode;
public PackagesTreeNodeBase BaseNode {
get {
return _baseNode;
}
}
public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
base(parent, provider) {
if (baseNode == null) {
throw new ArgumentNullException("baseNode");
}
_searchText = searchText;
_baseNode = baseNode;
// Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
IsSearchResultsNode = true;
}
public override string Name {
get {
return Resources.Dialog_RootNodeSearch;
}
}
public void SetSearchText(string newSearchText) {
if (newSearchText == null) {
throw new ArgumentNullException("newSearchText");
}
if (_searchText != newSearchText) {
_searchText = newSearchText;
if (IsSelected) {
ResetQuery();
LoadPage(1);
}
}
}
public override IQueryable<IPackage> GetPackages() {
return _baseNode.GetPackages().Find(_searchText);
}
}
}``` |
1ecb572f-74c8-44e3-8ed4-968898d473d2 | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDox.Build.Roslyn.MethodVisitors;
namespace SharpDox.Build.Roslyn.Parser.ProjectParser
{
internal class MethodCallParser : BaseParser
{
internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { }
internal void ParseMethodCalls()
{
var namespaces = ParserOptions.SDRepository.GetAllNamespaces();
foreach (var sdNamespace in namespaces)
{
foreach (var sdType in sdNamespace.Types)
{
foreach (var sdMethod in sdType.Methods)
{
HandleOnItemParseStart(sdMethod.Name);
var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).Single();
var file = ParserOptions.CodeSolution.GetDocument(fileId);
var syntaxTree = file.GetSyntaxTreeAsync().Result;
if (file.Project.Language == "C#")
{
var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file);
var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
.Single(m => m.Span.Start == sdMethod.Region.Start &&
m.Span.End == sdMethod.Region.End);
methodVisitor.Visit(methodSyntaxNode);
}
else if (file.Project.Language == "VBNET")
{
}
}
}
}
}
}
}
```
Fix Roslyn compiler issues when the same file is being used for multiple target platforms (and might result in a class without methods) | ```c#
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDox.Build.Roslyn.MethodVisitors;
namespace SharpDox.Build.Roslyn.Parser.ProjectParser
{
internal class MethodCallParser : BaseParser
{
internal MethodCallParser(ParserOptions parserOptions) : base(parserOptions) { }
internal void ParseMethodCalls()
{
var namespaces = ParserOptions.SDRepository.GetAllNamespaces();
foreach (var sdNamespace in namespaces)
{
foreach (var sdType in sdNamespace.Types)
{
foreach (var sdMethod in sdType.Methods)
{
HandleOnItemParseStart(sdMethod.Name);
var fileId = ParserOptions.CodeSolution.GetDocumentIdsWithFilePath(sdMethod.Region.FilePath).FirstOrDefault();
var file = ParserOptions.CodeSolution.GetDocument(fileId);
var syntaxTree = file.GetSyntaxTreeAsync().Result;
if (file.Project.Language == "C#")
{
var methodVisitor = new CSharpMethodVisitor(ParserOptions.SDRepository, sdMethod, sdType, file);
var methodSyntaxNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
.FirstOrDefault(m => m.Span.Start == sdMethod.Region.Start &&
m.Span.End == sdMethod.Region.End);
if (methodSyntaxNode != null)
{
methodVisitor.Visit(methodSyntaxNode);
}
}
else if (file.Project.Language == "VBNET")
{
}
}
}
}
}
}
}
``` |
36d3acc4-8c9c-49c1-a817-d76cefb37d80 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Management.Sql;
using Xunit;
namespace Sql.Tests
{
public class ServiceObjectiveScenarioTests
{
[Fact]
public void TestGetListServiceObjectives()
{
string testPrefix = "sqlcrudtest-";
string suiteName = this.GetType().FullName;
string serverName = SqlManagementTestUtilities.GenerateName(testPrefix);
SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, "TestGetListServiceObjectives", testPrefix, (resClient, sqlClient, resourceGroup, server) =>
{
var serviceObjectives = sqlClient.Servers.ListServiceObjectives(resourceGroup.Name, server.Name);
foreach(ServiceObjective objective in serviceObjectives)
{
Assert.NotNull(objective.ServiceObjectiveName);
Assert.NotNull(objective.IsDefault);
Assert.NotNull(objective.IsSystem);
Assert.NotNull(objective.Enabled);
// Assert Get finds the service objective from List
Assert.NotNull(sqlClient.Servers.GetServiceObjective(resourceGroup.Name, server.Name, objective.Name));
}
});
}
}
}
```
Fix test failing in playback | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.Azure.Management.Sql;
using Xunit;
namespace Sql.Tests
{
public class ServiceObjectiveScenarioTests
{
[Fact]
public void TestGetListServiceObjectives()
{
string testPrefix = "sqlcrudtest-";
string suiteName = this.GetType().FullName;
SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, "TestGetListServiceObjectives", testPrefix, (resClient, sqlClient, resourceGroup, server) =>
{
var serviceObjectives = sqlClient.Servers.ListServiceObjectives(resourceGroup.Name, server.Name);
foreach(ServiceObjective objective in serviceObjectives)
{
Assert.NotNull(objective.ServiceObjectiveName);
Assert.NotNull(objective.IsDefault);
Assert.NotNull(objective.IsSystem);
Assert.NotNull(objective.Enabled);
// Assert Get finds the service objective from List
Assert.NotNull(sqlClient.Servers.GetServiceObjective(resourceGroup.Name, server.Name, objective.Name));
}
});
}
}
}
``` |
2f8567d1-cf61-41c2-b1c3-29674fd64b03 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class LocalsCommand : ICommand
{
public string Name
{
get { return "Locals"; }
}
public string Description
{
get { return "Prints local variables."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var backtrace = SoftDebugger.Backtrace;
if (backtrace == null)
{
Logger.WriteErrorLine("No backtrace available.");
return;
}
var frame = backtrace.CurrentStackFrame;
if (frame == null)
{
Logger.WriteErrorLine("No stack frame available.");
return;
}
foreach (var local in frame.GetLocalVariables())
Logger.WriteInfoLine("[{0}] {1}: {2}", local.TypeName, local.Name, local.DisplayValue);
}
}
}
```
Make local evaluation a little safer. | ```c#
using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class LocalsCommand : ICommand
{
public string Name
{
get { return "Locals"; }
}
public string Description
{
get { return "Prints local variables."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var backtrace = SoftDebugger.Backtrace;
if (backtrace == null)
{
Logger.WriteErrorLine("No backtrace available.");
return;
}
var frame = backtrace.CurrentStackFrame;
if (frame == null)
{
Logger.WriteErrorLine("No stack frame available.");
return;
}
foreach (var local in frame.GetLocalVariables())
if (!local.IsUnknown && !local.IsError && !local.IsNotSupported)
Logger.WriteInfoLine("[{0}] {1}: {2}", local.TypeName, local.Name, local.DisplayValue);
}
}
}
``` |
978ca464-f726-45e7-9084-361410cca445 | {
"language": "C#"
} | ```c#
using OrienteeringToolWPF.Model;
using OrienteeringToolWPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrienteeringToolWPF.DAO
{
public static class CompetitorHelper
{
public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId)
{
var db = DatabaseUtils.GetDatabase();
dynamic resultsAlias, punchAlias;
var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId)
.LeftJoin(db.Results, out resultsAlias)
.On(db.Results.Chip == db.Competitors.Chip)
.LeftJoin(db.Punches, out punchAlias)
.On(db.Punches.Chip == db.Competitors.Chip)
.With(resultsAlias)
.With(punchAlias);
foreach (var competitor in CompetitorList)
{
var punches = (List<Punch>)competitor.Punches;
try
{
punches?.Sort();
Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime);
Punch.CalculateDeltaPrevious(ref punches);
}
catch (ArgumentNullException) { }
competitor.Punches = punches;
}
return CompetitorList;
}
}
}
```
Change exception to proper class | ```c#
using OrienteeringToolWPF.Model;
using OrienteeringToolWPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrienteeringToolWPF.DAO
{
public static class CompetitorHelper
{
public static List<Competitor> CompetitorsJoinedWhereRelayId(long RelayId)
{
var db = DatabaseUtils.GetDatabase();
dynamic resultsAlias, punchAlias;
var CompetitorList = (List<Competitor>)db.Competitors.FindAllByRelayId(RelayId)
.LeftJoin(db.Results, out resultsAlias)
.On(db.Results.Chip == db.Competitors.Chip)
.LeftJoin(db.Punches, out punchAlias)
.On(db.Punches.Chip == db.Competitors.Chip)
.With(resultsAlias)
.With(punchAlias);
foreach (var competitor in CompetitorList)
{
var punches = (List<Punch>)competitor.Punches;
try
{
punches?.Sort();
Punch.CalculateDeltaStart(ref punches, competitor.Result.StartTime);
Punch.CalculateDeltaPrevious(ref punches);
}
catch (NullReferenceException) { }
competitor.Punches = punches;
}
return CompetitorList;
}
}
}
``` |
56a9b5f3-bdc2-4431-a30d-18b3614a03af | {
"language": "C#"
} | ```c#
using LiveScoreUpdateSystem.Data.Models.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace LiveScoreUpdateSystem.Data.Models
{
public class User : IdentityUser, IDeletable, IAuditable, IDataModel
{
public DateTime? CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
Guid IDataModel.Id => throw new NotImplementedException();
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
```
Remove fat arrow getter because of appveyor .net version support | ```c#
using LiveScoreUpdateSystem.Data.Models.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace LiveScoreUpdateSystem.Data.Models
{
public class User : IdentityUser, IDeletable, IAuditable, IDataModel
{
public DateTime? CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
Guid IDataModel.Id { get; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
``` |
a509c458-e72d-4317-a74c-a77d6fb62f47 | {
"language": "C#"
} | ```c#
@model Vehicle
@switch(Model.Status)
{
case Vehicle.VehicleStatus.FMC:
<span class="label label-success">FMC</span>
return;
case Vehicle.VehicleStatus.NMC:
<span class="label label-danger">NMC</span>
return;
default:
<span class="label label-warning">@Model</span>
return;
}```
Fix for Unknown status display | ```c#
@model Vehicle
@switch(Model.Status)
{
case Vehicle.VehicleStatus.FMC:
<span class="label label-success">FMC</span>
return;
case Vehicle.VehicleStatus.NMC:
<span class="label label-danger">NMC</span>
return;
case Vehicle.VehicleStatus.Unknown:
<span class="label label-warning">Unknown</span>
return;
}``` |
2aee94f8-f8ca-4ab1-a417-93d9aa3b4924 | {
"language": "C#"
} | ```c#
using System.Windows.Controls.Primitives;
namespace SharpGraphEditor.Controls.GraphElements
{
/// <summary>
/// Логика взаимодействия для VertexControl.xaml
/// </summary>
public partial class VertexControl : Thumb
{
public VertexControl()
{
InitializeComponent();
}
}
}
```
Fix bug: incorrectly determines the center of the top | ```c#
using System.Windows.Controls.Primitives;
namespace SharpGraphEditor.Controls.GraphElements
{
/// <summary>
/// Логика взаимодействия для VertexControl.xaml
/// </summary>
public partial class VertexControl : Thumb
{
public VertexControl()
{
InitializeComponent();
SizeChanged += (_, __) =>
{
var centerX = ActualWidth / 2;
var centerY = ActualHeight / 2;
Margin = new System.Windows.Thickness(-centerX, -centerY, centerX, centerY);
};
}
}
}
``` |
2739fc1f-3d03-46c2-8f04-2261ffebf72b | {
"language": "C#"
} | ```c#
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Responsive
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add responsive services.
services.AddDetection();
// Add framework services.
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseDetection();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
}```
Set endpoint routing in responsive sample web app | ```c#
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Responsive
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add responsive services.
services.AddDetection();
// Add framework services.
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseDetection();
app.UseRouting();
app.UseEndpoints(
endpoints =>
{
endpoints.MapControllerRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
"areas",
"{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
}
}
}``` |
ceb77c67-387d-4930-a438-53ee183e10e7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace CodeComb.AspNet.Upload.Models
{
public static class ModelBuilderExtensions
{
public static ModelBuilder SetupBlob(this ModelBuilder self)
{
return self.Entity<File>(e =>
{
e.HasIndex(x => x.Time);
e.HasIndex(x => x.FileName);
});
}
}
}
```
Rename setup blob => setup files | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace CodeComb.AspNet.Upload.Models
{
public static class ModelBuilderExtensions
{
public static ModelBuilder SetupFiles(this ModelBuilder self)
{
return self.Entity<File>(e =>
{
e.HasIndex(x => x.Time);
e.HasIndex(x => x.FileName);
});
}
}
}
``` |
20c374fe-4322-46e8-ab54-b1a16a945f5a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Forms.GoogleMaps
{
public static class GeoConstants
{
public const double EarthRadiusKm = 6371;
public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI;
public const double MetersPerMile = 1609.344;
public const double MetersPerKilometer = 1000.0;
}
}
```
Change classe accessibility to internal | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Forms.GoogleMaps
{
internal static class GeoConstants
{
public const double EarthRadiusKm = 6371;
public const double EarthCircumferenceKm = EarthRadiusKm * 2 * Math.PI;
public const double MetersPerMile = 1609.344;
public const double MetersPerKilometer = 1000.0;
}
}
``` |
5d0e6b2c-1763-40bb-8e32-3a7c73c60b86 | {
"language": "C#"
} | ```c#
using CodeHub.Services;
using GalaSoft.MvvmLight;
namespace CodeHub.ViewModels.Settings
{
public class NofiticationSettingsViewModel : ObservableObject
{
private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled);
public bool IsToastEnabled
{
get => _isToastEnabled;
set
{
if (_isToastEnabled != value)
{
_isToastEnabled = value;
SettingsService.Save(SettingsKeys.IsToastEnabled, value);
RaisePropertyChanged();
}
}
}
public NofiticationSettingsViewModel()
{
}
}
}
```
Update NotificationSettingsVM for LiveTiles settings | ```c#
using CodeHub.Services;
using GalaSoft.MvvmLight;
namespace CodeHub.ViewModels.Settings
{
public class NofiticationSettingsViewModel : ObservableObject
{
private bool _isToastEnabled = SettingsService.Get<bool>(SettingsKeys.IsToastEnabled);
private bool _isLiveTilesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesEnabled);
private bool _isLiveTilesBadgeEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTilesBadgeEnabled);
private bool _isLiveTileUpdateAllBadgesEnabled = SettingsService.Get<bool>(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled);
public bool IsToastEnabled
{
get => _isToastEnabled;
set
{
if (_isToastEnabled != value)
{
_isToastEnabled = value;
SettingsService.Save(SettingsKeys.IsToastEnabled, value);
RaisePropertyChanged(() => IsToastEnabled);
}
}
}
public bool IsLiveTilesEnabled
{
get => _isLiveTilesEnabled;
set
{
if (_isLiveTilesEnabled != value)
{
_isLiveTilesEnabled = value;
SettingsService.Save(SettingsKeys.IsLiveTilesEnabled, value);
RaisePropertyChanged(() => IsLiveTilesEnabled);
}
if (!value && IsLiveTilesBadgeEnabled)
{
IsLiveTilesBadgeEnabled = false;
}
}
}
public bool IsLiveTilesBadgeEnabled
{
get => _isLiveTilesBadgeEnabled;
set
{
if (_isLiveTilesBadgeEnabled != value)
{
_isLiveTilesBadgeEnabled = value;
SettingsService.Save(SettingsKeys.IsLiveTilesBadgeEnabled, value);
RaisePropertyChanged(() => IsLiveTilesBadgeEnabled);
}
if (!value && IsAllBadgesUpdateEnabled)
{
IsAllBadgesUpdateEnabled = false;
}
}
}
public bool IsAllBadgesUpdateEnabled
{
get => _isLiveTilesEnabled;
set
{
if (_isLiveTileUpdateAllBadgesEnabled != value)
{
_isLiveTileUpdateAllBadgesEnabled = value;
SettingsService.Save(SettingsKeys.IsLiveTileUpdateAllBadgesEnabled, value);
RaisePropertyChanged(() => IsAllBadgesUpdateEnabled);
}
}
}
public NofiticationSettingsViewModel()
{
}
}
}
``` |
1222eaac-01ef-4226-acc8-2da8bb40b1a9 | {
"language": "C#"
} | ```c#
// Helpers/Settings.cs
using Refractored.Xam.Settings;
using Refractored.Xam.Settings.Abstractions;
namespace CodeCamp.Helpers
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public static class Settings
{
private static ISettings AppSettings
{
get
{
return CrossSettings.Current;
}
}
#region Setting Constants
private const string SettingsKey = "settings_key";
private static readonly string SettingsDefault = string.Empty;
#endregion
public static string GeneralSettings
{
get
{
return AppSettings.GetValueOrDefault(SettingsKey, SettingsDefault);
}
set
{
//if value has changed then save it!
if (AppSettings.AddOrUpdateValue(SettingsKey, value))
AppSettings.Save();
}
}
}
}```
Update settings with username and conference ids | ```c#
// Helpers/Settings.cs
using Refractored.Xam.Settings;
using Refractored.Xam.Settings.Abstractions;
namespace CodeCamp.Helpers
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public static class Settings
{
private static ISettings AppSettings
{
get
{
return CrossSettings.Current;
}
}
#region Setting Constants
private const string UsernameKey = "username_key";
private static readonly string UsernameDefault = string.Empty;
private const string MasterConferenceKey = "masterconference_key";
private static readonly int MasterConferenceDefault = -1;
private const string ConferenceKey = "conference_key";
private static readonly int ConferenceDefault = -1;
#endregion
public static string UsernameSettings
{
get
{
return AppSettings.GetValueOrDefault(UsernameKey, UsernameDefault);
}
set
{
if (AppSettings.AddOrUpdateValue(UsernameKey, value))
AppSettings.Save();
}
}
public static int MasterConference
{
get
{
return AppSettings.GetValueOrDefault(MasterConferenceKey, MasterConferenceDefault);
}
set
{
if (AppSettings.AddOrUpdateValue(MasterConferenceKey, value))
AppSettings.Save();
}
}
public static int Conference
{
get
{
return AppSettings.GetValueOrDefault(ConferenceKey, ConferenceDefault);
}
set
{
if (AppSettings.AddOrUpdateValue(ConferenceKey, value))
AppSettings.Save();
}
}
}
}``` |
e44434b9-d913-47d0-9fd1-ffc6c12eeea7 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Collections.Generic;
namespace CyLR
{
internal static class CollectionPaths
{
public static List<string> GetPaths(Arguments arguments)
{
var paths = new List<string>
{
@"C:\Windows\System32\config",
@"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup",
@"C:\Windows\Prefetch",
@"C:\Windows\Tasks",
@"C:\Windows\SchedLgU.Txt",
@"C:\Windows\System32\winevt\logs",
@"C:\Windows\System32\drivers\etc\hosts",
@"C:\$MFT"
};
if (Platform.IsUnixLike())
{
paths = new List<string>
{
"/root/.bash_history",
"/var/logs"
};
}
if (arguments.CollectionFilePath != ".")
{
if (File.Exists(arguments.CollectionFilePath))
{
paths.Clear();
paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath));
}
else
{
Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath);
Console.WriteLine("Exiting");
throw new ArgumentException();
}
}
return paths;
}
}
}
```
Revert "Fixing bad default path." | ```c#
using System;
using System.IO;
using System.Collections.Generic;
namespace CyLR
{
internal static class CollectionPaths
{
public static List<string> GetPaths(Arguments arguments)
{
var paths = new List<string>
{
@"C:\Windows\System32\config",
@"C:\Windows\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup",
@"C:\Windows\Prefetch",
@"C:\Windows\Tasks",
@"C:\Windows\SchedLgU.Txt",
@"C:\Windows\System32\winevt\logs",
@"C:\Windows\System32\drivers\etc\hosts",
@"C:\$MFT"
};
if (Platform.IsUnixLike())
{
paths = new List<string>
{
"/root/.bash_history",
"/var/logs"
};
}
if (arguments.CollectionFilePath != ".")
{
if (File.Exists(arguments.CollectionFilePath))
{
paths.Clear();
paths.AddRange(File.ReadAllLines(arguments.CollectionFilePath));
}
else
{
Console.WriteLine("Error: Could not find file: {0}", arguments.CollectionFilePath);
Console.WriteLine("Exiting");
throw new ArgumentException();
}
}
return paths;
}
}
}
``` |
9f83f3cf-2ed1-4d84-9093-f2c7a93dd771 | {
"language": "C#"
} | ```c#
@{
var parsedModel = TempData.GetStatusMessageModel();
}
@if (parsedModel != null)
{
<div class="alert alert-@parsedModel.SeverityCSS @(parsedModel.AllowDismiss? "alert-dismissible":"" )" role="alert">
@if (parsedModel.AllowDismiss)
{
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
}
@if (!string.IsNullOrEmpty(parsedModel.Message))
{
@parsedModel.Message
}
@if (!string.IsNullOrEmpty(parsedModel.Html))
{
@Safe.Raw(parsedModel.Html)
}
</div>
}
```
Improve spacing for status messages | ```c#
@{
var parsedModel = TempData.GetStatusMessageModel();
}
@if (parsedModel != null)
{
<div class="alert alert-@parsedModel.SeverityCSS @(parsedModel.AllowDismiss? "alert-dismissible":"" ) mb-5" role="alert">
@if (parsedModel.AllowDismiss)
{
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
}
@if (!string.IsNullOrEmpty(parsedModel.Message))
{
@parsedModel.Message
}
@if (!string.IsNullOrEmpty(parsedModel.Html))
{
@Safe.Raw(parsedModel.Html)
}
</div>
}
``` |
b36f80bb-2ee7-4221-8f42-22bc05802e02 | {
"language": "C#"
} | ```c#
// 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Edit.Timing;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
public class TimelineButton : CompositeDrawable
{
public Action Action;
public readonly BindableBool Enabled = new BindableBool(true);
public IconUsage Icon
{
get => button.Icon;
set => button.Icon = value;
}
private readonly TimelineIconButton button;
public TimelineButton()
{
InternalChild = button = new TimelineIconButton { Action = () => Action?.Invoke() };
button.Enabled.BindTo(Enabled);
Width = button.Width;
}
protected override void Update()
{
base.Update();
button.Size = new Vector2(button.Width, DrawHeight);
}
private class TimelineIconButton : IconButton
{
public TimelineIconButton()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
IconColour = OsuColour.Gray(0.35f);
IconHoverColour = Color4.White;
HoverColour = OsuColour.Gray(0.25f);
FlashColour = OsuColour.Gray(0.5f);
Add(new RepeatingButtonBehaviour(this));
}
protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet);
}
}
}
```
Remove unnecessary nesting of `IconButton` and update design a touch | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
public class TimelineButton : IconButton
{
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
// These are using colourProvider but don't match the design.
// Just something to fit until someone implements the updated design.
IconColour = colourProvider.Background1;
IconHoverColour = colourProvider.Content2;
HoverColour = colourProvider.Background1;
FlashColour = colourProvider.Content2;
Add(new RepeatingButtonBehaviour(this));
}
protected override HoverSounds CreateHoverSounds(HoverSampleSet sampleSet) => new HoverSounds(sampleSet);
}
}
``` |
649992ac-2b47-4e0b-b8c2-26675dcc3d2c | {
"language": "C#"
} | ```c#
<script type="text/javascript">
angular.module("myapp")
.constant("WAIT", @ViewBag.WAIT)
.constant("NAME", @ViewBag.NAME)
;
</script>
```
Fix string injection of NAME from ViewBag to ng.constant | ```c#
<script type="text/javascript">
angular.module("myapp")
.constant("WAIT", @ViewBag.WAIT)
.constant("NAME", '@ViewBag.NAME')
;
</script>
``` |
2fdefa91-873f-492d-9dfa-660bf1ae281f | {
"language": "C#"
} | ```c#
using Glimpse.Web;
using Microsoft.AspNet.Http;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using Microsoft.AspNet.Builder;
namespace Glimpse.Server.Web
{
public class HttpChannelReceiver : IMiddlewareResourceComposer
{
private readonly IServerBroker _messageServerBus;
public HttpChannelReceiver(IServerBroker messageServerBus)
{
_messageServerBus = messageServerBus;
}
public void Register(IApplicationBuilder appBuilder)
{
appBuilder.Map("/agent", chuldApp => chuldApp.Run(async context =>
{
var envelope = ReadMessage(context.Request);
_messageServerBus.SendMessage(envelope);
// TEST CODE ONLY!!!!
var response = context.Response;
response.Headers.Set("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes(envelope.Payload);
await response.Body.WriteAsync(data, 0, data.Length);
// TEST CODE ONLY!!!!
}));
}
private Message ReadMessage(HttpRequest request)
{
var reader = new StreamReader(request.Body);
var text = reader.ReadToEnd();
var message = JsonConvert.DeserializeObject<Message>(text);
return message;
}
}
}```
Simplify the response from the server on the agent-server http channel | ```c#
using Glimpse.Web;
using Microsoft.AspNet.Http;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using Microsoft.AspNet.Builder;
namespace Glimpse.Server.Web
{
public class HttpChannelReceiver : IMiddlewareResourceComposer
{
private readonly IServerBroker _messageServerBus;
public HttpChannelReceiver(IServerBroker messageServerBus)
{
_messageServerBus = messageServerBus;
}
public void Register(IApplicationBuilder appBuilder)
{
appBuilder.Map("/agent", childApp => childApp.Run(async context =>
{
var envelope = ReadMessage(context.Request);
_messageServerBus.SendMessage(envelope);
// TODO: Really should do something better
var response = context.Response;
response.Headers.Set("Content-Type", "text/plain");
var data = Encoding.UTF8.GetBytes("OK");
await response.Body.WriteAsync(data, 0, data.Length);
}));
}
private Message ReadMessage(HttpRequest request)
{
var reader = new StreamReader(request.Body);
var text = reader.ReadToEnd();
var message = JsonConvert.DeserializeObject<Message>(text);
return message;
}
}
}``` |
ef6f81a3-5f3d-414e-8911-1c77dc15aad2 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using Claim = System.Security.Claims.Claim;
using ClaimTypes = System.Security.Claims.ClaimTypes;
namespace Joinrpg.Web.Identity
{
internal static class ClaimInfoBuilder
{
public static IList<Claim> ToClaimsList(this User dbUser)
{
return new List<Claim>
{
new Claim(ClaimTypes.Email, dbUser.Email),
new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()),
new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString())
};
}
}
}
```
Fix problem with missing avatars | ```c#
using System.Collections.Generic;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using Claim = System.Security.Claims.Claim;
using ClaimTypes = System.Security.Claims.ClaimTypes;
namespace Joinrpg.Web.Identity
{
internal static class ClaimInfoBuilder
{
public static IList<Claim> ToClaimsList(this User dbUser)
{
var claimList = new List<Claim>
{
new Claim(ClaimTypes.Email, dbUser.Email),
new Claim(JoinClaimTypes.DisplayName, dbUser.GetDisplayName()),
};
if (dbUser.SelectedAvatarId is not null)
{
//TODO: When we fix all avatars, it will be not required check
claimList.Add(new Claim(JoinClaimTypes.AvatarId, dbUser.SelectedAvatarId?.ToString()));
}
return claimList;
}
}
}
``` |
8207777c-48eb-470f-9759-5fed0ed9746b | {
"language": "C#"
} | ```c#
namespace Nubot.Abstractions
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public abstract class RobotPluginBase : IRobotPlugin
{
protected readonly IRobot Robot;
protected RobotPluginBase(string pluginName, IRobot robot)
{
Name = pluginName;
Robot = robot;
HelpMessages = new List<string>();
}
static RobotPluginBase()
{
ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins");
}
public string Name { get; protected set; }
public static string ExecutingDirectory { get; private set; }
public static string BasePluginsDirectory { get; private set; }
public IEnumerable<string> HelpMessages { get; protected set; }
public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} }
public virtual string MakeConfigFileName()
{
var pluginName = Name.Replace(" ", string.Empty);
//Bug it is not defined that the plugin is from the root folder
var file = string.Format("{0}.config", pluginName);
var configFileName = Path.Combine(BasePluginsDirectory, file);
return configFileName;
}
}
}```
Read plugin settings from BasePluginsDirectory and all sub-directories | ```c#
namespace Nubot.Abstractions
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public abstract class RobotPluginBase : IRobotPlugin
{
protected readonly IRobot Robot;
protected RobotPluginBase(string pluginName, IRobot robot)
{
Name = pluginName;
Robot = robot;
HelpMessages = new List<string>();
}
static RobotPluginBase()
{
ExecutingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
BasePluginsDirectory = Path.Combine(ExecutingDirectory, "plugins");
}
public string Name { get; private set; }
public static string ExecutingDirectory { get; private set; }
public static string BasePluginsDirectory { get; private set; }
public IEnumerable<string> HelpMessages { get; protected set; }
public virtual IEnumerable<IPluginSetting> Settings { get { return Enumerable.Empty<IPluginSetting>();} }
public virtual string MakeConfigFileName()
{
var pluginName = Name.Replace(" ", string.Empty);
var file = string.Format("{0}.config", pluginName);
return Directory.GetFiles(BasePluginsDirectory, file, SearchOption.AllDirectories).FirstOrDefault();
}
}
}``` |
420699e8-adc0-449b-b740-ea7a04a952b2 | {
"language": "C#"
} | ```c#
// 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
{
public class SliderBodyPiece : BlueprintPiece<Slider>
{
private readonly ManualSliderBody body;
public SliderBodyPiece()
{
InternalChild = body = new ManualSliderBody
{
AccentColour = Color4.Transparent
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
body.BorderColour = colours.Yellow;
}
public override void UpdateFrom(Slider hitObject)
{
base.UpdateFrom(hitObject);
body.PathRadius = hitObject.Scale * OsuHitObject.OBJECT_RADIUS;
var vertices = new List<Vector2>();
hitObject.Path.GetPathToProgress(vertices, 0, 1);
body.SetVertices(vertices);
Size = body.Size;
OriginPosition = body.PathOffset;
}
}
}
```
Fix slider selection input handled outside path | ```c#
// 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
{
public class SliderBodyPiece : BlueprintPiece<Slider>
{
private readonly ManualSliderBody body;
public SliderBodyPiece()
{
InternalChild = body = new ManualSliderBody
{
AccentColour = Color4.Transparent
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
body.BorderColour = colours.Yellow;
}
public override void UpdateFrom(Slider hitObject)
{
base.UpdateFrom(hitObject);
body.PathRadius = hitObject.Scale * OsuHitObject.OBJECT_RADIUS;
var vertices = new List<Vector2>();
hitObject.Path.GetPathToProgress(vertices, 0, 1);
body.SetVertices(vertices);
Size = body.Size;
OriginPosition = body.PathOffset;
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => body.ReceivePositionalInputAt(screenSpacePos);
}
}
``` |
56cbf36b-ee81-4f9a-96eb-16ce77115741 | {
"language": "C#"
} | ```c#
using Autofac;
using Autofac.Integration.Owin;
using Bit.Owin.Contracts;
using Bit.Owin.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace Bit.OwinCore.Middlewares
{
public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration
{
public virtual void Configure(IAppBuilder owinApp)
{
owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>();
owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>();
}
}
public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware
{
public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next)
: base(next)
{
}
static AspNetCoreAutofacDependencyInjectionMiddleware()
{
TypeInfo autofacConstantsType = typeof(OwinContextExtensions).GetTypeInfo().Assembly.GetType("Autofac.Integration.Owin.Constants").GetTypeInfo();
FieldInfo owinLifetimeScopeKeyField = autofacConstantsType.GetField("OwinLifetimeScopeKey", BindingFlags.Static | BindingFlags.NonPublic);
if (owinLifetimeScopeKeyField == null)
throw new InvalidOperationException($"OwinLifetimeScopeKey field could not be found in {nameof(OwinContextExtensions)} ");
OwinLifetimeScopeKey = (string)owinLifetimeScopeKeyField.GetValue(null);
}
private static readonly string OwinLifetimeScopeKey;
public override async Task Invoke(IOwinContext context)
{
HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"];
aspNetCoreContext.Items["OwinContext"] = context;
ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>();
context.Set(OwinLifetimeScopeKey, autofacScope);
await Next.Invoke(context);
}
}
}
```
Use newly introduced autofac's SetAutofacLifetimeScope method to pass autofac scope from asp.net core pipeline to owin pipeline | ```c#
using Autofac;
using Autofac.Integration.Owin;
using Bit.Owin.Contracts;
using Bit.Owin.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;
using System.Threading.Tasks;
namespace Bit.OwinCore.Middlewares
{
public class AspNetCoreAutofacDependencyInjectionMiddlewareConfiguration : IOwinMiddlewareConfiguration
{
public virtual void Configure(IAppBuilder owinApp)
{
owinApp.Use<AspNetCoreAutofacDependencyInjectionMiddleware>();
owinApp.Use<AutofacScopeBasedDependencyResolverMiddleware>();
}
}
public class AspNetCoreAutofacDependencyInjectionMiddleware : OwinMiddleware
{
public AspNetCoreAutofacDependencyInjectionMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"];
aspNetCoreContext.Items["OwinContext"] = context;
ILifetimeScope autofacScope = aspNetCoreContext.RequestServices.GetService<ILifetimeScope>();
context.SetAutofacLifetimeScope(autofacScope);
await Next.Invoke(context);
}
}
}
``` |
33dcac39-bbd3-464c-928b-039957cca99e | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons
{
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Seasons;
using System.Collections.Generic;
internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment>
{
internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { }
internal TraktCommentSortOrder? Sorting { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
uriParams.Add("sorting", Sorting.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/{id}/seasons/{season}/comments/{sorting}";
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Fix uri templates in season requests. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Seasons
{
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Seasons;
using System.Collections.Generic;
internal class TraktSeasonCommentsRequest : TraktGetByIdSeasonRequest<TraktPaginationListResult<TraktSeasonComment>, TraktSeasonComment>
{
internal TraktSeasonCommentsRequest(TraktClient client) : base(client) { }
internal TraktCommentSortOrder? Sorting { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
uriParams.Add("sorting", Sorting.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/{id}/seasons/{season}/comments{/sorting}";
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
1bf0d24b-9ce3-4604-8141-0f040e957275 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Immutable;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal sealed class AggregationPhysicalOperatorChooser : BoundTreeRewriter
{
protected override BoundRelation RewriteGroupByAndAggregationRelation(BoundGroupByAndAggregationRelation node)
{
var input = RewriteRelation(node.Input);
var sortedValues = node.Groups.Select(g => new BoundSortedValue(g, Comparer.Default)).ToImmutableArray();
var sortedInput = new BoundSortRelation(input, sortedValues);
return new BoundStreamAggregatesRelation(sortedInput, node.Groups, node.Aggregates);
}
}
}```
Fix bug which causes unnecessary sorts | ```c#
using System;
using System.Collections;
using System.Collections.Immutable;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal sealed class AggregationPhysicalOperatorChooser : BoundTreeRewriter
{
protected override BoundRelation RewriteGroupByAndAggregationRelation(BoundGroupByAndAggregationRelation node)
{
var input = RewriteRelation(node.Input);
var sortedValues = node.Groups.Select(g => new BoundSortedValue(g, Comparer.Default)).ToImmutableArray();
var sortedInput = sortedValues.Any()
? new BoundSortRelation(input, sortedValues)
: input;
return new BoundStreamAggregatesRelation(sortedInput, node.Groups, node.Aggregates);
}
}
}``` |
96432c97-b444-4e19-813f-61935ccf3876 | {
"language": "C#"
} | ```c#
namespace Stripe.Terminal
{
using System;
using Newtonsoft.Json;
public class ReaderListOptions : ListOptions
{
[JsonProperty("location")]
public string Location { get; set; }
[Obsolete("This feature has been deprecated and should not be used moving forward.")]
[JsonProperty("operator_account")]
public string OperatorAccount { get; set; }
}
}
```
Support `Status` filter when listing Terminal `Reader`s | ```c#
namespace Stripe.Terminal
{
using System;
using Newtonsoft.Json;
public class ReaderListOptions : ListOptions
{
/// <summary>
/// A location ID to filter the response list to only readers at the specific location.
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
/// <summary>
/// A status filter to filter readers to only offline or online readers. Possible values
/// are <c>offline</c> and <c>online</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
[Obsolete("This feature has been deprecated and should not be used moving forward.")]
[JsonProperty("operator_account")]
public string OperatorAccount { get; set; }
}
}
``` |
8ac36819-02ee-43e5-9b40-68461af35e72 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Description;
namespace Microsoft.Azure.WebJobs.ServiceBus
{
/// <summary>
/// Setup an 'trigger' on a parameter to listen on events from an event hub.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Binding]
public sealed class EventHubTriggerAttribute : Attribute
{
/// <summary>
/// Create an instance of this attribute.
/// </summary>
/// <param name="eventHubName">Event hub to listen on for messages. </param>
public EventHubTriggerAttribute(string eventHubName)
{
this.EventHubName = eventHubName;
}
/// <summary>
/// Name of the event hub.
/// </summary>
public string EventHubName { get; private set; }
/// <summary>
/// Optional Name of the consumer group. If missing, then use the default name, "$Default"
/// </summary>
public string ConsumerGroup { get; set; }
}
}```
Add event hub connection property | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Description;
namespace Microsoft.Azure.WebJobs.ServiceBus
{
/// <summary>
/// Setup an 'trigger' on a parameter to listen on events from an event hub.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Binding]
public sealed class EventHubTriggerAttribute : Attribute
{
/// <summary>
/// Create an instance of this attribute.
/// </summary>
/// <param name="eventHubName">Event hub to listen on for messages. </param>
public EventHubTriggerAttribute(string eventHubName)
{
this.EventHubName = eventHubName;
}
/// <summary>
/// Name of the event hub.
/// </summary>
public string EventHubName { get; private set; }
/// <summary>
/// Optional Name of the consumer group. If missing, then use the default name, "$Default"
/// </summary>
public string ConsumerGroup { get; set; }
/// <summary>
/// Optional connection name. If missing, tries to use a registered event hub receiver.
/// </summary>
public string Connection { get; set; }
}
}``` |
db5c84bf-c1dc-459c-a78b-056fae5318b9 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using BookSleeve;
using SignalR;
namespace Compilify.Web.EndPoints
{
public class ExecuteEndPoint : PersistentConnection
{
/// <summary>
/// Handle messages sent by the client.</summary>
protected override Task OnReceivedAsync(string connectionId, string data)
{
var redis = DependencyResolver.Current.GetService<RedisConnection>();
var command = new ExecuteCommand
{
ClientId = connectionId,
Code = data
};
var message = Convert.ToBase64String(command.GetBytes());
redis.Lists.AddLast(0, "queue:execute", message);
return Send(new { status = "ok" });
}
}
}```
Throw an exception if the Redis connection is not open | ```c#
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using BookSleeve;
using SignalR;
namespace Compilify.Web.EndPoints
{
public class ExecuteEndPoint : PersistentConnection
{
/// <summary>
/// Handle messages sent by the client.</summary>
protected override Task OnReceivedAsync(string connectionId, string data)
{
var redis = DependencyResolver.Current.GetService<RedisConnection>();
if (redis.State != RedisConnectionBase.ConnectionState.Open)
{
throw new InvalidOperationException("RedisConnection state is " + redis.State);
}
var command = new ExecuteCommand
{
ClientId = connectionId,
Code = data
};
var message = Convert.ToBase64String(command.GetBytes());
redis.Lists.AddLast(0, "queue:execute", message);
return Send(new { status = "ok" });
}
}
}``` |
c61f8700-cf5b-4823-8bd6-c10d7a19e9ef | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.Windows.Input;
using Norma.Models;
using Norma.ViewModels.Internal;
using Prism.Commands;
namespace Norma.ViewModels
{
internal class LibraryViewModel : ViewModel
{
private readonly Library _library;
public string Name => _library.Name;
public string Url => _library.Url;
public string License => _library.License;
public LibraryViewModel(Library library)
{
_library = library;
}
#region OpenHyperlinkCommand
private ICommand _openHyperlinkCommand;
public ICommand OpenHyperlinkCommand =>
_openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink));
private void OpenHyperlink() => Process.Start(Url);
#endregion
}
}```
Remove protocol from licenses view. | ```c#
using System.Diagnostics;
using System.Windows.Input;
using Norma.Models;
using Norma.ViewModels.Internal;
using Prism.Commands;
namespace Norma.ViewModels
{
internal class LibraryViewModel : ViewModel
{
private readonly Library _library;
public string Name => _library.Name;
public string Url => _library.Url.Replace("https://", "").Replace("http://", "");
public string License => _library.License;
public LibraryViewModel(Library library)
{
_library = library;
}
#region OpenHyperlinkCommand
private ICommand _openHyperlinkCommand;
public ICommand OpenHyperlinkCommand =>
_openHyperlinkCommand ?? (_openHyperlinkCommand = new DelegateCommand(OpenHyperlink));
private void OpenHyperlink() => Process.Start(_library.Url);
#endregion
}
}``` |
fd2195c2-ff8d-45d4-9078-4c84c4e1e6ab | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
namespace CoffeeFilter.UITests.Shared
{
public static class UITestsHelpers
{
public static string XTCApiKey {
get;
} = "024b0d715a7e9c22388450cf0069cb19";
public static TestType SelectedTest { get; set; }
public enum TestType
{
NoConnection,
ParseError,
OpenCoffee,
ClosedCoffee,
NoLocations,
UserMoved
}
}
public static class TestTypeExtensions
{
public static string ToFriendlyString(this UITestsHelpers.TestType me)
{
switch(me)
{
case UITestsHelpers.TestType.NoConnection:
return "No Internet Connection";
case UITestsHelpers.TestType.ParseError:
return "Parse Error";
case UITestsHelpers.TestType.OpenCoffee:
return "Open Coffee Locations";
case UITestsHelpers.TestType.ClosedCoffee:
return "Closed Coffee Locations";
case UITestsHelpers.TestType.NoLocations:
return "No Locations Around";
case UITestsHelpers.TestType.UserMoved:
return "User Moved and Refreshed";
}
return string.Empty;
}
}
}
```
Set OpenCoffee as default test type | ```c#
using System;
using System.ComponentModel;
namespace CoffeeFilter.UITests.Shared
{
public static class UITestsHelpers
{
public static string XTCApiKey {
get;
} = "024b0d715a7e9c22388450cf0069cb19";
public static TestType SelectedTest { get; set; }
public enum TestType
{
OpenCoffee = 0,
NoConnection,
ParseError,
ClosedCoffee,
NoLocations,
UserMoved
}
}
public static class TestTypeExtensions
{
public static string ToFriendlyString(this UITestsHelpers.TestType me)
{
switch(me)
{
case UITestsHelpers.TestType.NoConnection:
return "No Internet Connection";
case UITestsHelpers.TestType.ParseError:
return "Parse Error";
case UITestsHelpers.TestType.OpenCoffee:
return "Open Coffee Locations";
case UITestsHelpers.TestType.ClosedCoffee:
return "Closed Coffee Locations";
case UITestsHelpers.TestType.NoLocations:
return "No Locations Around";
case UITestsHelpers.TestType.UserMoved:
return "User Moved and Refreshed";
}
return string.Empty;
}
}
}
``` |
5f780348-3505-4fbb-9f82-397d3b07fec9 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using CompaniesHouse.Response.Document;
using CompaniesHouse.UriBuilders;
using FluentAssertions;
using Moq;
using NUnit.Framework;
namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests
{
[TestFixture]
public class CompaniesHouseDocumentClientTests
{
private CompaniesHouseClientResponse<DocumentDownload> _result;
private const string ExpectedMediaType = "application/pdf";
private const string ExpectedContent = "test pdf";
private const string DocumentId = "wibble";
[SetUp]
public async Task GivenAClient_WhenDownloadingDocument()
{
var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content");
var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType);
var mockUriBuilder = new Mock<IDocumentUriBuilder>();
mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object);
mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString());
_result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId);
}
[Test]
public void ThenDocumentContentIsCorrect()
{
var memoryStream = new MemoryStream();
_result.Data.Content.CopyToAsync(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent);
}
}
}
```
Add using when creating a memorystream | ```c#
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using CompaniesHouse.Response.Document;
using CompaniesHouse.UriBuilders;
using FluentAssertions;
using Moq;
using NUnit.Framework;
namespace CompaniesHouse.Tests.CompaniesHouseDocumentClientTests
{
[TestFixture]
public class CompaniesHouseDocumentClientTests
{
private CompaniesHouseClientResponse<DocumentDownload> _result;
private const string ExpectedMediaType = "application/pdf";
private const string ExpectedContent = "test pdf";
private const string DocumentId = "wibble";
[SetUp]
public async Task GivenAClient_WhenDownloadingDocument()
{
var requestUri = new Uri($"https://document-api.companieshouse.gov.uk/document/{DocumentId}/content");
var stubHttpMessageHandler = new StubHttpMessageHandler(requestUri, ExpectedContent, ExpectedMediaType);
var mockUriBuilder = new Mock<IDocumentUriBuilder>();
mockUriBuilder.Setup(x => x.WithContent()).Returns(mockUriBuilder.Object);
mockUriBuilder.Setup(x => x.Build(DocumentId)).Returns(requestUri.ToString());
_result = await new CompaniesHouseDocumentClient(new HttpClient(stubHttpMessageHandler), mockUriBuilder.Object).DownloadDocumentAsync(DocumentId);
}
[Test]
public void ThenDocumentContentIsCorrect()
{
using var memoryStream = new MemoryStream();
_result.Data.Content.CopyToAsync(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
new StreamReader(memoryStream).ReadToEnd().Should().Be(ExpectedContent);
}
}
}
``` |
f845685b-911e-42ac-9d98-e2c3412c5248 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
using Klawr.ClrHost.Managed;
using Klawr.ClrHost.Interfaces;
using Klawr.ClrHost.Managed.SafeHandles;
namespace Klawr.UnrealEngine
{
public class TestActor : AActorScriptObject
{
public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject)
{
Console.WriteLine("TestActor()");
}
public override void BeginPlay()
{
Console.WriteLine("BeginPlay()");
var world = K2_GetWorld();
var worldClass = UWorld.StaticClass();
bool isWorldClass = world.IsA(worldClass);
var anotherWorldClass = (UClass)typeof(UWorld);
bool isSameClass = worldClass == anotherWorldClass;
bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass());
world.Dispose();
}
public override void Tick(float deltaTime)
{
Console.WriteLine("Tick()");
}
public override void Destroy()
{
Console.WriteLine("Destroy()");
}
}
}
```
Comment out some test code that no longer works due to API changes in UE | ```c#
using System;
using System.Runtime.InteropServices;
using Klawr.ClrHost.Managed;
using Klawr.ClrHost.Interfaces;
using Klawr.ClrHost.Managed.SafeHandles;
namespace Klawr.UnrealEngine
{
// NOTE: IScriptObject should probably be considered deprecated in favor of UKlawrScriptComponent
public class TestActor : AActorScriptObject
{
public TestActor(long instanceID, UObjectHandle nativeObject) : base(instanceID, nativeObject)
{
Console.WriteLine("TestActor()");
}
public override void BeginPlay()
{
Console.WriteLine("BeginPlay()");
// FIXME: AActor::K2_GetWorld() is no more, and AActor::GetWorld() is not exposed to
// Blueprints at all... may need to expose UObject::GetWorld() manually.
/*
var world = K2_GetWorld();
var worldClass = UWorld.StaticClass();
bool isWorldClass = world.IsA(worldClass);
var anotherWorldClass = (UClass)typeof(UWorld);
bool isSameClass = worldClass == anotherWorldClass;
bool isWorldClassDerivedFromObjectClass = worldClass.IsChildOf(UObject.StaticClass());
world.Dispose();
*/
}
public override void Tick(float deltaTime)
{
Console.WriteLine("Tick()");
}
public override void Destroy()
{
Console.WriteLine("Destroy()");
}
}
}
``` |
9ec60a2b-3572-4c03-a653-6ef438534b1e | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="BeCompletedTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace FluentSample.Test.Unit
{
using System;
using System.Threading.Tasks;
using FluentAssertions;
using FluentSample;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class BeCompletedTest
{
[TestMethod]
public void CompletedTaskShouldPassBeCompleted()
{
Task task = Task.FromResult(false);
Action act = () => task.Should().BeCompleted();
act.ShouldNotThrow();
}
[TestMethod]
public void PendingTaskShouldFailBeCompleted()
{
Task task = new TaskCompletionSource<bool>().Task;
Action act = () => task.Should().BeCompleted();
act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was WaitingForActivation.");
}
[TestMethod]
public void NullTaskShouldFailBeCompleted()
{
Task task = null;
Action act = () => task.Should().BeCompleted();
act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was <null>.");
}
[TestMethod]
public void FaultedTaskShouldPassBeCompleted()
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
tcs.SetException(new InvalidCastException("Expected failure."));
Task task = tcs.Task;
Action act = () => task.Should().BeCompleted();
act.ShouldNotThrow();
}
}
}
```
Rename tests after file rename | ```c#
//-----------------------------------------------------------------------
// <copyright file="BeCompletedTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace FluentSample.Test.Unit
{
using System;
using System.Threading.Tasks;
using FluentAssertions;
using FluentSample;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class BeCompletedTest
{
[TestMethod]
public void CompletedTaskShouldPass()
{
Task task = Task.FromResult(false);
Action act = () => task.Should().BeCompleted();
act.ShouldNotThrow();
}
[TestMethod]
public void PendingTaskShouldFail()
{
Task task = new TaskCompletionSource<bool>().Task;
Action act = () => task.Should().BeCompleted();
act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was WaitingForActivation.");
}
[TestMethod]
public void NullTaskShouldFail()
{
Task task = null;
Action act = () => task.Should().BeCompleted();
act.ShouldThrow<AssertFailedException>().WithMessage("Expected task to be completed but was <null>.");
}
[TestMethod]
public void FaultedTaskShouldPass()
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
tcs.SetException(new InvalidCastException("Expected failure."));
Task task = tcs.Task;
Action act = () => task.Should().BeCompleted();
act.ShouldNotThrow();
}
}
}
``` |
adfcb5b7-556d-4fb9-8fbf-cd5b015beb06 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
using Markdig;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
public class ResolveLinkExtension : IMarkdownExtension
{
private readonly MarkdownContext _context;
public ResolveLinkExtension(MarkdownContext context)
{
_context = context;
}
public void Setup(MarkdownPipelineBuilder pipeline)
{
pipeline.DocumentProcessed += UpdateLinks;
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
}
private void UpdateLinks(MarkdownObject markdownObject)
{
switch (markdownObject)
{
case TabTitleBlock _:
break;
case LinkInline linkInline:
linkInline.Url = _context.GetLink(linkInline.Url, linkInline);
break;
case ContainerBlock containerBlock:
foreach (var subBlock in containerBlock)
{
UpdateLinks(subBlock);
}
break;
case LeafBlock leafBlock when leafBlock.Inline != null:
foreach (var subInline in leafBlock.Inline)
{
UpdateLinks(subInline);
}
break;
case ContainerInline containerInline:
foreach (var subInline in containerInline)
{
UpdateLinks(subInline);
}
break;
default:
break;
}
}
}
}
```
Fix link resolve not resolving child token | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
using Markdig;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
public class ResolveLinkExtension : IMarkdownExtension
{
private readonly MarkdownContext _context;
public ResolveLinkExtension(MarkdownContext context)
{
_context = context;
}
public void Setup(MarkdownPipelineBuilder pipeline)
{
pipeline.DocumentProcessed += UpdateLinks;
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
}
private void UpdateLinks(MarkdownObject markdownObject)
{
switch (markdownObject)
{
case TabTitleBlock _:
break;
case LinkInline linkInline:
linkInline.Url = _context.GetLink(linkInline.Url, linkInline);
foreach (var subBlock in linkInline)
{
UpdateLinks(subBlock);
}
break;
case ContainerBlock containerBlock:
foreach (var subBlock in containerBlock)
{
UpdateLinks(subBlock);
}
break;
case LeafBlock leafBlock when leafBlock.Inline != null:
foreach (var subInline in leafBlock.Inline)
{
UpdateLinks(subInline);
}
break;
case ContainerInline containerInline:
foreach (var subInline in containerInline)
{
UpdateLinks(subInline);
}
break;
default:
break;
}
}
}
}
``` |
88e67a15-6366-4ab2-a538-c356acf36953 | {
"language": "C#"
} | ```c#
using System;
using Orchard.Environment;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.Localization;
using Orchard.Packaging.Services;
using Orchard.UI.Notify;
namespace Orchard.Packaging {
[OrchardFeature("Gallery")]
public class DefaultPackagingUpdater : IFeatureEventHandler {
private readonly IPackagingSourceManager _packagingSourceManager;
private readonly INotifier _notifier;
public DefaultPackagingUpdater(IPackagingSourceManager packagingSourceManager, INotifier notifier) {
_packagingSourceManager = packagingSourceManager;
_notifier = notifier;
}
public Localizer T { get; set; }
public void Install(Feature feature) {
_packagingSourceManager.AddSource(new PackagingSource { Id = Guid.NewGuid(), FeedTitle = "Orchard Module Gallery", FeedUrl = "http://orchardproject.net/gallery/feed" });
}
public void Enable(Feature feature) {
}
public void Disable(Feature feature) {
}
public void Uninstall(Feature feature) {
}
}
}```
Change the feed url to the new url for 0.8 | ```c#
using System;
using Orchard.Environment;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.Localization;
using Orchard.Packaging.Services;
using Orchard.UI.Notify;
namespace Orchard.Packaging {
[OrchardFeature("Gallery")]
public class DefaultPackagingUpdater : IFeatureEventHandler {
private readonly IPackagingSourceManager _packagingSourceManager;
private readonly INotifier _notifier;
public DefaultPackagingUpdater(IPackagingSourceManager packagingSourceManager, INotifier notifier) {
_packagingSourceManager = packagingSourceManager;
_notifier = notifier;
}
public Localizer T { get; set; }
public void Install(Feature feature) {
_packagingSourceManager.AddSource(new PackagingSource { Id = Guid.NewGuid(), FeedTitle = "Orchard Module Gallery", FeedUrl = "http://orchardproject.net/gallery08/feed" });
}
public void Enable(Feature feature) {
}
public void Disable(Feature feature) {
}
public void Uninstall(Feature feature) {
}
}
}``` |
24dcaafa-abc3-45c6-8daf-d81bf46ebe5a | {
"language": "C#"
} | ```c#
using MarkdownLog;
using NBi.Core.ResultSet;
using NBi.Core.ResultSet.Lookup;
using NBi.Core.ResultSet.Lookup.Violation;
using NBi.Framework.FailureMessage.Common;
using NBi.Framework.FailureMessage.Common.Helper;
using NBi.Framework.FailureMessage.Markdown.Helper;
using NBi.Framework.Sampling;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Framework.FailureMessage.Markdown
{
class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown
{
public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers)
: base(samplers) { }
protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container)
{
container.Append("Analysis".ToMarkdownHeader());
var state = violations.Values.Select(x => x.State).First();
container.Append(GetExplanationText(violations, state).ToMarkdownParagraph());
var rows = violations.Values.Where(x => x is LookupExistsViolationInformation)
.Cast<LookupExistsViolationInformation>()
.SelectMany(x => x.CandidateRows);
sampler.Build(rows);
var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler);
tableHelper.Render(container);
}
}
}
```
Fix issue when the error messages are rendered in Markdown with an Always configuration | ```c#
using MarkdownLog;
using NBi.Core.ResultSet;
using NBi.Core.ResultSet.Lookup;
using NBi.Core.ResultSet.Lookup.Violation;
using NBi.Framework.FailureMessage.Common;
using NBi.Framework.FailureMessage.Common.Helper;
using NBi.Framework.FailureMessage.Markdown.Helper;
using NBi.Framework.Sampling;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Framework.FailureMessage.Markdown
{
class LookupExistsViolationMessageMarkdown : LookupViolationMessageMarkdown
{
public LookupExistsViolationMessageMarkdown(IDictionary<string, ISampler<DataRow>> samplers)
: base(samplers) { }
protected override void RenderAnalysis(LookupViolationCollection violations, IEnumerable<ColumnMetadata> metadata, ISampler<DataRow> sampler, ColumnMappingCollection keyMappings, ColumnMappingCollection valueMappings, MarkdownContainer container)
{
if (violations.Values.Any())
{
container.Append("Analysis".ToMarkdownHeader());
var state = violations.Values.Select(x => x.State).First();
container.Append(GetExplanationText(violations, state).ToMarkdownParagraph());
var rows = violations.Values.Where(x => x is LookupExistsViolationInformation)
.Cast<LookupExistsViolationInformation>()
.SelectMany(x => x.CandidateRows);
sampler.Build(rows);
var tableHelper = new StandardTableHelperMarkdown(rows, metadata, sampler);
tableHelper.Render(container);
}
}
}
}
``` |
2f075680-7ad0-4a37-8b5c-5e79f8c675dd | {
"language": "C#"
} | ```c#
using System;
namespace Urho {
public partial class BillboardSet
{
public BillboardWrapper GetBillboardSafe (uint index)
{
unsafe {
Billboard* result = BillboardSet_GetBillboard (handle, index);
if (result == null)
return null;
return new BillboardWrapper(result);
}
}
}
}
```
Fix BillboardWrapper, prevent bb from collecting by GC | ```c#
using System;
namespace Urho {
public partial class BillboardSet
{
public BillboardWrapper GetBillboardSafe (uint index)
{
unsafe {
Billboard* result = BillboardSet_GetBillboard (handle, index);
if (result == null)
return null;
return new BillboardWrapper(this, result);
}
}
}
}
``` |
c7329c3d-5603-450a-8d83-a52e088cc18a | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
new MvcRouteHandler());
}
}
}
```
Add new private field for the route handler | ```c#
using System.Web.Mvc;
using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
private readonly IRouteHandler _routeHandler;
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
new MvcRouteHandler());
}
}
}
``` |
134a7eb5-c1dd-4c34-961f-05b88799ec9e | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Contentful.Core.Models.Management
{
/// <summary>
/// Encapsulates information about a Contentful Ui Extension
/// </summary>
public class UiExtension : IContentfulResource
{
/// <summary>
/// Common system managed metadata properties.
/// </summary>
[JsonProperty("sys")]
public SystemProperties SystemProperties { get; set; }
/// <summary>
/// The source URL for html file for the extension.
/// </summary>
public string Src { get; set; }
/// <summary>
/// String representation of the widget, e.g. inline HTML.
/// </summary>
public string SrcDoc { get; set; }
/// <summary>
/// The name of the extension
/// </summary>
public string Name { get; set; }
/// <summary>
/// The field types for which this extension applies.
/// </summary>
public List<string> FieldTypes { get; set; }
/// <summary>
/// Whether or not this is an extension for the Contentful sidebar.
/// </summary>
public bool Sidebar { get; set; }
}
}
```
Add jsonconverter to extension model | ```c#
using Contentful.Core.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Contentful.Core.Models.Management
{
/// <summary>
/// Encapsulates information about a Contentful Ui Extension
/// </summary>
[JsonConverter(typeof(ExtensionJsonConverter))]
public class UiExtension : IContentfulResource
{
/// <summary>
/// Common system managed metadata properties.
/// </summary>
[JsonProperty("sys")]
public SystemProperties SystemProperties { get; set; }
/// <summary>
/// The source URL for html file for the extension.
/// </summary>
public string Src { get; set; }
/// <summary>
/// String representation of the widget, e.g. inline HTML.
/// </summary>
public string SrcDoc { get; set; }
/// <summary>
/// The name of the extension
/// </summary>
public string Name { get; set; }
/// <summary>
/// The field types for which this extension applies.
/// </summary>
public List<string> FieldTypes { get; set; }
/// <summary>
/// Whether or not this is an extension for the Contentful sidebar.
/// </summary>
public bool Sidebar { get; set; }
}
}
``` |
b49b9dcf-42bb-479b-a950-110b0710b364 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#elif (XAMARIN)
using Xamarin.Forms;
#endif
namespace ValueConverters
{
/// <summary>
/// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3
/// The output of converter N becomes the input of converter N+1.
/// </summary>
#if (NETFX || XAMARIN || WINDOWS_PHONE)
[ContentProperty(nameof(Converters))]
#elif (NETFX_CORE)
[ContentProperty(Name = nameof(Converters))]
#endif
public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup>
{
public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>();
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
}
}
```
Add missing namespace for uwp | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
#elif (XAMARIN)
using Xamarin.Forms;
#endif
namespace ValueConverters
{
/// <summary>
/// Value converters which aggregates the results of a sequence of converters: Converter1 >> Converter2 >> Converter3
/// The output of converter N becomes the input of converter N+1.
/// </summary>
#if (NETFX || XAMARIN || WINDOWS_PHONE)
[ContentProperty(nameof(Converters))]
#elif (NETFX_CORE)
[ContentProperty(Name = nameof(Converters))]
#endif
public class ValueConverterGroup : SingletonConverterBase<ValueConverterGroup>
{
public List<IValueConverter> Converters { get; set; } = new List<IValueConverter>();
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.Converters?.Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.Converters?.Reverse<IValueConverter>().Aggregate(value, (current, converter) => converter.Convert(current, targetType, parameter, culture));
}
}
}
``` |
352fb419-265e-4bf3-a8c3-9bee550dac6a | {
"language": "C#"
} | ```c#
using System.IO;
using System.Web;
namespace Bundlr
{
public class TemplateSource : IContentSource
{
private readonly string global;
private readonly Compiler compiler;
private readonly TemplateFinder finder;
public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
{
this.global = global;
this.compiler = compiler;
this.finder = finder;
}
public string GetContent(HttpContextBase httpContext)
{
var templates = finder.Find(httpContext);
using (var writer = new StringWriter())
{
writer.WriteLine("!function() {");
writer.WriteLine(" var templates = {0}.templates = {{}};", global);
foreach (var template in templates)
{
string name = template.GetName();
string content = compiler.Compile(template.GetContent());
writer.WriteLine(" templates['{0}'] = {1};", name, content);
}
writer.WriteLine("}();");
return writer.ToString();
}
}
}
}```
Add parallelism when compiling templates. | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Bundlr
{
public class TemplateSource : IContentSource
{
private readonly string global;
private readonly Compiler compiler;
private readonly TemplateFinder finder;
public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
{
this.global = global;
this.compiler = compiler;
this.finder = finder;
}
public string GetContent(HttpContextBase httpContext)
{
var templates = finder.Find(httpContext);
using (var writer = new StringWriter())
{
writer.WriteLine("!function() {");
writer.WriteLine(" var templates = {0}.templates = {{}};", global);
var results = Compile(templates);
foreach (var result in results)
{
writer.WriteLine(result);
}
writer.WriteLine("}();");
return writer.ToString();
}
}
private IEnumerable<string> Compile(IEnumerable<Template> templates)
{
return templates.AsParallel().Select(template =>
{
string name = template.GetName();
string content = compiler.Compile(template.GetContent());
return string.Format(" templates['{0}'] = {1};", name, content);
});
}
}
}``` |
3e40a5c8-e6c4-46ac-b8ca-78d2fab523bb | {
"language": "C#"
} | ```c#
using Mindscape.Raygun4Net.Utils;
namespace Mindscape.Raygun4Net.Logging
{
public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger
{
public RaygunLogLevel LogLevel { get; set; }
public void Error(string message)
{
Log(RaygunLogLevel.Error, message);
}
public void Warning(string message)
{
Log(RaygunLogLevel.Warning, message);
}
public void Info(string message)
{
Log(RaygunLogLevel.Info, message);
}
public void Debug(string message)
{
Log(RaygunLogLevel.Debug, message);
}
public void Verbose(string message)
{
Log(RaygunLogLevel.Verbose, message);
}
private void Log(RaygunLogLevel level, string message)
{
if (LogLevel == RaygunLogLevel.None)
{
return;
}
if (level <= LogLevel)
{
System.Diagnostics.Trace.WriteLine(message);
}
}
}
}```
Add a prefix to each log | ```c#
using Mindscape.Raygun4Net.Utils;
namespace Mindscape.Raygun4Net.Logging
{
public class RaygunLogger : Singleton<RaygunLogger>, IRaygunLogger
{
private const string RaygunPrefix = "Raygun: ";
public RaygunLogLevel LogLevel { get; set; }
public void Error(string message)
{
Log(RaygunLogLevel.Error, message);
}
public void Warning(string message)
{
Log(RaygunLogLevel.Warning, message);
}
public void Info(string message)
{
Log(RaygunLogLevel.Info, message);
}
public void Debug(string message)
{
Log(RaygunLogLevel.Debug, message);
}
public void Verbose(string message)
{
Log(RaygunLogLevel.Verbose, message);
}
private void Log(RaygunLogLevel level, string message)
{
if (LogLevel == RaygunLogLevel.None)
{
return;
}
if (level <= LogLevel)
{
System.Diagnostics.Trace.WriteLine($"{RaygunPrefix}{message}");
}
}
}
}``` |
f1268545-e4a1-44bd-a60e-5508680d7fd7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace MultiMiner.Utility.Networking
{
public class PortScanner
{
public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100)
{
if (startingPort >= endingPort)
throw new ArgumentException();
List<IPEndPoint> endpoints = new List<IPEndPoint>();
IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses();
foreach (IPAddress ipAddress in ipAddresses)
for (int currentPort = startingPort; currentPort <= endingPort; currentPort++)
if (IsPortOpen(ipAddress, currentPort, connectTimeout))
endpoints.Add(new IPEndPoint(ipAddress, currentPort));
return endpoints;
}
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
{
bool portIsOpen = false;
using (var tcp = new TcpClient())
{
IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null);
using (ar.AsyncWaitHandle)
{
//Wait connectTimeout ms for connection.
if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
{
try
{
tcp.EndConnect(ar);
portIsOpen = true;
//Connect was successful.
}
catch
{
//Server refused the connection.
}
}
}
}
return portIsOpen;
}
}
}
```
Use Socket instead of TcpClient for port scanning Works around ObjectDisposedException on Linux + Mono | ```c#
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace MultiMiner.Utility.Networking
{
public class PortScanner
{
public static List<IPEndPoint> Find(string ipRange, int startingPort, int endingPort, int connectTimeout = 100)
{
if (startingPort >= endingPort)
throw new ArgumentException();
List<IPEndPoint> endpoints = new List<IPEndPoint>();
IEnumerable<IPAddress> ipAddresses = new IPRange(ipRange).GetIPAddresses();
foreach (IPAddress ipAddress in ipAddresses)
for (int currentPort = startingPort; currentPort <= endingPort; currentPort++)
if (IsPortOpen(ipAddress, currentPort, connectTimeout))
endpoints.Add(new IPEndPoint(ipAddress, currentPort));
return endpoints;
}
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
{
bool portIsOpen = false;
//use raw Sockets
//using TclClient along with IAsyncResult can lead to ObjectDisposedException on Linux+Mono
Socket socket = null;
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);
IAsyncResult result = socket.BeginConnect(ipAddress.ToString(), currentPort, null, null);
result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(connectTimeout), true);
portIsOpen = socket.Connected;
}
catch
{
}
finally
{
if (socket != null)
socket.Close();
}
return portIsOpen;
}
}
}
``` |
d71eb472-b406-482d-b719-d70bc5b5da95 | {
"language": "C#"
} | ```c#
namespace TestAppUWP.Samples.Map
{
public class MapServiceSettings
{
public static string Token = string.Empty;
}
}```
Add multiple bing maps keys | ```c#
namespace TestAppUWP.Samples.Map
{
public class MapServiceSettings
{
public const string TokenUwp1 = "TokenUwp1";
public const string TokenUwp2 = "TokenUwp2";
public static string SelectedToken = TokenUwp1;
}
}``` |
18057974-8935-40af-b315-d0053c65d7a8 | {
"language": "C#"
} | ```c#
using Microsoft.Speech.Recognition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lex4all
{
public static class EngineControl
{
/// <summary>
/// creates engine and sets properties
/// </summary>
/// <returns>
/// the engine used for recognition
/// </returns>
public static SpeechRecognitionEngine getEngine () {
Console.WriteLine("Building recognition engine");
SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
// set confidence threshold(s)
sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0);
// add event handlers
sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
Console.WriteLine("Done.");
return sre;
}
/// <summary>
/// handles the speech recognized event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Console.WriteLine("Recognized text: " + e.Result.Text);
}
}
}
```
Change recognized event handler for eval | ```c#
using Microsoft.Speech.Recognition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lex4all
{
public static class EngineControl
{
/// <summary>
/// creates engine and sets properties
/// </summary>
/// <returns>
/// the engine used for recognition
/// </returns>
public static SpeechRecognitionEngine getEngine () {
Console.WriteLine("Building recognition engine");
SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
// set confidence threshold(s)
sre.UpdateRecognizerSetting("CFGConfidenceRejectionThreshold", 0);
// add event handlers
sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
Console.WriteLine("Done.");
return sre;
}
/// <summary>
/// handles the speech recognized event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
//Console.WriteLine("Recognized text: " + e.Result.Text);
}
}
}
``` |
c574337b-05ef-420d-9d36-7b6c237486c8 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("autocomplete")]
public async Task<IActionResult> AutoComplete([FromBody]Request request)
{
_workspace.EnsureBufferUpdated(request);
var completions = Enumerable.Empty<AutoCompleteResponse>();
var document = _workspace.GetDocument(request.FileName);
if (document != null)
{
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
var model = await document.GetSemanticModelAsync();
var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace);
completions = symbols.Select(MakeAutoCompleteResponse);
}
else
{
return new HttpNotFoundResult();
}
return new ObjectResult(completions);
}
private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol)
{
var response = new AutoCompleteResponse();
response.CompletionText = symbol.Name;
// TODO: Do something more intelligent here
response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
response.Description = symbol.GetDocumentationCommentXml();
return response;
}
}
}```
Return completions from all documents | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("autocomplete")]
public async Task<IActionResult> AutoComplete([FromBody]Request request)
{
_workspace.EnsureBufferUpdated(request);
var completions = new List<AutoCompleteResponse>();
var documents = _workspace.GetDocuments(request.FileName);
foreach (var document in documents)
{
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
var model = await document.GetSemanticModelAsync();
var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, _workspace);
completions.AddRange(symbols.Select(MakeAutoCompleteResponse));
}
return new ObjectResult(completions);
}
private AutoCompleteResponse MakeAutoCompleteResponse(ISymbol symbol)
{
var response = new AutoCompleteResponse();
response.CompletionText = symbol.Name;
// TODO: Do something more intelligent here
response.DisplayText = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
response.Description = symbol.GetDocumentationCommentXml();
return response;
}
}
}``` |
b94b7985-77bf-43b0-a621-3f043c233a53 | {
"language": "C#"
} | ```c#
using InfinniPlatform.Http;
using InfinniPlatform.IoC;
namespace InfinniPlatform.Auth.HttpService.IoC
{
public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser
{
public void Load(IContainerBuilder builder)
{
builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser)))
.As<IHttpService>()
.SingleInstance();
builder.RegisterType<UserEventHandlerInvoker>()
.AsSelf()
.SingleInstance();
}
}
}```
Fix auth http services registration | ```c#
using InfinniPlatform.Http;
using InfinniPlatform.IoC;
namespace InfinniPlatform.Auth.HttpService.IoC
{
public class AuthHttpServiceContainerModule<TUser> : IContainerModule where TUser : AppUser
{
public void Load(IContainerBuilder builder)
{
builder.RegisterType(typeof(AuthInternalHttpService<>).MakeGenericType(typeof(TUser)))
.As<IHttpService>()
.SingleInstance();
builder.RegisterType(typeof(AuthExternalHttpService<>).MakeGenericType(typeof(TUser)))
.As<IHttpService>()
.SingleInstance();
builder.RegisterType(typeof(AuthManagementHttpService<>).MakeGenericType(typeof(TUser)))
.As<IHttpService>()
.SingleInstance();
builder.RegisterType<UserEventHandlerInvoker>()
.AsSelf()
.SingleInstance();
}
}
}``` |
3d30526e-43ff-4e16-b13c-f3a944ff6930 | {
"language": "C#"
} | ```c#
// 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.Containers;
using osu.Game.Overlays.Toolbar;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using System.Linq;
using osu.Framework.MathUtils;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneToolbarRulesetSelector : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ToolbarRulesetSelector),
typeof(ToolbarRulesetTabButton),
};
public TestSceneToolbarRulesetSelector()
{
ToolbarRulesetSelector selector;
Add(new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.X,
Height = Toolbar.HEIGHT,
Child = selector = new ToolbarRulesetSelector()
});
AddStep("Select random", () =>
{
selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count()));
});
}
}
}
```
Make testcase even more useful | ```c#
// 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.Containers;
using osu.Game.Overlays.Toolbar;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using System.Linq;
using osu.Framework.MathUtils;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneToolbarRulesetSelector : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ToolbarRulesetSelector),
typeof(ToolbarRulesetTabButton),
};
public TestSceneToolbarRulesetSelector()
{
ToolbarRulesetSelector selector;
Add(new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.X,
Height = Toolbar.HEIGHT,
Child = selector = new ToolbarRulesetSelector()
});
AddStep("Select random", () =>
{
selector.Current.Value = selector.Items.ElementAt(RNG.Next(selector.Items.Count()));
});
AddStep("Toggle disabled state", () => selector.Current.Disabled = !selector.Current.Disabled);
}
}
}
``` |
633fc5e7-ad54-4d42-8aab-6689a3d87595 | {
"language": "C#"
} | ```c#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RockLib.Logging.DependencyInjection;
using System;
namespace RockLib.Logging
{
public static class RockLibLoggerExtensions
{
public static ILoggingBuilder AddRockLibLoggerProvider(this ILoggingBuilder builder, string rockLibLoggerName = Logger.DefaultName)
{
if (builder is null)
throw new ArgumentNullException(nameof(builder));
builder.Services.AddRockLibLoggerProvider(rockLibLoggerName);
return builder;
}
public static IServiceCollection AddRockLibLoggerProvider(this IServiceCollection services, string rockLibLoggerName = Logger.DefaultName)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
services.Add(ServiceDescriptor.Singleton<ILoggerProvider>(serviceProvider =>
{
var lookup = serviceProvider.GetRequiredService<LoggerLookup>();
var options = serviceProvider.GetService<IOptionsMonitor<RockLibLoggerOptions>>();
return new RockLibLoggerProvider(lookup(rockLibLoggerName), options);
}));
return services;
}
}
}
```
Add configureOptions parameter to extension methods | ```c#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RockLib.Logging.DependencyInjection;
using System;
namespace RockLib.Logging
{
public static class RockLibLoggerExtensions
{
public static ILoggingBuilder AddRockLibLoggerProvider(this ILoggingBuilder builder,
string rockLibLoggerName = Logger.DefaultName, Action<RockLibLoggerOptions> configureOptions = null)
{
if (builder is null)
throw new ArgumentNullException(nameof(builder));
builder.Services.AddRockLibLoggerProvider(rockLibLoggerName, configureOptions);
return builder;
}
public static IServiceCollection AddRockLibLoggerProvider(this IServiceCollection services,
string rockLibLoggerName = Logger.DefaultName, Action<RockLibLoggerOptions> configureOptions = null)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
services.Add(ServiceDescriptor.Singleton<ILoggerProvider>(serviceProvider =>
{
var lookup = serviceProvider.GetRequiredService<LoggerLookup>();
var options = serviceProvider.GetService<IOptionsMonitor<RockLibLoggerOptions>>();
return new RockLibLoggerProvider(lookup(rockLibLoggerName), options);
}));
if (configureOptions != null)
services.Configure(configureOptions);
return services;
}
}
}
``` |
3e57dcbc-c483-4662-8bc7-743b4342d2df | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Ical.Net.Interfaces.DataTypes
{
public interface IPeriodList : IEncodableDataType, IList<IPeriod>
{
string TzId { get; set; }
IPeriod this[int index] { get; set; }
void Add(IDateTime dt);
void Remove(IDateTime dt);
}
}```
Stop hiding indexer on IList | ```c#
using System.Collections.Generic;
namespace Ical.Net.Interfaces.DataTypes
{
public interface IPeriodList : IEncodableDataType, IList<IPeriod>
{
string TzId { get; set; }
new IPeriod this[int index] { get; set; }
void Add(IDateTime dt);
void Remove(IDateTime dt);
}
}``` |
ac68e8e4-9eb9-4a6b-aadf-1e73ea8e267c | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Content.Server.GameObjects.EntitySystems.StationEvents;
using NUnit.Framework;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;
namespace Content.IntegrationTests.Tests.StationEvents
{
[TestFixture]
public class StationEventsSystemTest : ContentIntegrationTest
{
[Test]
public async Task Test()
{
var server = StartServerDummyTicker();
server.Assert(() =>
{
// Idle each event once
var stationEventsSystem = EntitySystem.Get<StationEventSystem>();
var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds;
foreach (var stationEvent in stationEventsSystem.StationEvents)
{
stationEvent.Startup();
stationEvent.Update(dummyFrameTime);
stationEvent.Shutdown();
Assert.That(stationEvent.Occurrences == 1);
}
stationEventsSystem.ResettingCleanup();
foreach (var stationEvent in stationEventsSystem.StationEvents)
{
Assert.That(stationEvent.Occurrences == 0);
}
});
await server.WaitIdleAsync();
}
}
}```
Fix station events system test | ```c#
using System.Threading.Tasks;
using Content.Server.GameObjects.EntitySystems.StationEvents;
using NUnit.Framework;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;
namespace Content.IntegrationTests.Tests.StationEvents
{
[TestFixture]
public class StationEventsSystemTest : ContentIntegrationTest
{
[Test]
public async Task Test()
{
var server = StartServerDummyTicker();
server.Assert(() =>
{
// Idle each event once
var stationEventsSystem = EntitySystem.Get<StationEventSystem>();
var dummyFrameTime = (float) IoCManager.Resolve<IGameTiming>().TickPeriod.TotalSeconds;
foreach (var stationEvent in stationEventsSystem.StationEvents)
{
stationEvent.Startup();
stationEvent.Update(dummyFrameTime);
stationEvent.Shutdown();
Assert.That(stationEvent.Occurrences == 1);
}
stationEventsSystem.Reset();
foreach (var stationEvent in stationEventsSystem.StationEvents)
{
Assert.That(stationEvent.Occurrences == 0);
}
});
await server.WaitIdleAsync();
}
}
}
``` |
d5e3c0bc-b230-43bb-981a-14da2bd2069b | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Config;
using static Microsoft.Azure.Web.DataProtection.Constants;
namespace Microsoft.Azure.WebJobs.Script.WebHost
{
public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory
{
private bool _encryptionSupported;
private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite);
private static ScriptSettingsManager _settingsManager;
public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager)
{
_settingsManager = settingsManager;
_encryptionSupported = IsEncryptionSupported();
}
// In Linux Containers AzureWebsiteLocalEncryptionKey will be set, enabling encryption
private static bool IsEncryptionSupported() => _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null;
public IKeyValueReader GetValueReader(Key key)
{
if (key.IsEncrypted)
{
return new DataProtectionKeyValueConverter(FileAccess.Read);
}
return PlaintextValueConverter;
}
public IKeyValueWriter GetValueWriter(Key key)
{
if (_encryptionSupported)
{
return new DataProtectionKeyValueConverter(FileAccess.Write);
}
return PlaintextValueConverter;
}
}
}```
Use plain text for function secrets in Linux Containers | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Config;
using static Microsoft.Azure.Web.DataProtection.Constants;
namespace Microsoft.Azure.WebJobs.Script.WebHost
{
public sealed class DefaultKeyValueConverterFactory : IKeyValueConverterFactory
{
private readonly bool _encryptionSupported;
private static readonly PlaintextKeyValueConverter PlaintextValueConverter = new PlaintextKeyValueConverter(FileAccess.ReadWrite);
private static ScriptSettingsManager _settingsManager;
public DefaultKeyValueConverterFactory(ScriptSettingsManager settingsManager)
{
_settingsManager = settingsManager;
_encryptionSupported = IsEncryptionSupported();
}
private static bool IsEncryptionSupported()
{
if (_settingsManager.IsLinuxContainerEnvironment)
{
// TEMP: https://github.com/Azure/azure-functions-host/issues/3035
return false;
}
return _settingsManager.IsAppServiceEnvironment || _settingsManager.GetSetting(AzureWebsiteLocalEncryptionKey) != null;
}
public IKeyValueReader GetValueReader(Key key)
{
if (key.IsEncrypted)
{
return new DataProtectionKeyValueConverter(FileAccess.Read);
}
return PlaintextValueConverter;
}
public IKeyValueWriter GetValueWriter(Key key)
{
if (_encryptionSupported)
{
return new DataProtectionKeyValueConverter(FileAccess.Write);
}
return PlaintextValueConverter;
}
}
}``` |
e414fc53-27e3-414c-9f1d-3c4d409a5d05 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
Storage storage;
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
storage = host.Storage;
host.Run(new OsuTestCaseTestRunner(this));
}
// clean up after each run
storage.DeleteDirectory(string.Empty);
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
```
Remove TestCase cleanup temporarily until context disposal is sorted | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
host.Run(new OsuTestCaseTestRunner(this));
}
// clean up after each run
//storage.DeleteDirectory(string.Empty);
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
``` |
1aff3247-ae1e-4eaf-b8d2-602b785d02dd | {
"language": "C#"
} | ```c#
// Copyright 2016 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class GroupServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public GroupServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
/* TODO: Reinstate when ListGroups is present again.
[Fact]
public void ListGroups()
{
string projectId = _fixture.ProjectId;
// Snippet: ListGroups
GroupServiceClient client = GroupServiceClient.Create();
string projectName = MetricServiceClient.FormatProjectName(projectId);
IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
foreach (Group group in groups.Take(10))
{
Console.WriteLine($"{group.Name}: {group.DisplayName}");
}
// End snippet
}
*/
}
}
```
Remove the ListGroups snippet from Monitoring | ```c#
// Copyright 2016 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 Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class GroupServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public GroupServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
/* TODO: Reinstate when ListGroups is present again.
[Fact]
public void ListGroups()
{
string projectId = _fixture.ProjectId;
// FIXME:Snippet: ListGroups
GroupServiceClient client = GroupServiceClient.Create();
string projectName = MetricServiceClient.FormatProjectName(projectId);
IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
foreach (Group group in groups.Take(10))
{
Console.WriteLine($"{group.Name}: {group.DisplayName}");
}
// End snippet
}
*/
}
}
``` |
921aae49-3a66-4e37-ac29-840926324b82 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Plugin.MediaManager.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Plugin.MediaManager.Android")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Set Android permissions through Assemblyinfo | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Plugin.MediaManager.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Plugin.MediaManager.Android")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: UsesPermission(Android.Manifest.Permission.AccessWifiState)]
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.MediaContentControl)]
[assembly: UsesPermission(Android.Manifest.Permission.WakeLock)]``` |
0598afb6-5161-417f-95e6-a4b499e1ec17 | {
"language": "C#"
} | ```c#
namespace BigEgg.ConsoleExtension.Parameters.Errors
{
using System;
internal class CommandHelpRequestError : Error
{
public CommandHelpRequestError()
: base(ErrorType.CommandHelpRequest, true)
{ }
public string CommandName { get; private set; }
public bool Existed { get; set; }
public Type CommandType { get; set; }
}
}
```
Update the Command Help Request Error to get the value | ```c#
namespace BigEgg.ConsoleExtension.Parameters.Errors
{
using System;
internal class CommandHelpRequestError : Error
{
public CommandHelpRequestError(string commandName, bool existed, Type commandType)
: base(ErrorType.CommandHelpRequest, true)
{
CommandName = commandName;
Existed = existed;
CommandType = existed ? commandType : null;
}
public string CommandName { get; private set; }
public bool Existed { get; private set; }
public Type CommandType { get; private set; }
}
}
``` |
a4cfd2ca-a694-40b4-a07f-fa141641e0eb | {
"language": "C#"
} | ```c#
// 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.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
namespace osu.Game.Rulesets.Osu.Beatmaps
{
public class OsuBeatmap : Beatmap<OsuHitObject>
{
public override IEnumerable<BeatmapStatistic> GetStatistics()
{
IEnumerable<HitObject> circles = HitObjects.Where(c => c is HitCircle);
IEnumerable<HitObject> sliders = HitObjects.Where(s => s is Slider);
IEnumerable<HitObject> spinners = HitObjects.Where(s => s is Spinner);
return new[]
{
new BeatmapStatistic
{
Name = @"Circle Count",
Content = circles.Count().ToString(),
Icon = FontAwesome.fa_circle_o
},
new BeatmapStatistic
{
Name = @"Slider Count",
Content = sliders.Count().ToString(),
Icon = FontAwesome.fa_circle
},
new BeatmapStatistic
{
Name = @"Spinner Count",
Content = spinners.Count().ToString(),
Icon = FontAwesome.fa_circle
}
};
}
}
}
```
Simplify statistics in osu ruleset | ```c#
// 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.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
namespace osu.Game.Rulesets.Osu.Beatmaps
{
public class OsuBeatmap : Beatmap<OsuHitObject>
{
public override IEnumerable<BeatmapStatistic> GetStatistics()
{
int circles = HitObjects.Count(c => c is HitCircle);
int sliders = HitObjects.Count(s => s is Slider);
int spinners = HitObjects.Count(s => s is Spinner);
return new[]
{
new BeatmapStatistic
{
Name = @"Circle Count",
Content = circles.ToString(),
Icon = FontAwesome.fa_circle_o
},
new BeatmapStatistic
{
Name = @"Slider Count",
Content = sliders.ToString(),
Icon = FontAwesome.fa_circle
},
new BeatmapStatistic
{
Name = @"Spinner Count",
Content = spinners.ToString(),
Icon = FontAwesome.fa_circle
}
};
}
}
}
``` |
8f8f0942-842a-4148-a142-4041a3e37050 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading;
using Nancy;
using Nancy.Hosting.Self;
namespace ChildProcessUtil
{
public class Program
{
private const string HttpAddress = "http://localhost:";
private static NancyHost host;
private static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId");
return;
}
StartServer(int.Parse(args[0]), int.Parse(args[1]));
}
public static void StartServer(int port, int mainProcessId)
{
var hostConfigs = new HostConfiguration
{
UrlReservations = new UrlReservations {CreateAutomatically = true}
};
var uriString = HttpAddress + port;
ProcessModule.ActiveProcesses = new List<int>();
host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
host.Start();
new MainProcessWatcher(mainProcessId);
Thread.Sleep(Timeout.Infinite);
}
internal static void StopServer(int port)
{
host.Stop();
}
}
}```
Add short desc on main | ```c#
using System;
using System.Collections.Generic;
using System.Threading;
using Nancy;
using Nancy.Hosting.Self;
namespace ChildProcessUtil
{
public class Program
{
private const string HttpAddress = "http://localhost:";
private static NancyHost host;
private static void Main(string[] args)
{
Console.WriteLine("Child process watcher and automatic killer");
if (args.Length != 2)
{
Console.WriteLine("usage: ChildProcessUtil.exe serverPort mainProcessId");
return;
}
StartServer(int.Parse(args[0]), int.Parse(args[1]));
}
public static void StartServer(int port, int mainProcessId)
{
var hostConfigs = new HostConfiguration
{
UrlReservations = new UrlReservations {CreateAutomatically = true}
};
var uriString = HttpAddress + port;
ProcessModule.ActiveProcesses = new List<int>();
host = new NancyHost(new Uri(uriString), new DefaultNancyBootstrapper(), hostConfigs);
host.Start();
new MainProcessWatcher(mainProcessId);
Thread.Sleep(Timeout.Infinite);
}
internal static void StopServer(int port)
{
host.Stop();
}
}
}``` |
bb2b487e-916c-486a-be79-7cb28a2eccb6 | {
"language": "C#"
} | ```c#
namespace ReimuPlugins.Common
{
public enum Revision
{
Rev1 = 1,
Rev2
}
public enum ErrorCode
{
NoFunction = -1,
AllRight,
NotSupport,
FileReadError,
FileWriteError,
NoMemory,
UnknownError,
DialogCanceled
}
public enum TextAlign
{
Left = 0,
Right,
Center
}
public enum SortType
{
String = 0,
Number,
Float,
Hex
}
public enum SystemInfoType
{
String = 0,
Path,
Directory,
Title,
Extension,
CreateTime,
LastAccessTime,
LastWriteTime,
FileSize
}
}
```
Add Enc class for convenience | ```c#
using System.Text;
namespace ReimuPlugins.Common
{
public enum Revision
{
Rev1 = 1,
Rev2
}
public enum ErrorCode
{
NoFunction = -1,
AllRight,
NotSupport,
FileReadError,
FileWriteError,
NoMemory,
UnknownError,
DialogCanceled
}
public enum TextAlign
{
Left = 0,
Right,
Center
}
public enum SortType
{
String = 0,
Number,
Float,
Hex
}
public enum SystemInfoType
{
String = 0,
Path,
Directory,
Title,
Extension,
CreateTime,
LastAccessTime,
LastWriteTime,
FileSize
}
public static class Enc
{
public static readonly Encoding SJIS = Encoding.GetEncoding("shift_jis");
public static readonly Encoding UTF8 = Encoding.UTF8;
}
}
``` |
695ba438-5102-421a-92b3-3b5d97a81085 | {
"language": "C#"
} | ```c#
/**
Copyright 2014-2017 Robert McNeel and Associates
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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using System;
using System.Drawing;
namespace RhinoCycles.Settings
{
public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
{
public OptionsDialogPage() : base(Localization.LocalizeString("Raytraced settings", 37))
{
CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
}
public override object PageControl => CollapsibleSectionHolder;
private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
}
}
```
Rename Raytraced settings Options page to just Cycles. | ```c#
/**
Copyright 2014-2017 Robert McNeel and Associates
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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using System;
using System.Drawing;
namespace RhinoCycles.Settings
{
public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
{
public OptionsDialogPage() : base(Localization.LocalizeString("Cycles", 7))
{
CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
}
public override object PageControl => CollapsibleSectionHolder;
private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
}
}
``` |
06aab446-82fc-47c5-b364-98475ff30296 | {
"language": "C#"
} | ```c#
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Utility
{
/// <summary>
/// Exception thrown when data read by Noda Time (such as serialized time zone data) is invalid.
/// </summary>
/// <remarks>
/// This type only exists as <c>InvalidDataException</c> doesn't exist in the Portable Class Library.
/// Unfortunately, <c>InvalidDataException</c> itself is sealed, so we can't derive from it for the sake
/// of backward compatibility.
/// </remarks>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
#if !PCL
[Serializable]
#endif
// TODO: Derive from IOException instead, like EndOfStreamException does?
public class InvalidNodaDataException : Exception
{
/// <summary>
/// Creates an instance with the given message.
/// </summary>
/// <param name="message">The message for the exception.</param>
public InvalidNodaDataException(string message) : base(message) { }
}
}
```
Fix crazy Unix line endings ;) | ```c#
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Utility
{
/// <summary>
/// Exception thrown when data read by Noda Time (such as serialized time zone data) is invalid.
/// </summary>
/// <remarks>
/// This type only exists as <c>InvalidDataException</c> doesn't exist in the Portable Class Library.
/// Unfortunately, <c>InvalidDataException</c> itself is sealed, so we can't derive from it for the sake
/// of backward compatibility.
/// </remarks>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
#if !PCL
[Serializable]
#endif
// TODO: Derive from IOException instead, like EndOfStreamException does?
public class InvalidNodaDataException : Exception
{
/// <summary>
/// Creates an instance with the given message.
/// </summary>
/// <param name="message">The message for the exception.</param>
public InvalidNodaDataException(string message) : base(message) { }
}
}
``` |
031531b1-8e20-4674-b4a5-e348ef6fc0a9 | {
"language": "C#"
} | ```c#
using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
/// <summary>
/// execute 'yarn version' with options
/// </summary>
/// <param name="versionSettings">options when running 'yarn version'</param>
IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);
}
}
```
Fix 'yarn audit'. Register the Audit alias | ```c#
using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
/// <summary>
/// execute 'yarn version' with options
/// </summary>
/// <param name="versionSettings">options when running 'yarn version'</param>
IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);
/// <summary>
/// execute 'yarn audit' with options
/// </summary>
/// <param name="auditSettings">options when running 'yarn audit'</param>
/// <returns></returns>
IYarnRunnerCommands Audit(Action<YarnAuditSettings> auditSettings = null);
}
}
``` |
7e0fa407-45ce-4b5d-93fb-9642bca044e6 | {
"language": "C#"
} | ```c#
/* Copyright 2014 Jonathan Holland.
*
* 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 Microsoft.Practices.Unity;
using Wave.Configuration;
using Wave.IoC.Unity;
namespace Wave
{
public static class FluentConfigurationSourceExtensions
{
public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, UnityContainer container)
{
return builder.UsingContainer(new UnityContainerAdapter(container));
}
}
}
```
Use interface, not concrete type, for Unity Fluent extension. | ```c#
/* Copyright 2014 Jonathan Holland.
*
* 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 Microsoft.Practices.Unity;
using Wave.Configuration;
using Wave.IoC.Unity;
namespace Wave
{
public static class FluentConfigurationSourceExtensions
{
public static FluentConfigurationSource UseUnity(this FluentConfigurationSource builder, IUnityContainer container)
{
return builder.UsingContainer(new UnityContainerAdapter(container));
}
}
}
``` |
35696e4a-b130-4973-8d68-409a13927efb | {
"language": "C#"
} | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickImageTests
{
public class TheAddNoiseMethod
{
[Fact]
public void ShouldCreateDifferentImagesEachRun()
{
using (var imageA = new MagickImage(MagickColors.Black, 10, 10))
{
using (var imageB = new MagickImage(MagickColors.Black, 10, 10))
{
imageA.AddNoise(NoiseType.Random);
imageB.AddNoise(NoiseType.Random);
Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
}
}
}
}
}
}
```
Test with a slightly larger image. | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickImageTests
{
public class TheAddNoiseMethod
{
[Fact]
public void ShouldCreateDifferentImagesEachRun()
{
using (var imageA = new MagickImage(MagickColors.Black, 100, 100))
{
imageA.AddNoise(NoiseType.Random);
using (var imageB = new MagickImage(MagickColors.Black, 100, 100))
{
imageB.AddNoise(NoiseType.Random);
Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared));
}
}
}
}
}
}
``` |
ee6c891a-7d9d-49aa-96c9-d49e21d69179 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Reflection;
using UnityEngine;
public class CoroutineModComponentSolver : ComponentSolver
{
public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
ProcessMethod = processMethod;
CommandComponent = commandComponent;
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand });
if (responseCoroutine == null)
{
yield break;
}
yield return "modcoroutine";
while (responseCoroutine.MoveNext())
{
yield return responseCoroutine.Current;
}
}
private readonly MethodInfo ProcessMethod = null;
private readonly Component CommandComponent = null;
}
```
Add option to yield return a KMSelectable to toggle-interact with. | ```c#
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class CoroutineModComponentSolver : ComponentSolver
{
public CoroutineModComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller, MethodInfo processMethod, Component commandComponent) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
ProcessMethod = processMethod;
CommandComponent = commandComponent;
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
IEnumerator responseCoroutine = (IEnumerator)ProcessMethod.Invoke(CommandComponent, new object[] { inputCommand });
if (responseCoroutine == null)
{
yield break;
}
yield return "modcoroutine";
while (responseCoroutine.MoveNext())
{
object currentObject = responseCoroutine.Current;
if (currentObject.GetType() == typeof(KMSelectable))
{
KMSelectable selectable = (KMSelectable)currentObject;
if (HeldSelectables.Contains(selectable))
{
DoInteractionEnd(selectable);
HeldSelectables.Remove(selectable);
}
else
{
DoInteractionStart(selectable);
HeldSelectables.Add(selectable);
}
}
yield return currentObject;
}
}
private readonly MethodInfo ProcessMethod = null;
private readonly Component CommandComponent = null;
private readonly List<KMSelectable> HeldSelectables = new List<KMSelectable>();
}
``` |
09378a9d-6253-4c92-9fcd-804747f7fc33 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace AsyncRewriter
{
/// <summary>
/// </summary>
/// <remarks>
/// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio
/// </remarks>
public class RewriteAsync : Microsoft.Build.Utilities.Task
{
[Required]
public ITaskItem[] InputFiles { get; set; }
[Required]
public ITaskItem OutputFile { get; set; }
readonly Rewriter _rewriter;
public RewriteAsync()
{
_rewriter = new Rewriter(new TaskLoggingAdapter(Log));
}
public override bool Execute()
{
var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray());
File.WriteAllText(OutputFile.ItemSpec, asyncCode);
return true;
}
}
}
```
Fix null reference exception when running under Mono | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace AsyncRewriter
{
/// <summary>
/// </summary>
/// <remarks>
/// http://stackoverflow.com/questions/2961753/how-to-hide-files-generated-by-custom-tool-in-visual-studio
/// </remarks>
public class RewriteAsync : Microsoft.Build.Utilities.Task
{
[Required]
public ITaskItem[] InputFiles { get; set; }
[Required]
public ITaskItem OutputFile { get; set; }
readonly Rewriter _rewriter;
public RewriteAsync()
{
_rewriter = Log == null ? new Rewriter() : new Rewriter(new TaskLoggingAdapter(Log));
}
public override bool Execute()
{
var asyncCode = _rewriter.RewriteAndMerge(InputFiles.Select(f => f.ItemSpec).ToArray());
File.WriteAllText(OutputFile.ItemSpec, asyncCode);
return true;
}
}
}
``` |
634742b6-36ca-4167-a2b4-550de7b8d375 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace Xamarin.Forms.Controls.Issues
{
public partial class Bugzilla42069_Page : ContentPage
{
public const string DestructorMessage = ">>>>>>>>>> Bugzilla42069_Page destructor <<<<<<<<<<";
public Bugzilla42069_Page()
{
InitializeComponent();
ImageWhichChanges = ImageSource.FromFile("oasissmall.jpg") as FileImageSource;
ChangingImage.SetBinding(Image.SourceProperty, nameof(ImageWhichChanges));
Button.Clicked += (sender, args) => Navigation.PopAsync(false);
Button2.Clicked += (sender, args) =>
{
ImageWhichChanges.File = ImageWhichChanges.File == "bank.png" ? "oasissmall.jpg" : "bank.png";
};
BindingContext = this;
}
~Bugzilla42069_Page()
{
Debug.WriteLine(DestructorMessage);
}
public FileImageSource ImageWhichChanges { get; set; }
}
}```
Add missing compiler directives to fix build error | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace Xamarin.Forms.Controls.Issues
{
public partial class Bugzilla42069_Page : ContentPage
{
public const string DestructorMessage = ">>>>>>>>>> Bugzilla42069_Page destructor <<<<<<<<<<";
public Bugzilla42069_Page()
{
#if APP
InitializeComponent();
ImageWhichChanges = ImageSource.FromFile("oasissmall.jpg") as FileImageSource;
ChangingImage.SetBinding(Image.SourceProperty, nameof(ImageWhichChanges));
Button.Clicked += (sender, args) => Navigation.PopAsync(false);
Button2.Clicked += (sender, args) =>
{
ImageWhichChanges.File = ImageWhichChanges.File == "bank.png" ? "oasissmall.jpg" : "bank.png";
};
BindingContext = this;
#endif
}
~Bugzilla42069_Page()
{
Debug.WriteLine(DestructorMessage);
}
public FileImageSource ImageWhichChanges { get; set; }
}
}``` |
f09713b0-e7d1-4e76-ad3a-4d08586d5fb2 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Castle.Windsor.MsDependencyInjection
{
public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer>
{
public IWindsorContainer CreateBuilder(IServiceCollection services)
{
var container = services.GetSingletonServiceOrNull<IWindsorContainer>();
if (container == null)
{
container = new WindsorContainer();
services.AddSingleton(container);
}
WindsorRegistrationHelper.AddServices(container, services);
return container;
}
public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder)
{
return containerBuilder.Resolve<IServiceProvider>();
}
}
}
```
Use extension method for WindsorRegistrationHelper.AddServices | ```c#
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Castle.Windsor.MsDependencyInjection
{
public class WindsorServiceProviderFactory : IServiceProviderFactory<IWindsorContainer>
{
public IWindsorContainer CreateBuilder(IServiceCollection services)
{
var container = services.GetSingletonServiceOrNull<IWindsorContainer>();
if (container == null)
{
container = new WindsorContainer();
services.AddSingleton(container);
}
container.AddServices(services);
return container;
}
public IServiceProvider CreateServiceProvider(IWindsorContainer containerBuilder)
{
return containerBuilder.Resolve<IServiceProvider>();
}
}
}
``` |
58c52018-fdaf-4384-bc52-8b9773415693 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings
{
public string ConnectionString { get; } = $@"{TestContext.CurrentContext.TestDirectory}\Tests.db";
}
}
```
Add interface as resharper forgot | ```c#
using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings : IMyDatabaseSettings
{
public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;";
}
}
``` |
5180d238-c31a-47a9-951e-d18f2c66e95f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace ChamberLib
{
public interface IModel
{
object Tag { get; set; }
IEnumerable<IMesh> GetMeshes();
void Draw(Matrix world, Matrix view, Matrix projection,
IMaterial materialOverride=null,
LightingData? lightingOverride=null);
IBone Root { get; set; }
void SetAmbientLightColor(Vector3 value);
void SetEmissiveColor(Vector3 value);
void SetDirectionalLight(DirectionalLight light, int index=0);
void DisableDirectionalLight(int index);
void SetAlpha(float alpha);
void SetTexture(ITexture2D texture);
void SetBoneTransforms(Matrix[] boneTransforms,
IMaterial materialOverride=null);
IEnumerable<Triangle> EnumerateTriangles();
}
public static class ModelHelper
{
public static Vector3? IntersectClosest(this IModel model, Ray ray)
{
Vector3? closest = null;
float closestDist = -1;
foreach (var tri in model.EnumerateTriangles())
{
var p = tri.Intersects(ray);
if (!p.HasValue) continue;
if (!closest.HasValue)
{
closest = p;
}
else
{
var dist = (p.Value - ray.Position).LengthSquared();
if (dist < closestDist)
{
closest = p;
closestDist = dist;
}
}
}
return closest;
}
}
}
```
Update the closest known distance. | ```c#
using System;
using System.Collections.Generic;
namespace ChamberLib
{
public interface IModel
{
object Tag { get; set; }
IEnumerable<IMesh> GetMeshes();
void Draw(Matrix world, Matrix view, Matrix projection,
IMaterial materialOverride=null,
LightingData? lightingOverride=null);
IBone Root { get; set; }
void SetAmbientLightColor(Vector3 value);
void SetEmissiveColor(Vector3 value);
void SetDirectionalLight(DirectionalLight light, int index=0);
void DisableDirectionalLight(int index);
void SetAlpha(float alpha);
void SetTexture(ITexture2D texture);
void SetBoneTransforms(Matrix[] boneTransforms,
IMaterial materialOverride=null);
IEnumerable<Triangle> EnumerateTriangles();
}
public static class ModelHelper
{
public static Vector3? IntersectClosest(this IModel model, Ray ray)
{
Vector3? closest = null;
float closestDist = -1;
foreach (var tri in model.EnumerateTriangles())
{
var p = tri.Intersects(ray);
if (!p.HasValue) continue;
if (!closest.HasValue)
{
closest = p;
closestDist = (p.Value - ray.Position).LengthSquared();
}
else
{
var dist = (p.Value - ray.Position).LengthSquared();
if (dist < closestDist)
{
closest = p;
closestDist = dist;
}
}
}
return closest;
}
}
}
``` |
95fbe905-174b-4fce-95ac-8e4ae2e1e459 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.EventFlow.Configuration
{
public class ElasticSearchMappingsConfiguration
{
public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; private set; }
public ElasticSearchMappingsConfiguration()
{
Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>();
}
internal ElasticSearchMappingsConfiguration DeepClone()
{
var other = new ElasticSearchMappingsConfiguration();
foreach (var item in this.Properties)
{
other.Properties.Add(item.Key, item.Value.DeepClone());
}
return other;
}
}
}
```
Make ES mapping configuration Properties setter public | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.EventFlow.Configuration
{
public class ElasticSearchMappingsConfiguration
{
public Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor> Properties { get; set; }
public ElasticSearchMappingsConfiguration()
{
Properties = new Dictionary<string, ElasticSearchMappingsConfigurationPropertyDescriptor>();
}
internal ElasticSearchMappingsConfiguration DeepClone()
{
var other = new ElasticSearchMappingsConfiguration();
foreach (var item in this.Properties)
{
other.Properties.Add(item.Key, item.Value.DeepClone());
}
return other;
}
}
}
``` |
c92b7616-3da7-4289-9c11-7b1c0a9b8a1d | {
"language": "C#"
} | ```c#
using System.IO;
using JetBrains.Annotations;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
using XmlDocInspections.Plugin.Highlighting;
namespace XmlDocInspections.Plugin.Tests.Integrative
{
public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestNet4Base
{
protected override string RelativeTestDataPath => "Highlighting";
protected override string GetGoldTestDataPath(string fileName)
{
return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName));
}
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile)
{
return highlighting is MissingXmlDocHighlighting;
}
protected override void DoTestSolution(params string[] fileSet)
{
ExecuteWithinSettingsTransaction(settingsStore =>
{
RunGuarded(() => MutateSettings(settingsStore));
base.DoTestSolution(fileSet);
});
}
protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore);
}
}```
Replace CSharpHighlightingTestBase (will be removed in 2016.2 SDK) usage with TestNetFramework4-attribute | ```c#
using System.IO;
using JetBrains.Annotations;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.TestFramework;
using XmlDocInspections.Plugin.Highlighting;
namespace XmlDocInspections.Plugin.Tests.Integrative
{
[TestNetFramework4]
public abstract class MissingXmlDocHighlightingTestsBase : CSharpHighlightingTestBase
{
protected override string RelativeTestDataPath => "Highlighting";
protected override string GetGoldTestDataPath(string fileName)
{
return base.GetGoldTestDataPath(Path.Combine(GetType().Name, fileName));
}
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile)
{
return highlighting is MissingXmlDocHighlighting;
}
protected override void DoTestSolution(params string[] fileSet)
{
ExecuteWithinSettingsTransaction(settingsStore =>
{
RunGuarded(() => MutateSettings(settingsStore));
base.DoTestSolution(fileSet);
});
}
protected abstract void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore);
}
}``` |
4e59df45-752d-4bbb-ba9f-3aa17f99f512 | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;
namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly string _apiKey;
public CompaniesHouseEmployerVerificationService(string apiKey)
{
_apiKey = apiKey;
}
public async Task<EmployerInformation> GetInformation(string id)
{
Logger.Info($"GetInformation({id})");
var webClient = new WebClient();
webClient.Headers.Add($"Authorization: Basic {_apiKey}");
try
{
var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");
return JsonConvert.DeserializeObject<EmployerInformation>(result);
}
catch (WebException ex)
{
Logger.Error(ex, "There was a problem with the call to Companies House");
}
return null;
}
}
}```
Modify the companies house verification service to use the config initalised as a constructor parameter | ```c#
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
using SFA.DAS.EmployerApprenticeshipsService.Domain;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;
namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
public class CompaniesHouseEmployerVerificationService : IEmployerVerificationService
{
private readonly EmployerApprenticeshipsServiceConfiguration _configuration;
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
public CompaniesHouseEmployerVerificationService(EmployerApprenticeshipsServiceConfiguration configuration)
{
_configuration = configuration;
}
public async Task<EmployerInformation> GetInformation(string id)
{
Logger.Info($"GetInformation({id})");
var webClient = new WebClient();
webClient.Headers.Add($"Authorization: Basic {_configuration.CompaniesHouse.ApiKey}");
try
{
var result = await webClient.DownloadStringTaskAsync($"https://api.companieshouse.gov.uk/company/{id}");
return JsonConvert.DeserializeObject<EmployerInformation>(result);
}
catch (WebException ex)
{
Logger.Error(ex, "There was a problem with the call to Companies House");
}
return null;
}
}
}``` |
636f5bb2-fe5b-4716-87bf-ebf3afa2e169 | {
"language": "C#"
} | ```c#
using AutoMapper;
using Esfa.Vacancy.Api.Types;
using Esfa.Vacancy.Register.Api;
using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies;
using FluentAssertions;
using NUnit.Framework;
namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters
{
[TestFixture]
public class AndPageNumber
{
private IMapper _mapper;
[SetUp]
public void Setup()
{
var config = AutoMapperConfig.Configure();
_mapper = config.CreateMapper();
}
[Test]
public void WhenProvided_ThenPopulateRequestWithTheGivenValue()
{
var expectedPageNumber = 2;
var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber };
var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
result.PageNumber.Should().Be(expectedPageNumber);
}
[Test]
public void WhenNotProvided_ThenPoplateRequestWithTheDefaultValue()
{
var parameters = new SearchApprenticeshipParameters();
var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
result.PageNumber.Should().Be(1);
}
}
}
```
Fix spelling error in method name | ```c#
using AutoMapper;
using Esfa.Vacancy.Api.Types;
using Esfa.Vacancy.Register.Api;
using Esfa.Vacancy.Register.Application.Queries.SearchApprenticeshipVacancies;
using FluentAssertions;
using NUnit.Framework;
namespace Esfa.Vacancy.Register.UnitTests.SearchApprenticeship.Api.GivenSearchApprenticeshipParameters
{
[TestFixture]
public class AndPageNumber
{
private IMapper _mapper;
[SetUp]
public void Setup()
{
var config = AutoMapperConfig.Configure();
_mapper = config.CreateMapper();
}
[Test]
public void WhenProvided_ThenPopulateRequestWithTheGivenValue()
{
var expectedPageNumber = 2;
var parameters = new SearchApprenticeshipParameters() { PageNumber = expectedPageNumber };
var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
result.PageNumber.Should().Be(expectedPageNumber);
}
[Test]
public void WhenNotProvided_ThenPopulateRequestWithTheDefaultValue()
{
var parameters = new SearchApprenticeshipParameters();
var result = _mapper.Map<SearchApprenticeshipVacanciesRequest>(parameters);
result.PageNumber.Should().Be(1);
}
}
}
``` |
766e4519-1052-4ee2-aa97-a396b969be36 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Text;
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class TransformExtensions
{
/// <summary>
/// An extension method that will get you the full path to an object.
/// </summary>
/// <param name="transform">The transform you wish a full path to.</param>
/// <param name="delimiter">The delimiter with which each object is delimited in the string.</param>
/// <param name="prefix">Prefix with which the full path to the object should start.</param>
/// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns>
public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/")
{
StringBuilder stringBuilder = new StringBuilder();
if (transform.parent == null)
{
stringBuilder.Append(prefix);
stringBuilder.Append(transform.name);
}
else
{
stringBuilder.Append(transform.parent.GetFullPath(delimiter, prefix));
stringBuilder.Append(delimiter);
stringBuilder.Append(transform.name);
}
return stringBuilder.ToString();
}
}
}```
Create one single instance of StringBuilder | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Text;
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class TransformExtensions
{
/// <summary>
/// An extension method that will get you the full path to an object.
/// </summary>
/// <param name="transform">The transform you wish a full path to.</param>
/// <param name="delimiter">The delimiter with which each object is delimited in the string.</param>
/// <param name="prefix">Prefix with which the full path to the object should start.</param>
/// <returns>A delimited string that is the full path to the game object in the hierarchy.</returns>
public static string GetFullPath(this Transform transform, string delimiter = ".", string prefix = "/")
{
StringBuilder stringBuilder = new StringBuilder();
GetFullPath(stringBuilder, transform, delimiter, prefix);
return stringBuilder.ToString();
}
private static void GetFullPath(StringBuilder stringBuilder, Transform transform, string delimiter = ".", string prefix = "/")
{
if (transform.parent == null)
{
stringBuilder.Append(prefix);
}
else
{
GetFullPath(stringBuilder, transform.parent, delimiter, prefix);
stringBuilder.Append(delimiter);
}
stringBuilder.Append(transform.name);
}
}
}``` |
c1fbb28d-1dc1-4ff1-abbe-5d4d6e856c57 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
if (savedInstanceState == null)
{
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState(outState);
webView.SaveState(outState);
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
base.OnRestoreInstanceState(savedInstanceState);
webView.RestoreState(savedInstanceState);
}
}
}```
Stop webview from reloading when rotated | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
if (savedInstanceState == null)
{
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
}
}``` |
1ac8ba36-e07e-472f-bfa0-b106f77c06c3 | {
"language": "C#"
} | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
<h1 class="heading-large">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script>
$('#manualLoginContainer').hide();
$('#autoRedirect').show();
$('#mainForm').submit();
</script>
}```
Fix h1 class to match other views | ```c#
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Login Successful";
ViewBag.HideSigninLink = "true";
}
<h1 class="heading-xlarge">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script>
$('#manualLoginContainer').hide();
$('#autoRedirect').show();
$('#mainForm').submit();
</script>
}``` |
f0959e7c-31fe-4ee3-b346-52ae2b4d46ab | {
"language": "C#"
} | ```c#
using System;
namespace FbxSharp
{
public struct FbxTime
{
public static readonly FbxTime Infinite = new FbxTime(0x7fffffffffffffffL);
public static readonly FbxTime Zero = new FbxTime(0);
public FbxTime(long time)
{
Value = time;
}
public long Value;
public long Get()
{
return Value;
}
public double GetSecondDouble()
{
return Value / 46186158000.0;
}
public long GetFrameCount()
{
return Value / 1539538600L;
}
}
}
```
Store the number of time units per second in a static const value. | ```c#
using System;
namespace FbxSharp
{
public struct FbxTime
{
public static readonly FbxTime Infinite = new FbxTime(0x7fffffffffffffffL);
public static readonly FbxTime Zero = new FbxTime(0);
public const long UnitsPerSecond = 46186158000L;
public FbxTime(long time)
{
Value = time;
}
public long Value;
public long Get()
{
return Value;
}
public double GetSecondDouble()
{
return Value / (double)UnitsPerSecond;
}
public long GetFrameCount()
{
return Value / 1539538600L;
}
}
}
``` |
82ccd21a-828a-4878-a386-0c6d73e2ab3d | {
"language": "C#"
} | ```c#
using Kentor.PU_Adapter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PU_Stub.Controllers
{
public class SnodController : ApiController
{
private static readonly IDictionary<string, string> TestPersons;
static SnodController()
{
TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList
.ToDictionary(p => p.Substring(8, 12)); // index by person number
}
[HttpGet]
public HttpResponseMessage PKNODPLUS(string arg)
{
System.Threading.Thread.Sleep(30); // Introduce production like latency
string result;
if (!TestPersons.TryGetValue(arg, out result))
{
// Returkod: 0001 = Sökt person saknas i registren
result = "13270001 _";
}
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain");
return resp;
}
}
}
```
Add inital response lines in PU-Stub to mimic production PU | ```c#
using Kentor.PU_Adapter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PU_Stub.Controllers
{
public class SnodController : ApiController
{
private static readonly IDictionary<string, string> TestPersons;
static SnodController()
{
TestPersons = Kentor.PU_Adapter.TestData.TestPersonsPuData.PuDataList
.ToDictionary(p => p.Substring(8, 12)); // index by person number
}
[HttpGet]
public HttpResponseMessage PKNODPLUS(string arg)
{
System.Threading.Thread.Sleep(30); // Introduce production like latency
string result;
if (!TestPersons.TryGetValue(arg, out result))
{
// Returkod: 0001 = Sökt person saknas i registren
result = "13270001 _";
}
result = "0\n0\n1327\n" + result; // add magic initial lines, like production PU does
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.GetEncoding("ISO-8859-1"), "text/plain");
return resp;
}
}
}
``` |
5b62004c-fb73-4a4f-9b82-1d39e2f5a185 | {
"language": "C#"
} | ```c#
using CIV.Ccs;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
System.Console.WriteLine(action);
}
}
}
}
```
Add “using static System.Console” to main | ```c#
using static System.Console;
using CIV.Ccs;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
``` |
b8f71b51-de44-44a9-b63f-7133256f83c6 | {
"language": "C#"
} | ```c#
// 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).AsSelf().As<ISitePlugin>();
return this;
}
public SiteObject Build()
{
var container = _containerBuilder.Build();
return container.Resolve<SiteObject>();
}
}
}```
Make sure that a plugin is only created once | ```c#
// 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>();
}
}
}``` |
1064e3a9-dcf6-4d27-a9cd-581932a21b54 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class GameStart : MonoBehaviour {
static int gameMode = INSTRUCTION;
const int INSTRUCTION = -1;
const int ONE_PLAYER = 1;
const int TWO_PLAYER = 2;
/// <summary>
/// The game mode of the current game
/// </summary>
public static int GameMode
{
get { return gameMode; }
set
{
if(value == ONE_PLAYER || value == TWO_PLAYER || value == INSTRUCTION)
{
gameMode = value;
}
}
}
/// <summary>
/// Add the game to the global board and then destroy this (no longer necessary)
/// </summary>
private void Awake()
{
if(GameMode == ONE_PLAYER)
{
gameObject.AddComponent<SinglePlayerGame>();
}
else if (GameMode == TWO_PLAYER)
{
gameObject.AddComponent<Game>();
}
else if (GameMode == INSTRUCTION)
{
gameObject.AddComponent<InstructionGame>();
}
Destroy(this);
}
}
```
Change default gamemode from INSTRUCTION to ONE_PLAYER | ```c#
using UnityEngine;
using System.Collections;
public class GameStart : MonoBehaviour {
static int gameMode = ONE_PLAYER;
const int INSTRUCTION = -1;
const int ONE_PLAYER = 1;
const int TWO_PLAYER = 2;
/// <summary>
/// The game mode of the current game
/// </summary>
public static int GameMode
{
get { return gameMode; }
set
{
if(value == ONE_PLAYER || value == TWO_PLAYER || value == INSTRUCTION)
{
gameMode = value;
}
}
}
/// <summary>
/// Add the game to the global board and then destroy this (no longer necessary)
/// </summary>
private void Awake()
{
if(GameMode == ONE_PLAYER)
{
gameObject.AddComponent<SinglePlayerGame>();
}
else if (GameMode == TWO_PLAYER)
{
gameObject.AddComponent<Game>();
}
else if (GameMode == INSTRUCTION)
{
gameObject.AddComponent<InstructionGame>();
}
Destroy(this);
}
}
``` |
27bbbf73-12fa-487c-ad48-033007226fe5 | {
"language": "C#"
} | ```c#
using Abp.AspNetCore.OData.Controllers;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Web.Models;
using AbpODataDemo.People;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace AbpODataDemo.Controllers
{
[DontWrapResult]
public class PersonsController : AbpODataEntityController<Person>, ITransientDependency
{
public PersonsController(IRepository<Person> repository)
: base(repository)
{
}
public override Task<IActionResult> Delete([FromODataUri] int key)
{
return base.Delete(key);
}
public override IQueryable<Person> Get()
{
return base.Get();
}
public override SingleResult<Person> Get([FromODataUri] int key)
{
return base.Get(key);
}
public override Task<IActionResult> Patch([FromODataUri] int key, Delta<Person> entity)
{
return base.Patch(key, entity);
}
public override Task<IActionResult> Post(Person entity)
{
return base.Post(entity);
}
public override Task<IActionResult> Put([FromODataUri] int key, Person update)
{
return base.Put(key, update);
}
}
}
```
Fix model binding for OData Patch, Post, Put | ```c#
using Abp.AspNetCore.OData.Controllers;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Web.Models;
using AbpODataDemo.People;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace AbpODataDemo.Controllers
{
[DontWrapResult]
public class PersonsController : AbpODataEntityController<Person>, ITransientDependency
{
public PersonsController(IRepository<Person> repository)
: base(repository)
{
}
public override Task<IActionResult> Delete([FromODataUri] int key)
{
return base.Delete(key);
}
public override IQueryable<Person> Get()
{
return base.Get();
}
public override SingleResult<Person> Get([FromODataUri] int key)
{
return base.Get(key);
}
public override Task<IActionResult> Patch([FromODataUri] int key, [FromBody] Delta<Person> entity)
{
return base.Patch(key, entity);
}
public override Task<IActionResult> Post([FromBody] Person entity)
{
return base.Post(entity);
}
public override Task<IActionResult> Put([FromODataUri] int key, [FromBody] Person update)
{
return base.Put(key, update);
}
}
}
``` |
2124c3b2-e974-4cd5-aa6d-01cefc8bfd50 | {
"language": "C#"
} | ```c#
/**
Copyright 2014-2017 Robert McNeel and Associates
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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using RhinoCyclesCore.Core;
using System;
using System.Drawing;
namespace RhinoCycles.Settings
{
public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
{
public OptionsDialogPage() : base(Localization.LocalizeString("Cycles", 7))
{
CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
}
public override object PageControl => CollapsibleSectionHolder;
public override bool ShowApplyButton => false;
public override bool ShowDefaultsButton => true;
public override void OnDefaults()
{
RcCore.It.EngineSettings.DefaultSettings();
CollapsibleSectionHolder.UpdateSections();
}
private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
}
}
```
Add PageImage override for Mac and fix title string | ```c#
/**
Copyright 2014-2017 Robert McNeel and Associates
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 Rhino;
using Rhino.DocObjects;
using Rhino.UI;
using RhinoCyclesCore.Core;
using System;
using System.Drawing;
namespace RhinoCycles.Settings
{
public class OptionsDialogPage : Rhino.UI.OptionsDialogPage
{
public OptionsDialogPage() : base("Cycles")
{
CollapsibleSectionHolder = new OptionsDialogCollapsibleSectionUIPanel();
}
public override object PageControl => CollapsibleSectionHolder;
public override bool ShowApplyButton => false;
public override bool ShowDefaultsButton => true;
public override string LocalPageTitle => Localization.LocalizeString ("Cycles", 7);
public override Image PageImage {
get {
var icon = Properties.Resources.Cycles_viewport_properties;
return icon.ToBitmap ();
}
}
public override void OnDefaults()
{
RcCore.It.EngineSettings.DefaultSettings();
CollapsibleSectionHolder.UpdateSections();
}
private OptionsDialogCollapsibleSectionUIPanel CollapsibleSectionHolder { get; }
}
}
``` |
58899a8f-68ad-4a80-9e81-f55c518e8f10 | {
"language": "C#"
} | ```c#
@model SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account
<h1 class="heading-xlarge" id="company-Name">@Model.Name</h1>
<div class="grid-row">
<div class="column-two-thirds">
<div style="max-width: 90%">
<div class="grid-row">
<div class="column-half">
<h3 class="heading-medium" style="margin-top: 0;">
<a href="@Url.Action("View", new { accountId = Model.Id })">Team</a>
</h3>
<p>Invite new users and manage existing ones</p>
</div>
<div class="column-half ">
<h3 class="heading-medium" style="margin-top: 0">
<a href="#">Funding</a>
</h3>
<p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p>
</div>
</div>
</div>
</div>
</div>
```
Update funding link to go to account transactions index | ```c#
@model SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account
<h1 class="heading-xlarge" id="company-Name">@Model.Name</h1>
<div class="grid-row">
<div class="column-two-thirds">
<div style="max-width: 90%">
<div class="grid-row">
<div class="column-half">
<h3 class="heading-medium" style="margin-top: 0;">
<a href="@Url.Action("View", new { accountId = Model.Id })">Team</a>
</h3>
<p>Invite new users and manage existing ones</p>
</div>
<div class="column-half ">
<h3 class="heading-medium" style="margin-top: 0">
<a href="@Url.Action("Index", "EmployerAccountTransactions", new { accountId = Model.Id })">Funding</a>
</h3>
<p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p>
</div>
</div>
</div>
</div>
</div>
``` |
a2a332bd-f091-41bb-a2b4-0bc1b3bea8ad | {
"language": "C#"
} | ```c#
namespace MadeWithLove.Middleware
{
using Owin;
public static class Extensions
{
public static void MakeWithLove(this IAppBuilder app, string customIngredient)
{
app.Use<MadeWithLoveMiddleware>(customIngredient);
}
}
}
```
Make custom ingredient optional on extension method | ```c#
namespace MadeWithLove.Middleware
{
using Owin;
public static class Extensions
{
public static void MakeWithLove(this IAppBuilder app, string customIngredient = null)
{
app.Use<MadeWithLoveMiddleware>(customIngredient);
}
}
}
``` |
96a5757c-4dad-46e8-b587-6220b532f76b | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Input;
using osu.Framework.Statistics;
namespace osu.Framework.OS
{
/// <summary>
/// A GameHost which doesn't require a graphical or sound device.
/// </summary>
public class HeadlessGameHost : BasicGameHost
{
public override GLControl GLControl => null;
public override bool IsActive => true;
public override TextInputSource TextInput => null;
protected override void DrawFrame()
{
//we can't draw.
}
public override void Run()
{
while (!ExitRequested)
{
UpdateMonitor.NewFrame();
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Scheduler))
{
UpdateScheduler.Update();
}
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Update))
{
UpdateSubTree();
using (var buffer = DrawRoots.Get(UsageType.Write))
buffer.Object = GenerateDrawNodeSubtree(buffer.Object);
}
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Sleep))
{
UpdateClock.ProcessFrame();
}
}
}
}
}
```
Add empty inputhandlers list for headless execution. | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.Statistics;
namespace osu.Framework.OS
{
/// <summary>
/// A GameHost which doesn't require a graphical or sound device.
/// </summary>
public class HeadlessGameHost : BasicGameHost
{
public override GLControl GLControl => null;
public override bool IsActive => true;
public override TextInputSource TextInput => null;
protected override void DrawFrame()
{
//we can't draw.
}
public override void Run()
{
while (!ExitRequested)
{
UpdateMonitor.NewFrame();
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Scheduler))
{
UpdateScheduler.Update();
}
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Update))
{
UpdateSubTree();
using (var buffer = DrawRoots.Get(UsageType.Write))
buffer.Object = GenerateDrawNodeSubtree(buffer.Object);
}
using (UpdateMonitor.BeginCollecting(PerformanceCollectionType.Sleep))
{
UpdateClock.ProcessFrame();
}
}
}
public override IEnumerable<InputHandler> GetInputHandlers() => new InputHandler[] { };
}
}
``` |
7ac8c212-f707-4cfd-a961-d8ee7ee88c3c | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: AssemblyProductAttribute("Gitnub: Automated Tasks for Github")]
[assembly: AssemblyCompanyAttribute("Tall Ambitions LLC")]
[assembly: AssemblyCopyrightAttribute("Copyright 2011 Tall Ambitions LLC, and contributors")]
[assembly: AssemblyVersionAttribute("0.0.0.0")]
[assembly: AssemblyFileVersionAttribute("0.0.0.0")]
[assembly: ComVisibleAttribute(false)]
[assembly: CLSCompliantAttribute(true)]
```
Increase version number to 0.1.0.0. | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: AssemblyProductAttribute("Gitnub: Automated Tasks for Github")]
[assembly: AssemblyCompanyAttribute("Tall Ambitions LLC")]
[assembly: AssemblyCopyrightAttribute("Copyright 2011 Tall Ambitions LLC, and contributors")]
[assembly: AssemblyVersionAttribute("0.1.0.0")]
[assembly: AssemblyFileVersionAttribute("0.1.0.0")]
[assembly: ComVisibleAttribute(false)]
[assembly: CLSCompliantAttribute(true)]
``` |
8a18840c-60c2-4938-bc9d-d14dd3f12825 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace LiveSplit.Model.Comparisons
{
public class StandardComparisonGeneratorsFactory : IComparisonGeneratorsFactory
{
static StandardComparisonGeneratorsFactory()
{
CompositeComparisons.AddShortComparisonName(BestSegmentsComparisonGenerator.ComparisonName, BestSegmentsComparisonGenerator.ShortComparisonName);
CompositeComparisons.AddShortComparisonName(Run.PersonalBestComparisonName, "PB");
CompositeComparisons.AddShortComparisonName(AverageSegmentsComparisonGenerator.ComparisonName, AverageSegmentsComparisonGenerator.ShortComparisonName);
CompositeComparisons.AddShortComparisonName(PercentileComparisonGenerator.ComparisonName, PercentileComparisonGenerator.ShortComparisonName);
}
public IEnumerable<IComparisonGenerator> Create(IRun run)
{
yield return new BestSegmentsComparisonGenerator(run);
yield return new AverageSegmentsComparisonGenerator(run);
}
public IEnumerable<IComparisonGenerator> GetAllGenerators(IRun run)
{
yield return new BestSegmentsComparisonGenerator(run);
yield return new BestSplitTimesComparisonGenerator(run);
yield return new AverageSegmentsComparisonGenerator(run);
yield return new WorstSegmentsComparisonGenerator(run);
yield return new PercentileComparisonGenerator(run);
yield return new NoneComparisonGenerator(run);
}
}
}
```
Add short name for Worst Segments | ```c#
using System.Collections.Generic;
namespace LiveSplit.Model.Comparisons
{
public class StandardComparisonGeneratorsFactory : IComparisonGeneratorsFactory
{
static StandardComparisonGeneratorsFactory()
{
CompositeComparisons.AddShortComparisonName(BestSegmentsComparisonGenerator.ComparisonName, BestSegmentsComparisonGenerator.ShortComparisonName);
CompositeComparisons.AddShortComparisonName(Run.PersonalBestComparisonName, "PB");
CompositeComparisons.AddShortComparisonName(AverageSegmentsComparisonGenerator.ComparisonName, AverageSegmentsComparisonGenerator.ShortComparisonName);
CompositeComparisons.AddShortComparisonName(WorstSegmentsComparisonGenerator.ComparisonName, WorstSegmentsComparisonGenerator.ShortComparisonName);
CompositeComparisons.AddShortComparisonName(PercentileComparisonGenerator.ComparisonName, PercentileComparisonGenerator.ShortComparisonName);
}
public IEnumerable<IComparisonGenerator> Create(IRun run)
{
yield return new BestSegmentsComparisonGenerator(run);
yield return new AverageSegmentsComparisonGenerator(run);
}
public IEnumerable<IComparisonGenerator> GetAllGenerators(IRun run)
{
yield return new BestSegmentsComparisonGenerator(run);
yield return new BestSplitTimesComparisonGenerator(run);
yield return new AverageSegmentsComparisonGenerator(run);
yield return new WorstSegmentsComparisonGenerator(run);
yield return new PercentileComparisonGenerator(run);
yield return new NoneComparisonGenerator(run);
}
}
}
``` |
a8978bb9-136d-4d0f-8d00-c905c90cc42a | {
"language": "C#"
} | ```c#
namespace Microsoft.ApplicationInsights.AspNetCore.Tests.ContextInitializers
{
using System;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;
using Helpers;
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.AspNetCore.Http;
using Xunit;
public class DomainNameRoleInstanceTelemetryInitializerTests
{
private const string TestListenerName = "TestListener";
[Fact]
public void RoleInstanceNameIsSetToDomainAndHost()
{
var source = new DomainNameRoleInstanceTelemetryInitializer();
var requestTelemetry = new RequestTelemetry();
source.Initialize(requestTelemetry);
string hostName = Dns.GetHostName();
#if net46
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
if (hostName.EndsWith(domainName, StringComparison.OrdinalIgnoreCase) == false)
{
hostName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", hostName, domainName);
}
#endif
Assert.Equal(hostName, requestTelemetry.Context.Cloud.RoleInstance);
}
[Fact]
public void ContextInitializerDoesNotOverrideMachineName()
{
var source = new DomainNameRoleInstanceTelemetryInitializer();
var requestTelemetry = new RequestTelemetry();
requestTelemetry.Context.Cloud.RoleInstance = "Test";
source.Initialize(requestTelemetry);
Assert.Equal("Test", requestTelemetry.Context.Cloud.RoleInstance);
}
}
}```
Correct compie time constant to be NET46 | ```c#
namespace Microsoft.ApplicationInsights.AspNetCore.Tests.ContextInitializers
{
using System;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;
using Helpers;
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.AspNetCore.Http;
using Xunit;
public class DomainNameRoleInstanceTelemetryInitializerTests
{
private const string TestListenerName = "TestListener";
[Fact]
public void RoleInstanceNameIsSetToDomainAndHost()
{
var source = new DomainNameRoleInstanceTelemetryInitializer();
var requestTelemetry = new RequestTelemetry();
source.Initialize(requestTelemetry);
string hostName = Dns.GetHostName();
#if NET46
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
if (hostName.EndsWith(domainName, StringComparison.OrdinalIgnoreCase) == false)
{
hostName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", hostName, domainName);
}
#endif
Assert.Equal(hostName, requestTelemetry.Context.Cloud.RoleInstance);
}
[Fact]
public void ContextInitializerDoesNotOverrideMachineName()
{
var source = new DomainNameRoleInstanceTelemetryInitializer();
var requestTelemetry = new RequestTelemetry();
requestTelemetry.Context.Cloud.RoleInstance = "Test";
source.Initialize(requestTelemetry);
Assert.Equal("Test", requestTelemetry.Context.Cloud.RoleInstance);
}
}
}``` |
aa44f099-2b6b-4dc8-8c1a-c975987cc6f4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicCash
{
public abstract class BaseActor
{
public string Name { get; set; }
public Guid ActorGuid { get; set; }
}
}
```
Move more stuff to superclass | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicCash
{
/// <summary>
/// The base actor abstracts all common properties of our actors (mainly Bank, Merchant, Customer)
/// </summary>
public abstract class BaseActor
{
public string Name { get; set; }
public Guid ActorGuid { get; set; }
public Int32 Money { get; set; }
public Dictionary<Guid, List<MoneyOrder>> Ledger { get; private set; }
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.