doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
4f949eb7-4c02-40f9-8740-7377652b250d | {
"language": "C#"
} | ```c#
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Phrase
{
private readonly string _phrase;
public Phrase(string phrase)
{
if (phrase == null) throw new ArgumentNullException("phrase");
_phrase = phrase;
}
public IDictionary<string, int> WordCount()
{
var counts = new Dictionary<string, int>();
Match match = Regex.Match(_phrase.ToLower(), @"\w+'\w+|\w+");
while(match.Success)
{
string word = match.Value;
if(!counts.ContainsKey(word))
{
counts[word] = 0;
}
counts[word]++;
match = match.NextMatch();
}
return counts;
}
}```
Add missing using statement in word-count | ```c#
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Phrase
{
private readonly string _phrase;
public Phrase(string phrase)
{
if (phrase == null) throw new ArgumentNullException("phrase");
_phrase = phrase;
}
public IDictionary<string, int> WordCount()
{
var counts = new Dictionary<string, int>();
Match match = Regex.Match(_phrase.ToLower(), @"\w+'\w+|\w+");
while(match.Success)
{
string word = match.Value;
if(!counts.ContainsKey(word))
{
counts[word] = 0;
}
counts[word]++;
match = match.NextMatch();
}
return counts;
}
}``` |
1c59f776-fbf3-4767-a975-2252eee995c9 | {
"language": "C#"
} | ```c#
#if DEBUG
using NUnit.Framework;
[assembly: LevelOfParallelism(4)]
[assembly: Parallelizable(ParallelScope.Fixtures)]
#endif
```
Enable tests parallelization for all build configurations | ```c#
using NUnit.Framework;
[assembly: Parallelizable(ParallelScope.Fixtures)]
``` |
1b3aa472-a2a0-45ff-8ab6-50b48a41c60f | {
"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.
using System;
using Xunit.Sdk;
namespace Xunit
{
/// <summary>
/// Apply this attribute to your test method to specify a outer-loop category.
/// </summary>
[TraitDiscoverer("Xunit.NetCore.Extensions.OuterLoopTestsDiscoverer", "Xunit.NetCore.Extensions")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class OuterLoopAttribute : Attribute, ITraitAttribute
{
public OuterLoopAttribute() { }
}
}
```
Allow OuterLoop on a class | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit.Sdk;
namespace Xunit
{
/// <summary>
/// Apply this attribute to your test method to specify a outer-loop category.
/// </summary>
[TraitDiscoverer("Xunit.NetCore.Extensions.OuterLoopTestsDiscoverer", "Xunit.NetCore.Extensions")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class OuterLoopAttribute : Attribute, ITraitAttribute
{
public OuterLoopAttribute() { }
}
}
``` |
ffe312ad-03f8-4e6a-9103-8e5d5889b2a8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CheckUp2 {
public partial class MainWindow : Form {
public MainWindow() {
InitializeComponent();
}
}
}
```
Test push for appveyor nuget restore | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CheckUp2 {
public partial class MainWindow : Form {
public MainWindow() {
InitializeComponent();
}
}
}
``` |
7ec4f28e-e65e-4300-8709-aac1a306a809 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Http;
using Mindscape.Raygun4Net.AspNetCore;
namespace Mindscape.Raygun4Net.AspNetCore2.Tests
{
public class ExampleRaygunAspNetCoreClientProvider : DefaultRaygunAspNetCoreClientProvider
{
public override AspNetCore.RaygunClient GetClient(AspNetCore.RaygunSettings settings, HttpContext context)
{
var client = base.GetClient(settings, context);
var email = "bob@raygun.com";
client.UserInfo = new RaygunIdentifierMessage(email)
{
IsAnonymous = false,
Email = email,
FullName = "Bob"
};
return client;
}
}
}```
Test adding tags in ASP.NET Core test project | ```c#
using Microsoft.AspNetCore.Http;
using Mindscape.Raygun4Net.AspNetCore;
using System.Collections.Generic;
namespace Mindscape.Raygun4Net.AspNetCore2.Tests
{
public class ExampleRaygunAspNetCoreClientProvider : DefaultRaygunAspNetCoreClientProvider
{
public override AspNetCore.RaygunClient GetClient(AspNetCore.RaygunSettings settings, HttpContext context)
{
var client = base.GetClient(settings, context);
var email = "bob@raygun.com";
client.UserInfo = new RaygunIdentifierMessage(email)
{
IsAnonymous = false,
Email = email,
FullName = "Bob"
};
client.SendingMessage += (_, args) =>
{
args.Message.Details.Tags ??= new List<string>();
args.Message.Details.Tags.Add("new tag");
};
return client;
}
}
}``` |
d19a6a3e-0565-4953-9c83-81bd3df7f617 | {
"language": "C#"
} | ```c#
namespace KInspector.Core
{
/// <summary>
/// The interface to implement to add a functionality to this application.
/// Add DLL with implementation of this interface to the same folder as executing assembly to auto-load
/// all of them.
/// </summary>
public interface IModule
{
/// <summary>
/// Returns the metadata of the module
/// </summary>
/// <example>
/// <![CDATA[
/// public ModuleMetadata GetModuleMetadata()
/// {
/// return new ModuleMetadata()
/// {
/// Name = "EventLog Information",
/// Versions = new List<string>() { "8.0", "8.1" },
/// Comment = "Checks event log for information like 404 pages and logged exceptions.",
/// ResultType = ModuleResultsType.Table
/// };
/// }
/// ]]>
/// </example>
ModuleMetadata GetModuleMetadata();
/// <summary>
/// Returns the whole result set of the module.
/// </summary>
/// <example>
/// <![CDATA[
/// public ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService)
/// {
/// var dbService = new DatabaseService(config);
/// var results = dbService.ExecuteAndGetPrintsFromFile("EventLogInfoModule.sql");
///
/// return new ModuleResults()
/// {
/// Result = results,
/// ResultComment = "Check event log for more details!"
/// };
/// }
/// ]]>
/// </example>
ModuleResults GetResults(InstanceInfo config, DatabaseService dbService);
}
}
```
Change interface parameter name to match it's type name | ```c#
namespace KInspector.Core
{
/// <summary>
/// The interface to implement to add a functionality to this application.
/// Add DLL with implementation of this interface to the same folder as executing assembly to auto-load
/// all of them.
/// </summary>
public interface IModule
{
/// <summary>
/// Returns the metadata of the module
/// </summary>
/// <example>
/// <![CDATA[
/// public ModuleMetadata GetModuleMetadata()
/// {
/// return new ModuleMetadata()
/// {
/// Name = "EventLog Information",
/// Versions = new List<string>() { "8.0", "8.1" },
/// Comment = "Checks event log for information like 404 pages and logged exceptions.",
/// ResultType = ModuleResultsType.Table
/// };
/// }
/// ]]>
/// </example>
ModuleMetadata GetModuleMetadata();
/// <summary>
/// Returns the whole result set of the module.
/// </summary>
/// <example>
/// <![CDATA[
/// public ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService)
/// {
/// var dbService = new DatabaseService(config);
/// var results = dbService.ExecuteAndGetPrintsFromFile("EventLogInfoModule.sql");
///
/// return new ModuleResults()
/// {
/// Result = results,
/// ResultComment = "Check event log for more details!"
/// };
/// }
/// ]]>
/// </example>
ModuleResults GetResults(InstanceInfo instanceInfo, DatabaseService dbService);
}
}
``` |
4dc8e12a-1c14-422b-a9aa-166888b2d1aa | {
"language": "C#"
} | ```c#
namespace Miruken.Map
{
using System;
using Callback;
using Concurrency;
public class MappingHandler : Handler, IMapping
{
public object Map(object source, object typeOrInstance,
object format = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (typeOrInstance == null)
throw new ArgumentNullException(nameof(typeOrInstance));
var mapFrom = new Mapping(source, typeOrInstance, format);
return Composer.Handle(mapFrom)
? mapFrom.Result
: Unhandled<object>();
}
public Promise MapAsync(object source, object typeOrInstance,
object format)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (typeOrInstance == null)
throw new ArgumentNullException(nameof(typeOrInstance));
var mapFrom = new Mapping(source, typeOrInstance, format)
{
WantsAsync = true
};
try
{
return Composer.Handle(mapFrom)
? (Promise)mapFrom.Result
: Unhandled<Promise>();
}
catch (Exception ex)
{
return Promise.Rejected(ex);
}
}
}
}
```
Revert "Convert mapping async exceptions to Promise" | ```c#
namespace Miruken.Map
{
using System;
using Callback;
using Concurrency;
public class MappingHandler : Handler, IMapping
{
public object Map(object source, object typeOrInstance,
object format = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (typeOrInstance == null)
throw new ArgumentNullException(nameof(typeOrInstance));
var mapFrom = new Mapping(source, typeOrInstance, format);
return Composer.Handle(mapFrom)
? mapFrom.Result
: Unhandled<object>();
}
public Promise MapAsync(object source, object typeOrInstance,
object format)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (typeOrInstance == null)
throw new ArgumentNullException(nameof(typeOrInstance));
var mapFrom = new Mapping(source, typeOrInstance, format)
{
WantsAsync = true
};
return Composer.Handle(mapFrom)
? (Promise)mapFrom.Result
: Unhandled<Promise>();
}
}
}
``` |
6cbab0ca-cd45-46e8-80b7-26c2f27bc853 | {
"language": "C#"
} | ```c#
using System;
namespace clipman.ViewModels
{
class SettingsPanelViewModel
{
public void ClearClips()
{
ClearRequested?.Invoke(this, EventArgs.Empty);
}
public event EventHandler ClearRequested;
}
}
```
Remove obsolete clip clear request code | ```c#
using System;
namespace clipman.ViewModels
{
class SettingsPanelViewModel
{
}
}
``` |
0a049661-c5d7-4527-afd0-55fff7ccdf02 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Transfiguration.Spells
{
[UsedImplicitly]
public class MiceToSnuffboxes : BaseSpell {
public override List<BaseCard> GetValidTargets()
{
var validCards = Player.InPlay.GetCreaturesInPlay();
validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay());
return validCards;
}
protected override void SpellAction(List<BaseCard> selectedCards)
{
//TODO: fix animation bugs by doing an AddAll if the selected cards belong to the same player.
foreach(var card in selectedCards) {
card.Player.Hand.Add(card, preview: false);
card.Player.InPlay.Remove(card);
}
}
}
}
```
Check if targets belong to the same player for animation purposes | ```c#
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Transfiguration.Spells
{
[UsedImplicitly]
public class MiceToSnuffboxes : BaseSpell {
public override List<BaseCard> GetValidTargets()
{
var validCards = Player.InPlay.GetCreaturesInPlay();
validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay());
return validCards;
}
protected override void SpellAction(List<BaseCard> selectedCards)
{
//Check if the cards belong to the same player and do and AddAll to prevent animation bugs
bool localPlayer = selectedCards.First().Player.IsLocalPlayer;
if (selectedCards.All(c => c.Player.IsLocalPlayer == localPlayer))
{
selectedCards.First().Player.Hand.AddAll(selectedCards);
selectedCards.First().Player.InPlay.RemoveAll(selectedCards);
}
else
{
foreach (var card in selectedCards)
{
card.Player.Hand.Add(card, preview: false);
card.Player.InPlay.Remove(card);
}
}
}
}
}
``` |
302b7fda-46f8-45fd-b099-37ce3929fcbf | {
"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.
#nullable enable
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
[return: NotNullIfNotNull("option")]
public static implicit operator CodeStyleOption<T>?(CodeStyleOption2<T>? option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption?)option.Notification);
}
[return: NotNullIfNotNull("option")]
public static implicit operator CodeStyleOption2<T>?(CodeStyleOption<T>? option)
{
return option?.UnderlyingOption;
}
}
}
```
Use explicit operators, since they are no longer used implicitly | ```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.
#nullable enable
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
[return: NotNullIfNotNull("option")]
public static explicit operator CodeStyleOption<T>?(CodeStyleOption2<T>? option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption?)option.Notification);
}
[return: NotNullIfNotNull("option")]
public static explicit operator CodeStyleOption2<T>?(CodeStyleOption<T>? option)
{
return option?.UnderlyingOption;
}
}
}
``` |
0efdbde5-4b06-4aaa-8d2c-685b73516d75 | {
"language": "C#"
} | ```c#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System.IO;
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public class TheAvifCoder
{
[Fact]
public void ShouldEncodeAndDecodeAlphaChannel()
{
using (var input = new MagickImage(Files.TestPNG))
{
input.Resize(new Percentage(15));
using (var stream = new MemoryStream())
{
input.Write(stream, MagickFormat.Avif);
stream.Position = 0;
using (var output = new MagickImage(stream))
{
Assert.True(output.HasAlpha);
Assert.Equal(MagickFormat.Avif, output.Format);
Assert.Equal(input.Width, output.Width);
Assert.Equal(input.Height, output.Height);
}
}
}
}
[Fact]
public void ShouldIgnoreEmptyExifProfile()
{
using (var image = new MagickImage(Files.Coders.EmptyExifAVIF))
{
Assert.Equal(1, image.Width);
Assert.Equal(1, image.Height);
ColorAssert.Equal(MagickColors.Magenta, image, 1, 1);
}
}
}
}
```
Test for exception for now until we can get a proper test image. | ```c#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System.IO;
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public class TheAvifCoder
{
[Fact]
public void ShouldEncodeAndDecodeAlphaChannel()
{
using (var input = new MagickImage(Files.TestPNG))
{
input.Resize(new Percentage(15));
using (var stream = new MemoryStream())
{
input.Write(stream, MagickFormat.Avif);
stream.Position = 0;
using (var output = new MagickImage(stream))
{
Assert.True(output.HasAlpha);
Assert.Equal(MagickFormat.Avif, output.Format);
Assert.Equal(input.Width, output.Width);
Assert.Equal(input.Height, output.Height);
}
}
}
}
[Fact]
public void ShouldIgnoreEmptyExifProfile()
{
using (var image = new MagickImage())
{
try
{
image.Read(Files.Coders.EmptyExifAVIF);
}
catch (MagickCorruptImageErrorException exception)
{
Assert.Contains("Invalid clean-aperture specification", exception.Message);
}
}
}
}
}
``` |
e53d1944-b3f0-4798-abdf-9861890ab91b | {
"language": "C#"
} | ```c#
using System.Collections.Immutable;
using LanguageExt;
namespace ExRam.Gremlinq.Core
{
public struct GremlinqOptions
{
private readonly IImmutableDictionary<GremlinqOption, object> _options;
public GremlinqOptions(IImmutableDictionary<GremlinqOption, object> options)
{
_options = options;
}
public TValue GetValue<TValue>(GremlinqOption<TValue> option)
{
return (_options?.TryGetValue(option))
.ToOption()
.Bind(x => x)
.Map(optionValue => (TValue)optionValue)
.IfNone(option.DefaultValue);
}
public GremlinqOptions SetValue<TValue>(GremlinqOption<TValue> option, TValue value)
{
return new GremlinqOptions(_options ?? ImmutableDictionary<GremlinqOption, object>.Empty.SetItem(option, value));
}
}
}
```
Support configuring an existing option value. | ```c#
using System;
using System.Collections.Immutable;
using LanguageExt;
namespace ExRam.Gremlinq.Core
{
public struct GremlinqOptions
{
private readonly IImmutableDictionary<GremlinqOption, object> _options;
public GremlinqOptions(IImmutableDictionary<GremlinqOption, object> options)
{
_options = options;
}
public TValue GetValue<TValue>(GremlinqOption<TValue> option)
{
return (_options?.TryGetValue(option))
.ToOption()
.Bind(x => x)
.Map(optionValue => (TValue)optionValue)
.IfNone(option.DefaultValue);
}
public GremlinqOptions SetValue<TValue>(GremlinqOption<TValue> option, TValue value)
{
return new GremlinqOptions(_options ?? ImmutableDictionary<GremlinqOption, object>.Empty.SetItem(option, value));
}
public GremlinqOptions ConfigureValue<TValue>(GremlinqOption<TValue> option, Func<TValue, TValue> configuration)
{
return SetValue(option, configuration(GetValue(option)));
}
}
}
``` |
7341b315-b1b8-4945-954c-1065f8697940 | {
"language": "C#"
} | ```c#
using System;
using Csla;
using Csla.Serialization;
namespace Csla.Security
{
/// <summary>
/// Criteria class for passing a
/// username/password pair to a
/// custom identity class.
/// </summary>
[Serializable]
public class UsernameCriteria : CriteriaBase
{
/// <summary>
/// Username property definition.
/// </summary>
public static PropertyInfo<string> UsernameProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Username", "Username"));
/// <summary>
/// Gets the username.
/// </summary>
public string Username
{
get { return ReadProperty(UsernameProperty); }
private set { LoadProperty(UsernameProperty, value); }
}
/// <summary>
/// Password property definition.
/// </summary>
public static PropertyInfo<string> PasswordProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Password", "Password"));
/// <summary>
/// Gets the password.
/// </summary>
public string Password
{
get { return ReadProperty(PasswordProperty); }
private set { LoadProperty(PasswordProperty, value); }
}
/// <summary>
/// Creates a new instance of the object.
/// </summary>
/// <param name="username">
/// Username value.
/// </param>
/// <param name="password">
/// Password value.
/// </param>
public UsernameCriteria(string username, string password)
{
this.Username = username;
this.Password = password;
}
}
}```
Add default ctor to class. bugid: 417 | ```c#
using System;
using Csla;
using Csla.Serialization;
namespace Csla.Security
{
/// <summary>
/// Criteria class for passing a
/// username/password pair to a
/// custom identity class.
/// </summary>
[Serializable]
public class UsernameCriteria : CriteriaBase
{
/// <summary>
/// Username property definition.
/// </summary>
public static PropertyInfo<string> UsernameProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Username", "Username"));
/// <summary>
/// Gets the username.
/// </summary>
public string Username
{
get { return ReadProperty(UsernameProperty); }
private set { LoadProperty(UsernameProperty, value); }
}
/// <summary>
/// Password property definition.
/// </summary>
public static PropertyInfo<string> PasswordProperty = RegisterProperty(typeof(UsernameCriteria), new PropertyInfo<string>("Password", "Password"));
/// <summary>
/// Gets the password.
/// </summary>
public string Password
{
get { return ReadProperty(PasswordProperty); }
private set { LoadProperty(PasswordProperty, value); }
}
/// <summary>
/// Creates a new instance of the object.
/// </summary>
/// <param name="username">
/// Username value.
/// </param>
/// <param name="password">
/// Password value.
/// </param>
public UsernameCriteria(string username, string password)
{
this.Username = username;
this.Password = password;
}
/// <summary>
/// Creates a new instance of the object.
/// </summary>
#if SILVERLIGHT
public UsernameCriteria()
{ }
#else
protected UsernameCriteria()
{ }
#endif
}
}``` |
42b374aa-2ab5-48c5-bc26-cc2ed9c14d9c | {
"language": "C#"
} | ```c#
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
private readonly IFixture _fixture;
public CreateCommandTest()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
}
[Theory, AutoCommandData]
public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command)
{
command.Execute(new string[] { "foo", "bar" });
client.Verify(x => x.CreateApplication("foo", "bar"), Times.Once());
}
}
}
```
Use AutoFixture for injecting argument string array | ```c#
using System.Linq;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
private readonly IFixture _fixture;
public CreateCommandTest()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
}
[Theory, AutoCommandData]
public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command, string[] arguments)
{
command.Execute(arguments);
client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once());
}
}
}
``` |
33969296-c2f7-4d6b-a83a-64397831f265 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Version = Msg.Core.Versioning;
namespace Msg.Core.Versioning
{
public static class VersionNegotiator
{
[System.Obsolete("This method is deprecated us VersionNegotiator.Select instead.")]
public static async Task<Version> NegotiateVersionAsync (IEnumerable<VersionRange> supportedVersions)
{
return await Task.FromResult (supportedVersions.First ().UpperBoundInclusive);
}
public static Version Select (ClientVersion client, ServerSupportedVersions server)
{
return new ServerVersion(0,0,0);
}
}
}
```
Return the highest supported version except where equal to the client version. | ```c#
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Version = Msg.Core.Versioning;
namespace Msg.Core.Versioning
{
public static class VersionNegotiator
{
[System.Obsolete("This method is deprecated us VersionNegotiator.Select instead.")]
public static async Task<Version> NegotiateVersionAsync (IEnumerable<VersionRange> supportedVersions)
{
return await Task.FromResult (supportedVersions.First ().UpperBoundInclusive);
}
public static Version Select (ClientVersion clientVersion, ServerSupportedVersions serverSupportedVersions)
{
var serverVersion = GetDefaultServerVersion (serverSupportedVersions);
return clientVersion == serverVersion ? new AcceptedVersion (clientVersion) : serverVersion;
}
static ServerVersion GetDefaultServerVersion (IEnumerable<VersionRange> supportedVersions)
{
var highestSupportedVersion = supportedVersions
.OrderBy (x => x.UpperBoundInclusive)
.First ()
.UpperBoundInclusive;
return new ServerVersion (highestSupportedVersion.Major, highestSupportedVersion.Minor, highestSupportedVersion.Revision);
}
}
}
``` |
039996d7-8de0-4841-aad5-f3735948f98c | {
"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 Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
/// <summary>
/// Complexify makes inferred names explicit for tuple elements and anonymous type members. This
/// class considers which ones of those can be simplified (after the refactoring was done).
/// If the inferred name of the member matches, the explicit name (from Complexify) can be removed.
/// </summary>
internal partial class CSharpInferredMemberNameReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new ObjectPool<IReductionRewriter>(
() => new Rewriter(s_pool));
public CSharpInferredMemberNameReducer() : base(s_pool)
{
}
}
}
```
Remove unused usings from a newly added file | ```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 Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
/// <summary>
/// Complexify makes inferred names explicit for tuple elements and anonymous type members. This
/// class considers which ones of those can be simplified (after the refactoring was done).
/// If the inferred name of the member matches, the explicit name (from Complexify) can be removed.
/// </summary>
internal partial class CSharpInferredMemberNameReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new ObjectPool<IReductionRewriter>(
() => new Rewriter(s_pool));
public CSharpInferredMemberNameReducer() : base(s_pool)
{
}
}
}
``` |
c7125534-eb89-47fe-baae-b13528b19678 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using JetBrains.Annotations;
namespace EnsureThat
{
public static class Ensure
{
public static bool IsActive { get; private set; } = true;
public static void Off() => IsActive = false;
public static void On() => IsActive = true;
[DebuggerStepThrough]
public static Param<T> That<T>([NoEnumeration]T value, string name = Param.DefaultName) => new Param<T>(name, value);
[DebuggerStepThrough]
public static Param<T> That<T>(Func<T> expression, string name = Param.DefaultName) => new Param<T>(
name,
expression.Invoke());
[DebuggerStepThrough]
public static TypeParam ThatTypeFor<T>(T value, string name = Param.DefaultName) => new TypeParam(name, value.GetType());
}
}```
Mark as obsolete for future removal | ```c#
using System;
using System.Diagnostics;
using JetBrains.Annotations;
namespace EnsureThat
{
public static class Ensure
{
public static bool IsActive { get; private set; } = true;
public static void Off() => IsActive = false;
public static void On() => IsActive = true;
[DebuggerStepThrough]
[Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)]
public static Param<T> That<T>([NoEnumeration]T value, string name = Param.DefaultName) => new Param<T>(name, value);
[DebuggerStepThrough]
[Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)]
public static Param<T> That<T>(Func<T> expression, string name = Param.DefaultName) => new Param<T>(
name,
expression.Invoke());
[DebuggerStepThrough]
[Obsolete("Use EnsureArg instead. This version will eventually be removed.", false)]
public static TypeParam ThatTypeFor<T>(T value, string name = Param.DefaultName) => new TypeParam(name, value.GetType());
}
}``` |
ba9c9df5-62cb-49a4-ab2c-7528b7e23636 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Garlic")]
[assembly: AssemblyDescription("Google Analytics Client for .Net")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Dusty Burwell")]
[assembly: AssemblyProduct("Garlic Google Analytics Client")]
[assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Change version due to API Change | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Garlic")]
[assembly: AssemblyDescription("Google Analytics Client for .Net")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Dusty Burwell")]
[assembly: AssemblyProduct("Garlic Google Analytics Client")]
[assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
``` |
1328b5fe-6bc2-4032-aa30-642bff70707b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace CIV.Processes
{
public static class Extensions
{
/// <summary>
/// Coaction of the specified action.
/// </summary>
/// <returns>The coaction: 'action if action does not start
/// with ' and vice versa</returns>
/// <param name="action">A CCS action</param>
public static String Coaction(this String action)
{
return action.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) ?
action.Substring(1) : String.Format("'{0}", action);
}
public static IEnumerable<Transition> WeakTransitions(this IProcess process)
{
var transitions = process.Transitions();
var result = (
from t in transitions
where t.Label != "tau"
select t
);
foreach(var t in transitions.Where(x => x.Label == "tau"))
{
result.Concat(t.Process.WeakTransitions());
}
return result;
}
}
}
```
Fix Coaction() for tau action | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace CIV.Processes
{
public static class Extensions
{
/// <summary>
/// Coaction of the specified action.
/// </summary>
/// <returns>The coaction: 'action if action does not start
/// with ' and vice versa</returns>
/// <param name="action">A CCS action</param>
public static String Coaction(this String action)
{
if (action == "tau") return "tau";
return action.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) ?
action.Substring(1) : String.Format("'{0}", action);
}
public static IEnumerable<Transition> WeakTransitions(this IProcess process)
{
var transitions = process.Transitions();
var result = (
from t in transitions
where t.Label != "tau"
select t
);
foreach(var t in transitions.Where(x => x.Label == "tau"))
{
result.Concat(t.Process.WeakTransitions());
}
return result;
}
}
}
``` |
7f04145c-860a-4f48-9f7a-eca96a6a4d31 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Perf.DiffPlex
{
public class PerfTester
{
public void Run(Action action)
{
const double count = 5;
var times = new List<double>();
var timer = new Stopwatch();
var totalTime = new Stopwatch();
double maxTime = 0;
double minTime = double.MaxValue;
Console.WriteLine();
Console.WriteLine("Time before run: {0}", DateTime.Now);
Console.WriteLine("Running {0} times.", count);
totalTime.Start();
for (var i = 0; i < count; i++)
{
timer.Start();
action();
timer.Stop();
maxTime = Math.Max(maxTime, timer.ElapsedMilliseconds);
minTime = Math.Min(minTime, timer.ElapsedMilliseconds);
times.Add(timer.ElapsedMilliseconds);
timer.Reset();
}
totalTime.Stop();
Console.WriteLine();
Console.WriteLine("Time after run: {0}", DateTime.Now);
Console.WriteLine("Elapsed: {0}ms", totalTime.ElapsedMilliseconds);
Console.WriteLine("Diffs Per Second: {0}", (count / totalTime.ElapsedMilliseconds) * 1000);
Console.WriteLine("Average: {0}ms", times.Average());
Console.WriteLine("Max time for a call: {0}ms", maxTime);
Console.WriteLine("Min time for a call: {0}ms", minTime);
}
}
}
```
Make sure code is jitted before perf test | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Perf.DiffPlex
{
public class PerfTester
{
public void Run(Action action)
{
const double count = 5;
var times = new List<double>();
var timer = new Stopwatch();
var totalTime = new Stopwatch();
double maxTime = 0;
double minTime = double.MaxValue;
Console.WriteLine("Ensuring code is Jitted");
action();
Console.WriteLine();
Console.WriteLine("Time before run: {0}", DateTime.Now);
Console.WriteLine("Running {0} times.", count);
totalTime.Start();
for (var i = 0; i < count; i++)
{
timer.Start();
action();
timer.Stop();
maxTime = Math.Max(maxTime, timer.ElapsedMilliseconds);
minTime = Math.Min(minTime, timer.ElapsedMilliseconds);
times.Add(timer.ElapsedMilliseconds);
timer.Reset();
}
totalTime.Stop();
Console.WriteLine();
Console.WriteLine("Time after run: {0}", DateTime.Now);
Console.WriteLine("Elapsed: {0}ms", totalTime.ElapsedMilliseconds);
Console.WriteLine("Diffs Per Second: {0}", (count / totalTime.ElapsedMilliseconds) * 1000);
Console.WriteLine("Average: {0}ms", times.Average());
Console.WriteLine("Max time for a call: {0}ms", maxTime);
Console.WriteLine("Min time for a call: {0}ms", minTime);
}
}
}
``` |
02e522b5-60b3-4f8d-a468-e2591368fd57 | {
"language": "C#"
} | ```c#
namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison = null)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result != ComparisonResult.Fail;
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison = null)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
throw new DeepEqualException(context);
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
}```
Use overloads instead of optional parameters | ```c#
namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected)
{
return IsDeepEqual(actual, expected, null);
}
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result != ComparisonResult.Fail;
}
public static void ShouldDeepEqual(this object actual, object expected)
{
ShouldDeepEqual(actual, expected, null);
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison)
{
comparison = comparison ?? new ComparisonBuilder().Create();
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
throw new DeepEqualException(context);
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
}``` |
74b0ea6c-53a5-4ac5-9ad1-50907c503a63 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using QuantConnect.Logging;
[SetUpFixture]
public class AssemblyInitialize
{
[SetUp]
public void SetLogHandler()
{
// save output to file as well
Log.LogHandler = new CompositeLogHandler();
}
}
```
Make tests use console log handler | ```c#
using NUnit.Framework;
using QuantConnect.Logging;
[SetUpFixture]
public class AssemblyInitialize
{
[SetUp]
public void SetLogHandler()
{
// save output to file as well
Log.LogHandler = new ConsoleLogHandler();
}
}
``` |
696742a6-5f89-44cf-a2ab-b99606936568 | {
"language": "C#"
} | ```c#
namespace Hiperion.Infrastructure.Ioc
{
#region References
using System.Configuration;
using System.Web.Http;
using AutoMapper;
using Automapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using EF;
using EF.Interfaces;
using Mappings;
#endregion
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString;
container.Register(
Component.For<IMappingEngine>()
.Instance(Mapper.Engine),
Component.For<IDbContext>()
.ImplementedBy<HiperionDbContext>()
.LifestylePerWebRequest()
.DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)),
Component.For(typeof (EntityResolver<>))
.ImplementedBy(typeof (EntityResolver<>))
.LifestyleTransient(),
Component.For(typeof (ManyToManyEntityResolver<,>))
.ImplementedBy(typeof (ManyToManyEntityResolver<,>))
.LifestyleTransient(),
Types.FromThisAssembly()
.Where(type => (type.Name.EndsWith("Services") ||
type.Name.EndsWith("Repository") ||
type.Name.EndsWith("Resolver") ||
type.Name.EndsWith("Controller")) && type.IsClass)
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
AutomapperConfiguration.Configure(container.Resolve);
GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container);
}
}
}```
Fix for automapper castle component | ```c#
namespace Hiperion.Infrastructure.Ioc
{
#region References
using System.Configuration;
using System.Web.Http;
using AutoMapper;
using Automapper;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using EF;
using EF.Interfaces;
using Mappings;
#endregion
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var connectionString = ConfigurationManager.ConnectionStrings["HiperionDb"].ConnectionString;
container.Register(
Component.For<IMappingEngine>()
.UsingFactoryMethod(() => Mapper.Engine),
Component.For<IDbContext>()
.ImplementedBy<HiperionDbContext>()
.LifestylePerWebRequest()
.DependsOn(Parameter.ForKey("connectionString").Eq(connectionString)),
Component.For(typeof (EntityResolver<>))
.ImplementedBy(typeof (EntityResolver<>))
.LifestyleTransient(),
Component.For(typeof (ManyToManyEntityResolver<,>))
.ImplementedBy(typeof (ManyToManyEntityResolver<,>))
.LifestyleTransient(),
Types.FromThisAssembly()
.Where(type => (type.Name.EndsWith("Services") ||
type.Name.EndsWith("Repository") ||
type.Name.EndsWith("Resolver") ||
type.Name.EndsWith("Controller")) && type.IsClass)
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
AutomapperConfiguration.Configure(container.Resolve);
GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(container);
}
}
}``` |
3d19391a-d4d5-45ef-b6d2-6ccbe4081e5c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace SoapCore
{
/// <summary>
/// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc
/// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner());
/// </summary>
public class TrailingServicePathTuner
{
public void ConvertPath(HttpContext httpContext)
{
string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/'));
httpContext.Request.Path = new PathString(trailingPath);
}
}
}
```
Make ConvertPath to allow this functionality to be modified to allow for slashes in path | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace SoapCore
{
/// <summary>
/// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc
/// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner());
/// </summary>
public class TrailingServicePathTuner
{
public virtual void ConvertPath(HttpContext httpContext)
{
string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/'));
httpContext.Request.Path = new PathString(trailingPath);
}
}
}
``` |
06c51e1c-e383-4e60-b712-39b6fa093f7b | {
"language": "C#"
} | ```c#
namespace GiveCRM.ImportExport
{
public class ExcelImport
{
}
}```
Revert "Revert "Modified the Import class"" | ```c#
using NPOI;
namespace GiveCRM.ImportExport
{
public class ExcelImport
{
}
}``` |
eb3d1daf-0cd1-40da-affc-8ae6fed977c2 | {
"language": "C#"
} | ```c#
//
// IRegisterablePhotoSource.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Tripod.Model
{
public interface ICacheablePhotoSource : IPhotoSource
{
void Initialize (string data);
string InitializationData { get; }
}
}
```
Fix rename which monodevelop missed. | ```c#
//
// ICacheablePhotoSource.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Tripod.Model
{
public interface ICacheablePhotoSource : IPhotoSource
{
void Initialize (string data);
string InitializationData { get; }
}
}
``` |
c75d743b-3515-4e3b-972e-b0a24d696aa1 | {
"language": "C#"
} | ```c#
using System;
using DSL;
namespace Revenj.Http
{
static class Program
{
static void Main(string[] args)
{
var server = Platform.Start<HttpServer>();
Console.WriteLine("Starting server");
server.Run();
}
}
}
```
Allow settings custom command line params. | ```c#
using System;
using System.Configuration;
using DSL;
namespace Revenj.Http
{
static class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
var i = arg.IndexOf('=');
if (i != -1)
{
var name = arg.Substring(0, i);
var value = arg.Substring(i + 1);
ConfigurationManager.AppSettings[name] = value;
}
}
var server = Platform.Start<HttpServer>();
Console.WriteLine("Starting server");
server.Run();
}
}
}
``` |
f7755795-f077-4c10-888f-76220d3056d6 | {
"language": "C#"
} | ```c#
// <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Variables
{
/// <summary>This class contains parameterized unit tests for ValSimple</summary>
[TestClass]
public partial class ValSimpleTest
{
#if false
/// <summary>Test stub for .ctor(String)</summary>
[PexMethod]
internal ValSimple Constructor(string v)
{
ValSimple target = new ValSimple(v, typeof(int));
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
return target;
}
[PexMethod]
internal ValSimple TestCTorWithType(string v, Type t)
{
ValSimple target = new ValSimple(v, t);
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
Assert.IsNotNull(target.Type, "Expected some value for the type!");
return target;
}
#endif
}
}
```
Check that a particular replacement is working well | ```c#
// <copyright file="ValSimpleTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Variables
{
/// <summary>This class contains parameterized unit tests for ValSimple</summary>
[TestClass]
public partial class ValSimpleTest
{
#if false
/// <summary>Test stub for .ctor(String)</summary>
[PexMethod]
internal ValSimple Constructor(string v)
{
ValSimple target = new ValSimple(v, typeof(int));
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
return target;
}
[PexMethod]
internal ValSimple TestCTorWithType(string v, Type t)
{
ValSimple target = new ValSimple(v, t);
Assert.AreEqual(v, target.RawValue, "Should have been set to the same thing!");
Assert.IsNotNull(target.Type, "Expected some value for the type!");
return target;
}
#endif
[TestMethod]
public void RenameMethodCall()
{
var target = new ValSimple("(*aNTH1F_1233).Fill(((double)aInt32_326),1.0*((1.0*1.0)*1.0))", typeof(int));
target.RenameRawValue("aInt32_326", "aInt32_37");
Assert.AreEqual("(*aNTH1F_1233).Fill(((double)aInt32_37),1.0*((1.0*1.0)*1.0))", target.RawValue);
}
}
}
``` |
c888d06a-e3dd-4312-816c-1bb60fcd0c96 | {
"language": "C#"
} | ```c#
using System;
namespace MySql.Data
{
internal static class Utility
{
public static void Dispose<T>(ref T disposable)
where T : class, IDisposable
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
}
}
}
}
```
Add extension to decode a string from an ArraySegment<byte>. | ```c#
using System;
using System.Text;
namespace MySql.Data
{
internal static class Utility
{
public static void Dispose<T>(ref T disposable)
where T : class, IDisposable
{
if (disposable != null)
{
disposable.Dispose();
disposable = null;
}
}
public static string GetString(this Encoding encoding, ArraySegment<byte> arraySegment)
=> encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
}
}
``` |
c36ee9db-9cc1-424b-8b19-aac8722de1d0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
/// <summary>Commands for the IRC Connection Holdable.</summary>
public static class IRCConnectionManagerCommands
{
[Command(@"disconnect")]
public static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable)
{
bool allowed = false;
yield return null;
yield return new object[]
{
"streamer",
new Action(() =>
{
allowed = true;
holdable.ConnectButton.OnInteract();
holdable.ConnectButton.OnInteractEnded();
}),
new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform))
};
if (!allowed)
yield return "sendtochaterror only the streamer may use the IRC disconnect button.";
}
}
```
Fix IRC Manager disconnect command | ```c#
using System;
using System.Collections;
/// <summary>Commands for the IRC Connection Holdable.</summary>
public static class IRCConnectionManagerCommands
{
[Command(@"disconnect")]
public static IEnumerator Disconnect(TwitchHoldable holdable, string user, bool isWhisper) =>
holdable.RespondToCommand(user, string.Empty, isWhisper, Disconnect(holdable.Holdable.GetComponent<IRCConnectionManagerHoldable>()));
private static IEnumerator Disconnect(IRCConnectionManagerHoldable holdable)
{
bool allowed = false;
yield return null;
yield return new object[]
{
"streamer",
new Action(() =>
{
allowed = true;
holdable.ConnectButton.OnInteract();
holdable.ConnectButton.OnInteractEnded();
}),
new Action(() => Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, holdable.transform))
};
if (!allowed)
yield return "sendtochaterror only the streamer may use the IRC disconnect button.";
}
}
``` |
a5437024-c8d4-47ab-be2b-d46009f81c2b | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Encodings.Web;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="IServiceCollection"/>.
/// </summary>
public static class RoutingServiceCollectionExtensions
{
public static IServiceCollection AddRouting(this IServiceCollection services)
{
return AddRouting(services, configureOptions: null);
}
public static IServiceCollection AddRouting(
this IServiceCollection services,
Action<RouteOptions> configureOptions)
{
services.AddOptions();
services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>();
services.TryAddSingleton(UrlEncoder.Default);
services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider());
services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s =>
{
var provider = s.GetRequiredService<ObjectPoolProvider>();
var encoder = s.GetRequiredService<UrlEncoder>();
return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder));
});
if (configureOptions != null)
{
services.Configure(configureOptions);
}
return services;
}
}
}```
Remove redundant AddOptions which is now a default hosting service | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Encodings.Web;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="IServiceCollection"/>.
/// </summary>
public static class RoutingServiceCollectionExtensions
{
public static IServiceCollection AddRouting(this IServiceCollection services)
{
return AddRouting(services, configureOptions: null);
}
public static IServiceCollection AddRouting(
this IServiceCollection services,
Action<RouteOptions> configureOptions)
{
services.TryAddTransient<IInlineConstraintResolver, DefaultInlineConstraintResolver>();
services.TryAddSingleton(UrlEncoder.Default);
services.TryAddSingleton<ObjectPoolProvider>(new DefaultObjectPoolProvider());
services.TryAddSingleton<ObjectPool<UriBuildingContext>>(s =>
{
var provider = s.GetRequiredService<ObjectPoolProvider>();
var encoder = s.GetRequiredService<UrlEncoder>();
return provider.Create<UriBuildingContext>(new UriBuilderContextPooledObjectPolicy(encoder));
});
if (configureOptions != null)
{
services.Configure(configureOptions);
}
return services;
}
}
}``` |
a69e5ae7-4966-40fd-84e0-4eb716a40e68 | {
"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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Edit.Compose.Components.Timeline;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimelineTickDisplay : TimelineTestScene
{
public override Drawable CreateTestComponent() => new TimelineTickDisplay();
[BackgroundDependencyLoader]
private void load()
{
BeatDivisor.Value = 4;
Add(new BeatDivisorControl(BeatDivisor)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding(30),
Size = new Vector2(90)
});
}
}
}
```
Fix timeline tick display test making two instances of the component | ```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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimelineTickDisplay : TimelineTestScene
{
public override Drawable CreateTestComponent() => Empty(); // tick display is implicitly inside the timeline.
[BackgroundDependencyLoader]
private void load()
{
BeatDivisor.Value = 4;
Add(new BeatDivisorControl(BeatDivisor)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding(30),
Size = new Vector2(90)
});
}
}
}
``` |
cab85543-32fd-4587-8792-1ec0a7f7c928 | {
"language": "C#"
} | ```c#
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Base class for making EasyButtons work
/// </summary>
public abstract class ButtonEditorBase : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
{
method.Invoke(target, null);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
/// <summary>
/// Custom inspector for MonoBehaviour including derived classes.
/// </summary>
[CustomEditor(typeof(MonoBehaviour), true)]
public class MonoBehaviourEditor : ButtonEditorBase { }
/// <summary>
/// Custom inspector for ScriptableObject including derived classes.
/// </summary>
[CustomEditor(typeof(ScriptableObject), true)]
public class ScriptableObjectEditor : ButtonEditorBase { }
}
```
Simplify the editor to work for any object | ```c#
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Custom inspector for Object including derived classes.
/// </summary>
[CustomEditor(typeof(Object), true)]
public class ObjectEditor : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
{
method.Invoke(target, null);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
}
``` |
c4b680df-9e59-4051-8225-1b26faba904a | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]```
Update assembly version to 1.0 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]``` |
5ffda4bf-c611-4501-b345-4e58c6cfb29f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerUsers.Application
{
public class InvalidRequestException : Exception
{
public Dictionary<string,string> ErrorMessages { get; private set; }
public InvalidRequestException(Dictionary<string,string> errorMessages)
: base(BuildErrorMessage(errorMessages))
{
this.ErrorMessages = errorMessages;
}
private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
{
return "Request is invalid:\n"
+ errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
}
}
}
```
Fix error message building when no specific errors defined | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace SFA.DAS.EmployerUsers.Application
{
public class InvalidRequestException : Exception
{
public Dictionary<string, string> ErrorMessages { get; private set; }
public InvalidRequestException(Dictionary<string, string> errorMessages)
: base(BuildErrorMessage(errorMessages))
{
this.ErrorMessages = errorMessages;
}
private static string BuildErrorMessage(Dictionary<string, string> errorMessages)
{
if (errorMessages.Count == 0)
{
return "Request is invalid";
}
return "Request is invalid:\n"
+ errorMessages.Select(kvp => $"{kvp.Key}: {kvp.Value}").Aggregate((x, y) => $"{x}\n{y}");
}
}
}
``` |
70291410-1162-4291-a4d0-90922ffc4119 | {
"language": "C#"
} | ```c#
using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<td>Shortcut</td>");
output.AppendLine("<td>Name</td>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
```
Change HTML table header generation to use the correct th HTML tag. | ```c#
using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<th>Shortcut</th>");
output.AppendLine("<th>Name</th>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
``` |
40a5210d-039f-48fa-9959-7279cdf31a31 | {
"language": "C#"
} | ```c#
using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;
namespace Kudu.FunctionalTests
{
public class GitStabilityTests
{
[Fact]
public void NSimpleDeployments()
{
string repositoryName = "HelloKudu";
string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
using (Git.Clone(repositoryName, cloneUrl))
{
for (int i = 0; i < 5; i++)
{
string applicationName = repositoryName + i;
ApplicationManager.Run(applicationName, appManager =>
{
// Act
appManager.AssertGitDeploy(repositoryName);
var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();
// Assert
Assert.Equal(1, results.Count);
Assert.Equal(DeployStatus.Success, results[0].Status);
KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
});
}
}
}
}
}
```
Use random app name to avoid 409 conflict error | ```c#
using System.Linq;
using Kudu.Core.Deployment;
using Kudu.FunctionalTests.Infrastructure;
using Kudu.TestHarness;
using Xunit;
namespace Kudu.FunctionalTests
{
public class GitStabilityTests
{
[Fact]
public void NSimpleDeployments()
{
string repositoryName = "HelloKudu";
string cloneUrl = "https://github.com/KuduApps/HelloKudu.git";
using (Git.Clone(repositoryName, cloneUrl))
{
for (int i = 0; i < 5; i++)
{
string applicationName = KuduUtils.GetRandomWebsiteName(repositoryName + i);
ApplicationManager.Run(applicationName, appManager =>
{
// Act
appManager.AssertGitDeploy(repositoryName);
var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList();
// Assert
Assert.Equal(1, results.Count);
Assert.Equal(DeployStatus.Success, results[0].Status);
KuduAssert.VerifyUrl(appManager.SiteUrl, "Hello Kudu");
});
}
}
}
}
}
``` |
77dbed29-3773-44ef-88fc-6f36cf955dbd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
{
yield break;
}
string[] files = null;
string[] directories = null;
try
{
// Get the files and directories now so we can get any exceptions up front
files = Directory.GetFiles(path, searchPattern);
directories = Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", path));
yield break;
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
yield break;
}
foreach (var file in files)
{
yield return file;
}
foreach (var file in directories.SelectMany(x => SafeEnumerateFiles(x, searchPattern)))
{
yield return file;
}
}
}
}
```
Replace recursive file enumeration with a stack based approach | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
allFiles = allFiles.Concat(GetFiles(current, pattern));
foreach (var subdirectory in GetSubdirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
}
return allFiles;
}
private IEnumerable<string> GetFiles(string path, string pattern)
{
try
{
return Directory.EnumerateFiles(path, pattern, SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
private IEnumerable<string> GetSubdirectories(string path)
{
try
{
return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
}
}
``` |
2288138c-9936-4de9-a749-ef83fa8b9d74 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;
namespace NRules.Integration.Autofac
{
/// <summary>
/// Rule activator that uses Autofac DI container.
/// </summary>
public class AutofacRuleActivator : IRuleActivator
{
private readonly ILifetimeScope _container;
public AutofacRuleActivator(ILifetimeScope container)
{
_container = container;
}
public IEnumerable<Rule> Activate(Type type)
{
if (_container.IsRegistered(type))
yield return (Rule) _container.Resolve(type);
yield return (Rule)Activator.CreateInstance(type);
}
}
}```
Allow multiple rule instances in autofac activator | ```c#
using System;
using System.Collections.Generic;
using Autofac;
using NRules.Fluent;
using NRules.Fluent.Dsl;
namespace NRules.Integration.Autofac
{
/// <summary>
/// Rule activator that uses Autofac DI container.
/// </summary>
public class AutofacRuleActivator : IRuleActivator
{
private readonly ILifetimeScope _container;
public AutofacRuleActivator(ILifetimeScope container)
{
_container = container;
}
public IEnumerable<Rule> Activate(Type type)
{
if (_container.IsRegistered(type))
{
var collectionType = typeof (IEnumerable<>).MakeGenericType(type);
return (IEnumerable<Rule>)_container.Resolve(collectionType);
}
return ActivateDefault(type);
}
private static IEnumerable<Rule> ActivateDefault(Type type)
{
yield return (Rule) Activator.CreateInstance(type);
}
}
}``` |
6517f553-03be-48cb-ae43-42804bbc417d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException("file");
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(String pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public String ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
```
Use nameof operator instead of magic string. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(String pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public String ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
``` |
a744d66a-7e84-43cc-a00a-8c2b7a7934d8 | {
"language": "C#"
} | ```c#
namespace Nett.Extensions
{
using System;
internal static class GenericExtensions
{
public static T CheckNotNull<T>(this T toCheck, string argName)
where T : class
{
if (toCheck == null) { throw new ArgumentNullException(nameof(argName)); }
return toCheck;
}
}
}
```
Fix that check not null message didn't contain argument name | ```c#
namespace Nett.Extensions
{
using System;
internal static class GenericExtensions
{
public static T CheckNotNull<T>(this T toCheck, string argName)
where T : class
{
if (toCheck == null) { throw new ArgumentNullException(argName); }
return toCheck;
}
}
}
``` |
9bd32c15-cdc3-4504-b348-39ffd7347717 | {
"language": "C#"
} | ```c#
using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageResizer.Sitecore.Plugin
{
public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
{
public IPlugin Install(global::ImageResizer.Configuration.Config c)
{
c.Plugins.add_plugin(this);
return this;
}
public bool Uninstall(global::ImageResizer.Configuration.Config c)
{
c.Plugins.remove_plugin(this);
return true;
}
private string FixVirtualPath(string virtualPath)
{
var subIndex = virtualPath.LastIndexOf("~");
if (subIndex < 0)
{
subIndex = virtualPath.LastIndexOf("-");
}
if (subIndex > 0)
{
return virtualPath.Substring(subIndex);
}
else
{
return virtualPath;
}
}
public bool FileExists(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
DynamicLink dynamicLink;
return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
}
public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
return new SitecoreVirtualFile(virtualPath);
}
}
}
```
Fix to the browse images coming up 404. | ```c#
using ImageResizer.Plugins;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageResizer.Sitecore.Plugin
{
public class SitecoreVirtualImageProviderPlugin : IPlugin, IVirtualImageProvider
{
public IPlugin Install(global::ImageResizer.Configuration.Config c)
{
c.Plugins.add_plugin(this);
return this;
}
public bool Uninstall(global::ImageResizer.Configuration.Config c)
{
c.Plugins.remove_plugin(this);
return true;
}
private string FixVirtualPath(string virtualPath)
{
var subIndex = virtualPath.LastIndexOf("~");
if (subIndex < 0)
{
subIndex = virtualPath.LastIndexOf("-");
}
if (subIndex > 0)
{
return virtualPath.Substring(subIndex);
}
else
{
return virtualPath;
}
}
public bool FileExists(string virtualPath, NameValueCollection queryString)
{
if (virtualPath.StartsWith("/sitecore/shell/-"))
{
return false;
}
virtualPath = FixVirtualPath(virtualPath);
DynamicLink dynamicLink;
return queryString.Count > 0 && DynamicLink.TryParse(virtualPath, out dynamicLink);
}
public IVirtualFile GetFile(string virtualPath, NameValueCollection queryString)
{
virtualPath = FixVirtualPath(virtualPath);
return new SitecoreVirtualFile(virtualPath);
}
}
}
``` |
24771728-4496-4cdf-9eca-482c8ff5bb73 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MemberProperty : MonoBehaviour {
public float E, I, length;
public int number;
}
```
Use type to find E I | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MemberProperty : MonoBehaviour {
public float length;
public int number,type;
float[] E = { 1 };
float[] I = { 1 };
public float GetI()
{
return I[type];
}
public float GetE()
{
return E[type];
}
}
``` |
b8728524-f25d-4bed-aa3f-160ded7e4803 | {
"language": "C#"
} | ```c#
using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;
namespace Schedules.API.Tasks
{
public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
{
public FetchReminderType FetchReminderType { get; set; }
public class Input
{
public Reminder Reminder { get; set; }
public String ReminderTypeName { get; set; }
}
public class Output
{
public Reminder Reminder { get; set; }
}
public override void Execute()
{
FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
FetchReminderType.Execute();
In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;
Out.Reminder = new Reminder ();
using (var connection = Db.Connect ()) {
try{
Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
sql,
(reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
In.Reminder).SingleOrDefault();
}
catch(Exception ex){
Console.WriteLine (ex);
}
}
}
const string sql = @"
with insertReminder as (
insert into Reminders(contact, message, verified, address, reminder_type_id)
values(@Contact, @Message, @Verified, @Address, @ReminderTypeId) returning *
)
select *
from insertReminder r
left join reminder_types t
on t.id = r.reminder_type_id
;
";
}
}
```
Add remind_on to insert statement | ```c#
using System;
using Simpler;
using Schedules.API.Models;
using Dapper;
using System.Linq;
namespace Schedules.API.Tasks
{
public class CreateReminder: InOutTask<CreateReminder.Input, CreateReminder.Output>
{
public FetchReminderType FetchReminderType { get; set; }
public class Input
{
public Reminder Reminder { get; set; }
public String ReminderTypeName { get; set; }
}
public class Output
{
public Reminder Reminder { get; set; }
}
public override void Execute()
{
FetchReminderType.In.ReminderTypeName = In.ReminderTypeName;
FetchReminderType.Execute();
In.Reminder.ReminderType = FetchReminderType.Out.ReminderType;
Out.Reminder = new Reminder ();
using (var connection = Db.Connect ()) {
try{
Out.Reminder = connection.Query<Reminder, ReminderType, Reminder>(
sql,
(reminder, reminderType) => {reminder.ReminderType = reminderType; return reminder;},
In.Reminder).SingleOrDefault();
}
catch(Exception ex){
Console.WriteLine (ex);
}
}
}
const string sql = @"
with insertReminder as (
insert into Reminders(contact, message, remind_on, verified, address, reminder_type_id)
values(@Contact, @Message, @RemindOn, @Verified, @Address, @ReminderTypeId) returning *
)
select *
from insertReminder r
left join reminder_types t
on t.id = r.reminder_type_id
;
";
}
}
``` |
7cb7a982-a21c-4baf-a2d7-197c4a0bd1dd | {
"language": "C#"
} | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using Scriban.Parsing;
using Scriban.Syntax;
namespace Scriban.Runtime
{
/// <summary>
/// The empty object (unique singleton, cannot be modified, does not contain any properties)
/// </summary>
public sealed class EmptyScriptObject : IScriptObject
{
public static readonly EmptyScriptObject Default = new EmptyScriptObject();
private EmptyScriptObject()
{
}
public int Count => 0;
public IEnumerable<string> GetMembers()
{
yield break;
}
public bool Contains(string member)
{
return false;
}
public bool IsReadOnly
{
get => true;
set { }
}
public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
{
value = null;
return false;
}
public bool CanWrite(string member)
{
return false;
}
public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
{
throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
}
public bool Remove(string member)
{
return false;
}
public void SetReadOnly(string member, bool readOnly)
{
}
public IScriptObject Clone(bool deep)
{
return this;
}
}
}```
Add ToString method to empty object | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using Scriban.Parsing;
using Scriban.Syntax;
namespace Scriban.Runtime
{
/// <summary>
/// The empty object (unique singleton, cannot be modified, does not contain any properties)
/// </summary>
[DebuggerDisplay("<empty object>")]
public sealed class EmptyScriptObject : IScriptObject
{
public static readonly EmptyScriptObject Default = new EmptyScriptObject();
private EmptyScriptObject()
{
}
public int Count => 0;
public IEnumerable<string> GetMembers()
{
yield break;
}
public bool Contains(string member)
{
return false;
}
public bool IsReadOnly
{
get => true;
set { }
}
public bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value)
{
value = null;
return false;
}
public bool CanWrite(string member)
{
return false;
}
public void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
{
throw new ScriptRuntimeException(span, "Cannot set a property on the empty object");
}
public bool Remove(string member)
{
return false;
}
public void SetReadOnly(string member, bool readOnly)
{
}
public IScriptObject Clone(bool deep)
{
return this;
}
public override string ToString()
{
return string.Empty;
}
}
}``` |
c76bf87a-e2b6-490a-93b1-d32c94a4f0ee | {
"language": "C#"
} | ```c#
using System;
namespace THNETII.Common
{
public static class ArgumentExtensions
{
public static T ThrowIfNull<T>(this T instance, string name) where T : class
=> instance ?? throw new ArgumentNullException(name);
}
}
```
Add String Argument Extension method | ```c#
using System;
namespace THNETII.Common
{
public static class ArgumentExtensions
{
public static T ThrowIfNull<T>(this T instance, string name) where T : class
=> instance ?? throw new ArgumentNullException(name);
/// <exception cref="ArgumentException" />
/// <exception cref="ArgumentNullException" />
public static string ThrowIfNullOrWhiteSpace(this string value, string name)
{
if (string.IsNullOrWhiteSpace(value))
throw value == null ? new ArgumentNullException(nameof(name)) : new ArgumentException("value must neither be empty, nor null, nor whitespace-only.", name);
return value;
}
}
}
``` |
b250f635-7bc4-4ba5-9f4e-81781f74116c | {
"language": "C#"
} | ```c#
using System;
public static class ExtensionMethods
{
public static string Str(this TimeSpan duration)
{
var hours = Math.Abs((int)duration.TotalHours);
var minutes = Math.Abs(duration.Minutes);
int seconds = Math.Abs(duration.Seconds);
if (Math.Abs(duration.Milliseconds) >= 500)
seconds++;
if (duration >= TimeSpan.Zero)
return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
else
return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
}
}```
Remove unnecessary, and wrong, check | ```c#
using System;
public static class ExtensionMethods
{
public static string Str(this TimeSpan duration)
{
var hours = Math.Abs((int)duration.TotalHours);
var minutes = Math.Abs(duration.Minutes);
int seconds = Math.Abs(duration.Seconds);
if (duration >= TimeSpan.Zero)
return string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
else
return string.Format("-{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
}
}``` |
0455ffb2-7f0f-444e-9c64-d235d20ac578 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Octokit
{
public class OauthToken
{
public string TokenType { get; set; }
public string AccessToken { get; set; }
public IReadOnlyCollection<string> Scope { get; set; }
}
}
```
Add comments and debugger display | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class OauthToken
{
/// <summary>
/// The type of OAuth token
/// </summary>
public string TokenType { get; set; }
/// <summary>
/// The secret OAuth access token. Use this to authenticate Octokit.net's client.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// The list of scopes the token includes.
/// </summary>
public IReadOnlyCollection<string> Scope { get; set; }
internal string DebuggerDisplay
{
get
{
return String.Format(CultureInfo.InvariantCulture, "TokenType: {0}, AccessToken: {1}, Scopes: {2}",
TokenType,
AccessToken,
Scope);
}
}
}
}
``` |
a58a069a-abcd-442f-9e7b-81d2ed389e28 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFDataBarConverter:IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };
var dataBar = new DataBar {ShowValue = !cf.ShowBarOnly};
var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml()};
if (cf.Values.Count >= 1) conditionalFormatValueObject1.Val = cf.Values[1].Value;
var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml()};
if (cf.Values.Count >= 2) conditionalFormatValueObject2.Val = cf.Values[2].Value;
var color = new Color { Rgb = cf.Colors[1].Color.ToHex() };
dataBar.Append(conditionalFormatValueObject1);
dataBar.Append(conditionalFormatValueObject2);
dataBar.Append(color);
conditionalFormattingRule.Append(dataBar);
return conditionalFormattingRule;
}
}
}
```
Fix data bar for min/max | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFDataBarConverter : IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = new ConditionalFormattingRule { Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };
var dataBar = new DataBar { ShowValue = !cf.ShowBarOnly };
var conditionalFormatValueObject1 = new ConditionalFormatValueObject { Type = cf.ContentTypes[1].ToOpenXml() };
if (cf.Values.Any() && cf.Values[1]?.Value != null) conditionalFormatValueObject1.Val = cf.Values[1].Value;
var conditionalFormatValueObject2 = new ConditionalFormatValueObject { Type = cf.ContentTypes[2].ToOpenXml() };
if (cf.Values.Count >= 2 && cf.Values[2]?.Value != null) conditionalFormatValueObject2.Val = cf.Values[2].Value;
var color = new Color();
switch (cf.Colors[1].ColorType)
{
case XLColorType.Color:
color.Rgb = cf.Colors[1].Color.ToHex();
break;
case XLColorType.Theme:
color.Theme = System.Convert.ToUInt32(cf.Colors[1].ThemeColor);
break;
case XLColorType.Indexed:
color.Indexed = System.Convert.ToUInt32(cf.Colors[1].Indexed);
break;
}
dataBar.Append(conditionalFormatValueObject1);
dataBar.Append(conditionalFormatValueObject2);
dataBar.Append(color);
conditionalFormattingRule.Append(dataBar);
return conditionalFormattingRule;
}
}
}
``` |
7fd300cb-7f74-4f28-b561-115983fd39b5 | {
"language": "C#"
} | ```c#
@using Csla.Web.Mvc
@using ProjectTracker.Library
@model IEnumerable<ProjectTracker.Library.ProjectInfo>
@{
ViewBag.Title = "Project list";
}
<h2>@ViewBag.Message</h2>
<p>
@Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)
@if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit)))
{
@Html.ActionLink("Create New", "Create")
}
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")
</td>
<td>
@item.Name
</td>
</tr>
}
</table>
```
Remove redundant code. bugid: 912 | ```c#
@using Csla.Web.Mvc
@using ProjectTracker.Library
@model IEnumerable<ProjectTracker.Library.ProjectInfo>
@{
ViewBag.Title = "Project list";
}
<h2>@ViewBag.Message</h2>
<p>
@Html.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectEdit), Html.ActionLink("Create New", "Create"), string.Empty)
</p>
<table>
<tr>
<th></th>
<th>
Name
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectEdit), Html.ActionLink("Edit", "Edit", new { id = item.Id }), "Edit") |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectEdit), Html.ActionLink("Delete", "Delete", new { id = item.Id }), "Delete")
</td>
<td>
@item.Name
</td>
</tr>
}
</table>
``` |
a0cf722a-4cff-4afe-af50-c63bfe0f9dbc | {
"language": "C#"
} | ```c#
using System;
using System.Windows;
namespace CupCake.Client
{
public static class Dispatch
{
public static void Invoke(Action callback)
{
Application.Current.Dispatcher.BeginInvoke(callback);
}
}
}```
Fix newConnection window is sometimes not displayed | ```c#
using System;
using System.Windows;
namespace CupCake.Client
{
public static class Dispatch
{
public static void Invoke(Action callback)
{
Application.Current.Dispatcher.Invoke(callback);
}
}
}``` |
ea574298-d46d-43c9-96d0-9a61110de1cb | {
"language": "C#"
} | ```c#
using System.Linq;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
where TSingleResult : XUnitSingleResultsBase
{
public XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
: base(true, configuration, singleResultLoader)
{
this.SetExampleSignatureBuilder(exampleSignatureBuilder);
}
public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
{
foreach (var testResult in TestResults.OfType<TSingleResult>())
{
testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
}
}
public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
{
var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();
return EvaluateTestResults(results);
}
}
}```
Make constructor of abstract class protected | ```c#
using System.Linq;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit
{
public abstract class XUnitResultsBase<TSingleResult> : MultipleTestResults
where TSingleResult : XUnitSingleResultsBase
{
protected XUnitResultsBase(IConfiguration configuration, ISingleResultLoader singleResultLoader, XUnitExampleSignatureBuilder exampleSignatureBuilder)
: base(true, configuration, singleResultLoader)
{
this.SetExampleSignatureBuilder(exampleSignatureBuilder);
}
public void SetExampleSignatureBuilder(XUnitExampleSignatureBuilder exampleSignatureBuilder)
{
foreach (var testResult in TestResults.OfType<TSingleResult>())
{
testResult.ExampleSignatureBuilder = exampleSignatureBuilder;
}
}
public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments)
{
var results = TestResults.OfType<TSingleResult>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray();
return EvaluateTestResults(results);
}
}
}``` |
091ae420-cd4a-432f-b4fa-a2e80b47426c | {
"language": "C#"
} | ```c#
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Overlays.Options.Sections.Audio
{
public class AudioDevicesOptions : OptionsSubsection
{
protected override string Header => "Devices";
public AudioDevicesOptions()
{
Children = new[]
{
new OptionLabel { Text = "Output device: TODO dropdown" }
};
}
}
}```
Allow audio device selection in settings | ```c#
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Overlays.Options.Sections.Audio
{
public class AudioDevicesOptions : OptionsSubsection
{
protected override string Header => "Devices";
private AudioManager audio;
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
this.audio = audio;
}
protected override void LoadComplete()
{
base.LoadComplete();
var deviceItems = new List<KeyValuePair<string, string>>();
deviceItems.Add(new KeyValuePair<string, string>("Standard", ""));
deviceItems.AddRange(audio.GetDeviceNames().Select(d => new KeyValuePair<string, string>(d, d)));
Children = new Drawable[]
{
new OptionDropDown<string>()
{
Items = deviceItems,
Bindable = audio.AudioDevice
},
};
}
}
}``` |
0c6b587c-c3fd-42dc-b06a-b645f3d19f40 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public GameObject global;
public GameObject objectToFollow;
// Use this for initialization
void Start () {
if (global == null)
{
return;
}
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
// Update is called once per frame (use LateUpdate for cameras)
void LateUpdate () {
transform.LookAt(objectToFollow.transform);
}
}
```
Fix linking of follow camera to hero | ```c#
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public GameObject global;
public GameObject objectToFollow;
// Use this for initialization
void Start () {
if (global == null)
{
return;
}
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
// Update is called once per frame (use LateUpdate for cameras)
void LateUpdate () {
if (objectToFollow != null)
{
transform.LookAt(objectToFollow.transform);
}
else
{
Global g = global.GetComponent<Global>();
if (g == null)
{
return;
}
objectToFollow = g.hero;
}
}
}
``` |
f4f7bc55-bd9c-4e32-aa7b-2bc9c6274f97 | {
"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.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Toolbar
{
public class ToolbarMusicButton : ToolbarOverlayToggleButton
{
public ToolbarMusicButton()
{
Icon = FontAwesome.Solid.Music;
TooltipMain = "Now playing";
TooltipSub = "Manage the currently playing track";
Hotkey = GlobalAction.ToggleNowPlaying;
}
[BackgroundDependencyLoader(true)]
private void load(NowPlayingOverlay music)
{
StateContainer = music;
}
}
}
```
Fix toolbar music button tooltip overflowing off-screen | ```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.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Toolbar
{
public class ToolbarMusicButton : ToolbarOverlayToggleButton
{
protected override Anchor TooltipAnchor => Anchor.TopRight;
public ToolbarMusicButton()
{
Icon = FontAwesome.Solid.Music;
TooltipMain = "Now playing";
TooltipSub = "Manage the currently playing track";
Hotkey = GlobalAction.ToggleNowPlaying;
}
[BackgroundDependencyLoader(true)]
private void load(NowPlayingOverlay music)
{
StateContainer = music;
}
}
}
``` |
a0039077-9c3d-495c-963a-8e3769db4dd8 | {
"language": "C#"
} | ```c#
namespace Miruken.Callback
{
using System;
public class Resolving : Inquiry, IResolveCallback
{
private bool _handled;
public Resolving(object key, object callback)
: base(key, true)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
Callback = callback;
}
public object Callback { get; }
object IResolveCallback.GetResolveCallback()
{
return this;
}
protected override bool IsSatisfied(
object resolution, bool greedy, IHandler composer)
{
if (_handled && !greedy) return true;
return _handled =
Handler.Dispatch(resolution, Callback, ref greedy, composer)
|| _handled;
}
public static object GetDefaultResolvingCallback(object callback)
{
var dispatch = callback as IDispatchCallback;
var policy = dispatch?.Policy ?? HandlesAttribute.Policy;
var handlers = policy.GetHandlers(callback);
var bundle = new Bundle(false);
foreach (var handler in handlers)
bundle.Add(h => h.Handle(new Resolving(handler, callback)));
bundle.Add(h => h.Handle(callback));
return bundle;
}
}
}
```
Handle callback directly if resolve bundle is empty | ```c#
namespace Miruken.Callback
{
using System;
public class Resolving : Inquiry, IResolveCallback
{
private bool _handled;
public Resolving(object key, object callback)
: base(key, true)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
Callback = callback;
}
public object Callback { get; }
object IResolveCallback.GetResolveCallback()
{
return this;
}
protected override bool IsSatisfied(
object resolution, bool greedy, IHandler composer)
{
if (_handled && !greedy) return true;
return _handled = Handler.Dispatch(
resolution, Callback, ref greedy, composer)
|| _handled;
}
public static object GetDefaultResolvingCallback(object callback)
{
var dispatch = callback as IDispatchCallback;
var policy = dispatch?.Policy ?? HandlesAttribute.Policy;
var handlers = policy.GetHandlers(callback);
var bundle = new Bundle(false);
foreach (var handler in handlers)
bundle.Add(h => h.Handle(new Resolving(handler, callback)));
if (bundle.IsEmpty)
bundle.Add(h => h.Handle(callback));
return bundle;
}
}
}
``` |
bfec1db3-1ca1-4450-9691-3698fae1e763 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;
namespace Diploms.DataLayer
{
public static class DiplomContentSystemExtensions
{
public static void EnsureSeedData(this DiplomContext context)
{
if (context.AllMigrationsApplied())
{
if (!context.Periods.Any())
{
context.Periods.Add(Period.Current);
}
if (!context.Roles.Any())
{
context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
}
if(!context.Users.Any())
{
context.Users.Add(new User{
Id = 1,
Login = "admin",
PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
Roles = new List<UserRole>
{
new UserRole
{
UserId = 1,
RoleId = 1
}
}
});
}
context.SaveChanges();
}
}
private static bool AllMigrationsApplied(this DiplomContext context)
{
var applied = context.GetService<IHistoryRepository>()
.GetAppliedMigrations()
.Select(m => m.MigrationId);
var total = context.GetService<IMigrationsAssembly>()
.Migrations
.Select(m => m.Key);
return !total.Except(applied).Any();
}
}
}```
Add positions to db on startup | ```c#
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
using System.Collections.Generic;
namespace Diploms.DataLayer
{
public static class DiplomContentSystemExtensions
{
public static void EnsureSeedData(this DiplomContext context)
{
if (context.AllMigrationsApplied())
{
if (!context.Periods.Any())
{
context.Periods.Add(Period.Current);
}
if (!context.TeachersPositions.Any())
{
context.TeachersPositions.AddRange(TeacherPosition.HighTeacher, TeacherPosition.Professor, TeacherPosition.Doctor);
}
if (!context.Roles.Any())
{
context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
}
if(!context.Users.Any())
{
context.Users.Add(new User{
Id = 1,
Login = "admin",
PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=",
Roles = new List<UserRole>
{
new UserRole
{
UserId = 1,
RoleId = 1
}
}
});
}
context.SaveChanges();
}
}
private static bool AllMigrationsApplied(this DiplomContext context)
{
var applied = context.GetService<IHistoryRepository>()
.GetAppliedMigrations()
.Select(m => m.MigrationId);
var total = context.GetService<IMigrationsAssembly>()
.Migrations
.Select(m => m.Key);
return !total.Except(applied).Any();
}
}
}``` |
ea73c8e7-9ab9-482d-a484-1993f7f2d7bd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BmpListener.Bmp
{
public enum MessageType : byte
{
RouteMonitoring,
StatisticsReport,
PeerDown,
PeerUp,
Initiation,
Termination,
RouteMirroring
}
public enum PeerType : byte
{
Global,
RD,
Local
}
}
```
Remove enum underlying type declaration | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BmpListener.Bmp
{
public enum MessageType
{
RouteMonitoring,
StatisticsReport,
PeerDown,
PeerUp,
Initiation,
Termination,
RouteMirroring
}
public enum PeerType
{
Global,
RD,
Local
}
}
``` |
36e3882e-860f-4c83-aa27-e52c2d011896 | {
"language": "C#"
} | ```c#
#region (c) 2010-2011 Lokad CQRS - New BSD License
// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
// This code is released as Open Source under the terms of the New BSD Licence
// Homepage: http://lokad.github.com/lokad-cqrs/
#endregion
using System;
using System.Collections.Generic;
using ProtoBuf.Meta;
namespace Lokad.Cqrs.Core.Serialization
{
public class DataSerializerWithProtoBuf : AbstractDataSerializer
{
public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes)
{
if (knownTypes.Count == 0)
throw new InvalidOperationException(
"ProtoBuf requires some known types to serialize. Have you forgot to supply them?");
}
protected override Formatter PrepareFormatter(Type type)
{
var name = ContractEvil.GetContractReference(type);
var formatter = RuntimeTypeModel.Default.CreateFormatter(type);
return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o));
}
}
}```
Remove contract count check for protobuf | ```c#
#region (c) 2010-2011 Lokad CQRS - New BSD License
// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
// This code is released as Open Source under the terms of the New BSD Licence
// Homepage: http://lokad.github.com/lokad-cqrs/
#endregion
using System;
using System.Collections.Generic;
using ProtoBuf.Meta;
namespace Lokad.Cqrs.Core.Serialization
{
public class DataSerializerWithProtoBuf : AbstractDataSerializer
{
public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes)
{
}
protected override Formatter PrepareFormatter(Type type)
{
var name = ContractEvil.GetContractReference(type);
var formatter = RuntimeTypeModel.Default.CreateFormatter(type);
return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o));
}
}
}``` |
65c3252c-fe71-4be9-aa42-4df9a5e147dd | {
"language": "C#"
} | ```c#
using NuGet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Squirrel
{
public static class VersionExtensions
{
private static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled);
private static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled);
public static SemanticVersion ToSemanticVersion(this IReleasePackage package)
{
return package.InputPackageFile.ToSemanticVersion();
}
public static SemanticVersion ToSemanticVersion(this string fileName)
{
var name = _suffixRegex.Replace(fileName, "");
var version = _versionRegex.Match(name).Value;
return new SemanticVersion(version);
}
}
}
```
Remove private qualifier on version regexes | ```c#
using NuGet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Squirrel
{
public static class VersionExtensions
{
static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled);
static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled);
public static SemanticVersion ToSemanticVersion(this IReleasePackage package)
{
return package.InputPackageFile.ToSemanticVersion();
}
public static SemanticVersion ToSemanticVersion(this string fileName)
{
var name = _suffixRegex.Replace(fileName, "");
var version = _versionRegex.Match(name).Value;
return new SemanticVersion(version);
}
}
}
``` |
1b5fbdbe-7cf0-455d-9de1-d9fd0d8d8e14 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.Win32;
namespace EasySnippets.Utils
{
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")]
public class StartUpManager
{
public static void AddApplicationToCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssembly = Assembly.GetExecutingAssembly();
key?.SetValue(curAssembly.GetName().Name, curAssembly.Location);
}
public static void RemoveApplicationFromCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
if (!string.IsNullOrWhiteSpace(curAssemblyName))
{
key?.DeleteValue(curAssemblyName, false);
}
}
public static bool IsApplicationAddedToCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssembly = Assembly.GetExecutingAssembly();
var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString();
return currentValue?.Equals(curAssembly.Location, StringComparison.InvariantCultureIgnoreCase) ?? false;
}
}
}```
Use AppContext.BaseDirectory for application path | ```c#
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.Win32;
namespace EasySnippets.Utils
{
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")]
public class StartUpManager
{
public static void AddApplicationToCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssembly = Assembly.GetExecutingAssembly();
key?.SetValue(curAssembly.GetName().Name, AppContext.BaseDirectory);
}
public static void RemoveApplicationFromCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
if (!string.IsNullOrWhiteSpace(curAssemblyName))
{
key?.DeleteValue(curAssemblyName, false);
}
}
public static bool IsApplicationAddedToCurrentUserStartup()
{
using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
var curAssembly = Assembly.GetExecutingAssembly();
var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString();
return currentValue?.Equals(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) ?? false;
}
}
}``` |
2d7faae9-f2c8-48db-a754-85d033b270d8 | {
"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.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
namespace osu.Game.Screens.Play
{
public class ComboEffects : CompositeDrawable
{
private readonly ScoreProcessor processor;
private SkinnableSound comboBreakSample;
private Bindable<bool> alwaysPlay;
private bool firstTime = true;
public ComboEffects(ScoreProcessor processor)
{
this.processor = processor;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak"));
alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.Combo.BindValueChanged(onComboChange);
}
private void onComboChange(ValueChangedEvent<int> combo)
{
if (combo.NewValue == 0 && (combo.OldValue > 20 || alwaysPlay.Value && firstTime))
{
comboBreakSample?.Play();
firstTime = false;
}
}
}
}
```
Add implicit braces for clarity | ```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.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
namespace osu.Game.Screens.Play
{
public class ComboEffects : CompositeDrawable
{
private readonly ScoreProcessor processor;
private SkinnableSound comboBreakSample;
private Bindable<bool> alwaysPlay;
private bool firstTime = true;
public ComboEffects(ScoreProcessor processor)
{
this.processor = processor;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak"));
alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.Combo.BindValueChanged(onComboChange);
}
private void onComboChange(ValueChangedEvent<int> combo)
{
if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlay.Value && firstTime)))
{
comboBreakSample?.Play();
firstTime = false;
}
}
}
}
``` |
5ac47851-4aeb-4a29-be77-52d922e61160 | {
"language": "C#"
} | ```c#
using System;
using Abp;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Castle.Facilities.Logging;
using Abp.Castle.Logging.Log4Net;
namespace AbpCompanyName.AbpProjectName.Migrator
{
public class Program
{
private static bool _skipConnVerification = false;
public static void Main(string[] args)
{
ParseArgs(args);
using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>())
{
bootstrapper.IocManager.IocContainer
.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net()
.WithConfig("log4net.config")
);
bootstrapper.Initialize();
using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>())
{
migrateExecuter.Object.Run(_skipConnVerification);
}
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
private static void ParseArgs(string[] args)
{
if (args.IsNullOrEmpty())
{
return;
}
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
switch (arg)
{
case "-s":
_skipConnVerification = true;
break;
}
}
}
}
}
```
Remove confirmation for exit with no verification | ```c#
using System;
using Abp;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Castle.Facilities.Logging;
using Abp.Castle.Logging.Log4Net;
namespace AbpCompanyName.AbpProjectName.Migrator
{
public class Program
{
private static bool _skipConnVerification = false;
public static void Main(string[] args)
{
ParseArgs(args);
using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>())
{
bootstrapper.IocManager.IocContainer
.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net()
.WithConfig("log4net.config")
);
bootstrapper.Initialize();
using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>())
{
migrateExecuter.Object.Run(_skipConnVerification);
}
if (!_skipConnVerification)
{
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
}
private static void ParseArgs(string[] args)
{
if (args.IsNullOrEmpty())
{
return;
}
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
switch (arg)
{
case "-s":
_skipConnVerification = true;
break;
}
}
}
}
}
``` |
6eef822d-b96e-4ce7-bf85-aa316e46e1a6 | {
"language": "C#"
} | ```c#
using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork;
using System;
using System.Collections.Generic;
namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate
{
public class Address : ValueObject
{
public String Street { get; }
public String City { get; }
public String State { get; }
public String Country { get; }
public String ZipCode { get; }
private Address() { }
public Address(string street, string city, string state, string country, string zipcode)
{
Street = street;
City = city;
State = state;
Country = country;
ZipCode = zipcode;
}
protected override IEnumerable<object> GetAtomicValues()
{
// Using a yield return statement to return each element one at a time
yield return Street;
yield return City;
yield return State;
yield return Country;
yield return ZipCode;
}
}
}
```
Add private setters so deserializing on integration event handler works as expected. | ```c#
using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork;
using System;
using System.Collections.Generic;
namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate
{
public class Address : ValueObject
{
public String Street { get; private set; }
public String City { get; private set; }
public String State { get; private set; }
public String Country { get; private set; }
public String ZipCode { get; private set; }
private Address() { }
public Address(string street, string city, string state, string country, string zipcode)
{
Street = street;
City = city;
State = state;
Country = country;
ZipCode = zipcode;
}
protected override IEnumerable<object> GetAtomicValues()
{
// Using a yield return statement to return each element one at a time
yield return Street;
yield return City;
yield return State;
yield return Country;
yield return ZipCode;
}
}
}
``` |
12babed1-4648-403b-bbaa-6e5feb0fae81 | {
"language": "C#"
} | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2019";
public const string Trademark = "";
public const string Version = "3.2.0.0";
}
}
```
Update file version to 3.2.1.0 | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2019";
public const string Trademark = "";
public const string Version = "3.2.1.0";
}
}
``` |
822d3823-7683-4e25-907f-80b7750ea538 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
namespace PcscDotNet
{
public delegate void PcscExceptionHandler(PcscException error);
public sealed class PcscException : Win32Exception
{
public SCardError Error => (SCardError)NativeErrorCode;
public bool ThrowIt { get; set; } = true;
public PcscException(int error) : base(error) { }
public PcscException(SCardError error) : base((int)error) { }
public PcscException(string message) : base(message) { }
public PcscException(int error, string message) : base(error, message) { }
public PcscException(string message, Exception innerException) : base(message, innerException) { }
}
}
```
Update `PcscExcetpion` class. Assign the value of `Error` in constructor. Remove unused constructors. | ```c#
using System;
using System.ComponentModel;
namespace PcscDotNet
{
public delegate void PcscExceptionHandler(PcscException error);
public sealed class PcscException : Win32Exception
{
public SCardError Error { get; private set; }
public bool ThrowIt { get; set; } = true;
public PcscException(SCardError error) : base((int)error)
{
Error = error;
}
}
}
``` |
af77e15a-9daa-4b80-b019-8edffa10031c | {
"language": "C#"
} | ```c#
namespace StraightSql
{
using Npgsql;
using System;
public class CommandPreparer
: ICommandPreparer
{
public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query)
{
if (npgsqlCommand == null)
throw new ArgumentNullException(nameof(npgsqlCommand));
if (query == null)
throw new ArgumentNullException(nameof(query));
var queryText = query.Text;
foreach (var literal in query.Literals)
{
var moniker = $":{literal.Key}";
if (!queryText.Contains(moniker))
throw new LiteralNotFoundException(literal.Key);
queryText = queryText.Replace(moniker, literal.Value);
}
npgsqlCommand.CommandText = queryText;
foreach (var queryParameter in query.Parameters)
{
npgsqlCommand.Parameters.Add(queryParameter);
}
}
}
}
```
Replace literals in order of key length, e.g. most-specific first. | ```c#
namespace StraightSql
{
using Npgsql;
using System;
using System.Linq;
public class CommandPreparer
: ICommandPreparer
{
public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query)
{
if (npgsqlCommand == null)
throw new ArgumentNullException(nameof(npgsqlCommand));
if (query == null)
throw new ArgumentNullException(nameof(query));
var queryText = query.Text;
foreach (var literal in query.Literals.OrderByDescending(l => l.Key.Length))
{
var moniker = $":{literal.Key}";
if (!queryText.Contains(moniker))
throw new LiteralNotFoundException(literal.Key);
queryText = queryText.Replace(moniker, literal.Value);
}
npgsqlCommand.CommandText = queryText;
foreach (var queryParameter in query.Parameters)
{
npgsqlCommand.Parameters.Add(queryParameter);
}
}
}
}
``` |
279124fc-2f9f-40f5-b721-ac0b00f6e9fc | {
"language": "C#"
} | ```c#
[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))]
namespace BatteryCommander.Web
{
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Auth/Login"),
LogoutPath = new PathString("/Auth/Logout"),
ExpireTimeSpan = TimeSpan.FromHours(1),
SlidingExpiration = true,
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.SameAsRequest
// CookieDomain = "",
// CookieName = ""
});
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
}
}```
Extend cookie timeout to 1 day | ```c#
[assembly: Microsoft.Owin.OwinStartup(typeof(BatteryCommander.Web.Startup))]
namespace BatteryCommander.Web
{
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Auth/Login"),
LogoutPath = new PathString("/Auth/Logout"),
ExpireTimeSpan = TimeSpan.FromDays(1),
SlidingExpiration = true,
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.SameAsRequest
// CookieDomain = "",
// CookieName = ""
});
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
}
}``` |
8cf26f54-b17e-48e3-bda4-50fbb9834a2b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cloud.Storage.Queues;
namespace Cloud.Storage.AWS.Queues
{
public class Queue : IQueue
{
public Task AddMessage(IMessage message)
{
throw new NotImplementedException();
}
public IMessage CreateMessage(byte[] messageContents)
{
throw new NotImplementedException();
}
public IMessage CreateMessage(string messageContents)
{
throw new NotImplementedException();
}
public Task<List<IMessage>> GetMessages(int numMessages, TimeSpan? visibilityTimeout = default(TimeSpan?))
{
throw new NotImplementedException();
}
public Task<IMessage> GetNextMessage(TimeSpan? visibilityTimeout = default(TimeSpan?))
{
throw new NotImplementedException();
}
public Task<List<IMessage>> PeekMessages(int numMessages)
{
throw new NotImplementedException();
}
public Task<IMessage> PeekNextMessage()
{
throw new NotImplementedException();
}
}
}
```
Fix compilation issues on AWS side. | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cloud.Storage.Queues;
namespace Cloud.Storage.AWS.Queues
{
public class Queue : IQueue
{
public Task AddMessage(IMessage message)
{
throw new NotImplementedException();
}
public Task Clear()
{
throw new NotImplementedException();
}
public IMessage CreateMessage(byte[] messageContents)
{
throw new NotImplementedException();
}
public IMessage CreateMessage(string messageContents)
{
throw new NotImplementedException();
}
public int GetApproximateMessageCount()
{
throw new NotImplementedException();
}
public Task<List<IMessage>> GetMessages(int numMessages, TimeSpan? visibilityTimeout = default(TimeSpan?))
{
throw new NotImplementedException();
}
public Task<IMessage> GetNextMessage(TimeSpan? visibilityTimeout = default(TimeSpan?))
{
throw new NotImplementedException();
}
public Task<List<IMessage>> PeekMessages(int numMessages)
{
throw new NotImplementedException();
}
public Task<IMessage> PeekNextMessage()
{
throw new NotImplementedException();
}
}
}
``` |
4c21c5b0-120b-45b9-800d-9c3dc3fff1ac | {
"language": "C#"
} | ```c#
namespace Microsoft.ApplicationInsights.AspNetCore.Common
{
/// <summary>
/// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response.
/// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses.
/// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious.
/// </summary>
public static class InjectionGuardConstants
{
/// <summary>
/// Max length of AppId allowed in response from Breeze.
/// </summary>
public const int AppIdMaxLengeth = 50;
/// <summary>
/// Max length of incoming Request Header value allowed.
/// </summary>
public const int RequestHeaderMaxLength = 1024;
/// <summary>
/// Max length of context header key.
/// </summary>
public const int ContextHeaderKeyMaxLength = 50;
/// <summary>
/// Max length of context header value.
/// </summary>
public const int ContextHeaderValueMaxLength = 100;
}
}```
Adjust max size of contents read from incoming request headers to be 1k | ```c#
namespace Microsoft.ApplicationInsights.AspNetCore.Common
{
/// <summary>
/// These values are listed to guard against malicious injections by limiting the max size allowed in an HTTP Response.
/// These max limits are intentionally exaggerated to allow for unexpected responses, while still guarding against unreasonably large responses.
/// Example: While a 32 character response may be expected, 50 characters may be permitted while a 10,000 character response would be unreasonable and malicious.
/// </summary>
public static class InjectionGuardConstants
{
/// <summary>
/// Max length of AppId allowed in response from Breeze.
/// </summary>
public const int AppIdMaxLengeth = 50;
/// <summary>
/// Max length of incoming Request Header value allowed.
/// </summary>
public const int RequestHeaderMaxLength = 1024;
/// <summary>
/// Max length of context header key.
/// </summary>
public const int ContextHeaderKeyMaxLength = 50;
/// <summary>
/// Max length of context header value.
/// </summary>
public const int ContextHeaderValueMaxLength = 1024;
}
}``` |
b1adbc41-2c13-4a1b-a619-eb19b6a766fa | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Linq;
using ARSoft.Tools.Net.Dns;
namespace DNSAgent
{
internal class DnsCacheMessageEntry
{
public DnsCacheMessageEntry(DnsMessage message, int timeToLive)
{
Message = message;
timeToLive =
Math.Max(message.AnswerRecords.Concat(message.AuthorityRecords).Min(record => record.TimeToLive),
timeToLive);
ExpireTime = DateTime.Now.AddSeconds(timeToLive);
}
public DnsMessage Message { get; set; }
public DateTime ExpireTime { get; set; }
public bool IsExpired
{
get { return DateTime.Now > ExpireTime; }
}
}
internal class DnsMessageCache :
ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>>
{
public void Update(DnsQuestion question, DnsMessage message, int timeToLive)
{
if (!ContainsKey(question.Name))
this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>();
this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive);
}
}
}```
Fix "Sequence contains no elements" error. | ```c#
using System;
using System.Collections.Concurrent;
using System.Linq;
using ARSoft.Tools.Net.Dns;
namespace DNSAgent
{
internal class DnsCacheMessageEntry
{
public DnsCacheMessageEntry(DnsMessage message, int timeToLive)
{
Message = message;
var records = message.AnswerRecords.Concat(message.AuthorityRecords).ToList();
if (records.Any())
timeToLive = Math.Max(records.Min(record => record.TimeToLive), timeToLive);
ExpireTime = DateTime.Now.AddSeconds(timeToLive);
}
public DnsMessage Message { get; set; }
public DateTime ExpireTime { get; set; }
public bool IsExpired
{
get { return DateTime.Now > ExpireTime; }
}
}
internal class DnsMessageCache :
ConcurrentDictionary<string, ConcurrentDictionary<RecordType, DnsCacheMessageEntry>>
{
public void Update(DnsQuestion question, DnsMessage message, int timeToLive)
{
if (!ContainsKey(question.Name))
this[question.Name] = new ConcurrentDictionary<RecordType, DnsCacheMessageEntry>();
this[question.Name][question.RecordType] = new DnsCacheMessageEntry(message, timeToLive);
}
}
}``` |
f8dcdf09-4fe5-4096-bebe-76639c868f35 | {
"language": "C#"
} | ```c#
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace Borodar.RainbowItems.Editor.Settings
{
public class CustomBrowserIconSettings : ScriptableObject
{
public List<Folder> Folders;
public Sprite GetSprite(string folderName, bool small = true)
{
var folder = Folders.FirstOrDefault(x => x.FolderName.Contains(folderName));
if (folder == null) { return null; }
return small ? folder.SmallIcon : folder.LargeIcon;
}
}
}```
Check for an exact match of item name | ```c#
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace Borodar.RainbowItems.Editor.Settings
{
public class CustomBrowserIconSettings : ScriptableObject
{
public List<Folder> Folders;
public Sprite GetSprite(string folderName, bool small = true)
{
var folder = Folders.FirstOrDefault(x => x.FolderName.Equals(folderName));
if (folder == null) { return null; }
return small ? folder.SmallIcon : folder.LargeIcon;
}
}
}``` |
c525f865-7279-43a2-84cb-6a6a5b077a4c | {
"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.
#nullable enable
using System;
namespace osu.Framework.Utils
{
public static class ThrowHelper
{
public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message);
}
}
```
Add xmldoc and TODO comment | ```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.
#nullable enable
using System;
namespace osu.Framework.Utils
{
/// <summary>
/// Helper class for throwing exceptions in isolated methods, for cases where method inlining is beneficial.
/// As throwing directly in that case causes JIT to disable inlining on the surrounding method.
/// </summary>
// todo: continue implementation and use where required, see https://github.com/ppy/osu-framework/issues/3470.
public static class ThrowHelper
{
public static void ThrowInvalidOperationException(string? message) => throw new InvalidOperationException(message);
}
}
``` |
86600d09-33db-4e89-b612-eba099943480 | {
"language": "C#"
} | ```c#
using System;
namespace Avalonia.Metadata
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class XmlnsPrefixAttribute : Attribute
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNamespace">XML namespce</param>
/// <param name="prefix">recommended prefix</param>
public XmlnsPrefixAttribute(string xmlNamespace, string prefix)
{
XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace));
Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix));
}
/// <summary>
/// XML Namespace
/// </summary>
public string XmlNamespace { get; }
/// <summary>
/// New Xml Namespace
/// </summary>
public string Prefix { get; }
}
}
```
Add sumary and remark to class header | ```c#
using System;
namespace Avalonia.Metadata
{
/// <summary>
/// Use to predefine the prefix associated to an xml namespace in a xaml file
/// </summary>
/// <remarks>
/// example:
/// [assembly: XmlnsPrefix("https://github.com/avaloniaui", "av")]
/// xaml:
/// xmlns:av="https://github.com/avaloniaui"
/// </remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class XmlnsPrefixAttribute : Attribute
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNamespace">XML namespce</param>
/// <param name="prefix">recommended prefix</param>
public XmlnsPrefixAttribute(string xmlNamespace, string prefix)
{
XmlNamespace = xmlNamespace ?? throw new ArgumentNullException(nameof(xmlNamespace));
Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix));
}
/// <summary>
/// XML Namespace
/// </summary>
public string XmlNamespace { get; }
/// <summary>
/// New Xml Namespace
/// </summary>
public string Prefix { get; }
}
}
``` |
68d88181-e475-4373-9db6-fc1648614033 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyProduct( "ZEISS PiWeb Api" )]
[assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyTrademark( "PiWeb" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "3.0.0" )]
[assembly: AssemblyInformationalVersion("3.0.0")]
[assembly: AssemblyFileVersion( "3.0.0" )]
```
Update assembly version to 4.0.0 (+semver: major) | ```c#
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyProduct( "ZEISS PiWeb Api" )]
[assembly: AssemblyCopyright( "Copyright © 2019 Carl Zeiss Innovationszentrum für Messtechnik GmbH" )]
[assembly: AssemblyTrademark( "PiWeb" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "4.0.0" )]
[assembly: AssemblyInformationalVersion("4.0.0")]
[assembly: AssemblyFileVersion( "4.0.0" )]
``` |
0efed87b-3794-4dda-a6c7-14d630d5ede1 | {
"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;
using Xunit.Sdk;
namespace Xunit
{
/// <summary>
/// Apply this attribute to your test method to specify this is a platform specific test.
/// </summary>
[TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute
{
public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform) { }
}
}
```
Allow specifying metadata for skip reason. | ```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;
using Xunit.Sdk;
namespace Xunit
{
/// <summary>
/// Apply this attribute to your test method to specify this is a platform specific test.
/// </summary>
[TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute
{
public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform, string reason = null) { }
}
}
``` |
6b93184b-fd40-43bb-bca6-cf610244426f | {
"language": "C#"
} | ```c#
using UnityEngine;
public class LinkButton : MonoBehaviour {
public void OpenUrl (string url) {
Application.OpenURL(url);
}
}
```
Fix link open in browsers | ```c#
using UnityEngine;
public class LinkButton : MonoBehaviour {
public void OpenUrl (string url) {
if(Application.platform == RuntimePlatform.WebGLPlayer) {
Application.ExternalEval("window.open(\"" + url + "\",\"_blank\")");
} else {
Application.OpenURL(url);
}
}
}
``` |
e8e49f07-d2f3-4347-b885-5643bd836bfe | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Python.Runtime;
using Wox.Plugin;
namespace Wox.PluginLoader
{
public class PythonPluginLoader : BasePluginLoader
{
public override List<PluginPair> LoadPlugin()
{
List<PluginPair> plugins = new List<PluginPair>();
List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList();
foreach (PluginMetadata metadata in metadatas)
{
PythonPluginWrapper python = new PythonPluginWrapper(metadata);
PluginPair pair = new PluginPair()
{
Plugin = python,
Metadata = metadata
};
plugins.Add(pair);
}
return plugins;
}
}
}
```
Fix crash issue when user didn't install python. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Python.Runtime;
using Wox.Plugin;
using Wox.Helper;
namespace Wox.PluginLoader
{
public class PythonPluginLoader : BasePluginLoader
{
public override List<PluginPair> LoadPlugin()
{
if (!CheckPythonEnvironmentInstalled()) return new List<PluginPair>();
List<PluginPair> plugins = new List<PluginPair>();
List<PluginMetadata> metadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.Python.ToUpper()).ToList();
foreach (PluginMetadata metadata in metadatas)
{
PythonPluginWrapper python = new PythonPluginWrapper(metadata);
PluginPair pair = new PluginPair()
{
Plugin = python,
Metadata = metadata
};
plugins.Add(pair);
}
return plugins;
}
private bool CheckPythonEnvironmentInstalled() {
try
{
PythonEngine.Initialize();
PythonEngine.Shutdown();
}
catch {
Log.Error("Could't find python environment, all python plugins disabled.");
return false;
}
return true;
}
}
}
``` |
c572328b-13da-4b9e-a6ae-3230511fe263 | {
"language": "C#"
} | ```c#
using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistByTagTopTests
{
[Test]
public void Can_hit_endpoint()
{
ArtistByTagTop tags = Api<ArtistByTagTop>.Create
.WithParameter("tags", "rock,pop,2000s")
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0));
Assert.That(tags.Type, Is.EqualTo(ItemType.artist));
Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty);
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create
.WithParameter("tags", "rock,pop,2000s")
.WithParameter("page", "2")
.WithParameter("pageSize", "20")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(20));
}
}
}```
Fix test failure After consulting with search team, we can get results needed for this test by searching for "rock,pop" not "rock,pop,2000s" | ```c#
using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistByTagTopTests
{
private const string Tags = "rock,pop";
[Test]
public void Can_hit_endpoint()
{
ArtistByTagTop tags = Api<ArtistByTagTop>.Create
.WithParameter("tags", Tags)
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TaggedArtists.Count, Is.GreaterThan(0));
Assert.That(tags.Type, Is.EqualTo(ItemType.artist));
Assert.That(tags.TaggedArtists.FirstOrDefault().Artist.Name, Is.Not.Empty);
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistByTagTop artistBrowse = Api<ArtistByTagTop>.Create
.WithParameter("tags", Tags)
.WithParameter("page", "2")
.WithParameter("pageSize", "20")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(20));
}
}
}``` |
46c1d240-0a1a-42fd-933d-d4304ae7dba6 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie>
{
internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/anticipated{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Add filter property to most anticipated movies request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedMovie>, TraktMostAnticipatedMovie>
{
internal TraktMoviesMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktMovieFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
2f075734-1fd5-4ca6-a4ec-dd8704e09c30 | {
"language": "C#"
} | ```c#
using System;
namespace DiscogsClient.Data.Result
{
public class DiscogsRelease : DiscogsReleaseBase
{
public DiscogsReleaseArtist[] extraartists { get; set; }
public DiscogsReleaseLabel[] labels { get; set; }
public DiscogsReleaseLabel[] companies { get; set; }
public DiscogsFormat[] formats { get; set; }
public DiscogsIdentifier[] identifiers { get; set; }
public DiscogsCommunity community { get; set; }
public DiscogsReleaseLabel[] series { get; set; }
public string artists_sort { get; set; }
public string catno { get; set; }
public string country { get; set; }
public DateTime date_added { get; set; }
public DateTime date_changed { get; set; }
public int estimated_weight { get; set; }
public int format_quantity { get; set; }
public int master_id { get; set; }
public string master_url { get; set; }
public string notes { get; set; }
public string released { get; set; }
public string released_formatted { get; set; }
public string status { get; set; }
public string thumb { get; set; }
}
}
```
Add DiscogRelease properties: lowest_price and num_for_sale | ```c#
using System;
namespace DiscogsClient.Data.Result
{
public class DiscogsRelease : DiscogsReleaseBase
{
public DiscogsReleaseArtist[] extraartists { get; set; }
public DiscogsReleaseLabel[] labels { get; set; }
public DiscogsReleaseLabel[] companies { get; set; }
public DiscogsFormat[] formats { get; set; }
public DiscogsIdentifier[] identifiers { get; set; }
public DiscogsCommunity community { get; set; }
public DiscogsReleaseLabel[] series { get; set; }
public string artists_sort { get; set; }
public string catno { get; set; }
public string country { get; set; }
public DateTime date_added { get; set; }
public DateTime date_changed { get; set; }
/// <remarks>Grams</remarks>
public int estimated_weight { get; set; }
public int format_quantity { get; set; }
public decimal lowest_price { get; set; }
public int master_id { get; set; }
public string master_url { get; set; }
public string notes { get; set; }
public int num_for_sale { get; set; }
public string released { get; set; }
public string released_formatted { get; set; }
public string status { get; set; }
public string thumb { get; set; }
}
}
``` |
dfb3b16b-ec08-4d5f-813b-4aa07d1276e2 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")]
[assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")]
[assembly: AssemblyCulture("es")]
// NuGet package metadata
[assembly: AssemblyMetadata("id", "Logo.es")]
[assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]```
Remove Culture since that causes issues for Workbooks | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Logo en español para Xamarin Workbooks")]
[assembly: AssemblyDescription("Aprende a programar con Xamarin Workbooks, C# y la legendaria Tortuga!")]
// NuGet package metadata
[assembly: AssemblyMetadata("id", "Logo.es")]
[assembly: AssemblyMetadata("authors", "Daniel Cazzulino")]``` |
67100f78-8d2a-43e0-b05a-9643f110016f | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !FIXED_ASSEMBLY_VERSION
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
```
Update assembly version to 2.2 | ```c#
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyProduct("NuGet")]
[assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !FIXED_ASSEMBLY_VERSION
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("2.2.0")]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
``` |
7bf2a409-260b-4eda-b2cd-87725d2dc210 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
namespace InterFAX.Api.Test.Integration
{
[TestFixture]
public class AccountTests
{
[Test]
public void can_get_balance()
{
var interfax = new FaxClient();
var actual = interfax.Account.GetBalance().Result;
Assert.IsTrue(actual > 0);
}
}
}```
Update account balance check, account can have zero balance and still be valid. | ```c#
using NUnit.Framework;
namespace InterFAX.Api.Test.Integration
{
[TestFixture]
public class AccountTests
{
[Test]
public void can_get_balance()
{
var interfax = new FaxClient();
var actual = interfax.Account.GetBalance().Result;
//Assert.IsTrue(actual > 0);
}
}
}``` |
8dc64e3f-6659-454a-bf62-ee5566e862a1 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using IntelliTect.Coalesce;
using IntelliTect.Coalesce.DataAnnotations;
using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext;
#nullable enable
namespace IntelliTect.Coalesce.Tests.TargetClasses
{
[Coalesce]
public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext>
{
[Key]
public int CaseId { get; set; }
public string? Title { get; set; }
public void MapTo(Case obj, IMappingContext context)
{
obj.Title = Title;
}
public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null)
{
CaseId = obj.CaseKey;
Title = obj.Title;
}
}
public class ExternalTypeWithDtoProp
{
public CaseDtoStandalone Case { get; set; }
}
}
```
Add additional code gen smoke test cases | ```c#
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using IntelliTect.Coalesce;
using IntelliTect.Coalesce.DataAnnotations;
using IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext;
#nullable enable
namespace IntelliTect.Coalesce.Tests.TargetClasses
{
[Coalesce]
public class CaseDtoStandalone : IClassDto<Case, TestDbContext.TestDbContext>
{
[Key]
public int CaseId { get; set; }
public string? Title { get; set; }
public void MapTo(Case obj, IMappingContext context)
{
obj.Title = Title;
}
public void MapFrom(Case obj, IMappingContext context, IncludeTree? tree = null)
{
CaseId = obj.CaseKey;
Title = obj.Title;
}
}
public class ExternalTypeWithDtoProp
{
public CaseDtoStandalone Case { get; set; }
public ICollection<CaseDtoStandalone> Cases { get; set; }
public List<CaseDtoStandalone> CasesList { get; set; }
public CaseDtoStandalone[] CasesArray { get; set; }
}
}
``` |
70624c05-cd9b-44f8-a156-602be2e7d50b | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace HardwareSensorSystem.SensorTechnology.Controllers
{
public class OwServerEnet2LogController : Controller
{
[AllowAnonymous]
[HttpPost("api/devices/{deviceId}/log")]
public async Task<IActionResult> Log([FromRoute]int deviceId)
{
XDocument file = XDocument.Load(HttpContext.Request.Body);
var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName);
var dataSensors = file.Root.Elements().Select(sensor => new
{
SerialNumber = sensor.Element(romIdName).Value,
Data = sensor.Elements().Where(element => element != sensor.Element(romIdName))
});
return Ok();
}
}
}
```
Update log controller for ow-server-enet | ```c#
using HardwareSensorSystem.SensorTechnology.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace HardwareSensorSystem.SensorTechnology.Controllers
{
public class OwServerEnet2LogController : Controller
{
private SensorTechnologyDbContext _context;
public OwServerEnet2LogController(SensorTechnologyDbContext context)
{
_context = context;
}
[AllowAnonymous]
[HttpPost("api/devices/{deviceId}/log/ow-server-enet")]
public async Task<IActionResult> Log([FromRoute]int deviceId)
{
XDocument file = XDocument.Load(HttpContext.Request.Body);
var romIdName = XName.Get("ROMId", file.Root.Name.NamespaceName);
var dataSensors = file.Root.Elements().Select(sensor => new
{
SerialNumber = sensor.Element(romIdName).Value,
Data = sensor.Elements().Where(element => element != sensor.Element(romIdName))
});
var groupedProperties = await _context.Sensors.Where(sensor => sensor.DeviceId.Equals(deviceId))
.Join(_context.SensorProperties
.Where(property => property.Name.Equals("SENSOR_ID"))
.Where(property => dataSensors.Any(e => e.SerialNumber.Equals(property.Value))),
sensor => sensor.Id,
property => property.SensorId,
(sensor, _) => sensor)
.GroupJoin(_context.SensorProperties,
sensor => sensor.Id,
property => property.SensorId,
(_, properties) => properties)
.ToListAsync();
foreach (var properties in groupedProperties)
{
var serialNumber = properties.Single(property => property.Name.Equals("SENSOR_ID")).Value;
try
{
var data = dataSensors.Single(e => e.SerialNumber.Equals(serialNumber)).Data;
}
catch
{
}
}
return Ok();
}
}
}
``` |
7f2b0ba9-c606-42cc-a60a-57c604b17b17 | {
"language": "C#"
} | ```c#
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
namespace Aerospike.Client
{
/// <summary>
/// Lua static configuration variables. These variables apply to all AerospikeClient instances
/// in a single process.
/// </summary>
public sealed class LuaConfig
{
/// <summary>
/// Directory location which contains user defined Lua source files.
/// </summary>
public static string PackagePath = "udf/?.lua";
/// <summary>
/// Maximum number of Lua runtime instances to cache at any point in time.
/// Each query with an aggregation function requires a Lua instance.
/// If the number of concurrent queries exceeds the Lua pool size, a new Lua
/// instance will still be created, but it will not be returned to the pool.
/// </summary>
public static int InstancePoolSize = 5;
}
}
```
Replace more hard-coded directory separators with "Path.DirectorySeparatorChar" | ```c#
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.IO;
namespace Aerospike.Client
{
/// <summary>
/// Lua static configuration variables. These variables apply to all AerospikeClient instances
/// in a single process.
/// </summary>
public sealed class LuaConfig
{
/// <summary>
/// Directory location which contains user defined Lua source files.
/// </summary>
public static string PackagePath = "udf" + Path.DirectorySeparatorChar + "?.lua";
/// <summary>
/// Maximum number of Lua runtime instances to cache at any point in time.
/// Each query with an aggregation function requires a Lua instance.
/// If the number of concurrent queries exceeds the Lua pool size, a new Lua
/// instance will still be created, but it will not be returned to the pool.
/// </summary>
public static int InstancePoolSize = 5;
}
}
``` |
605f36a9-ad35-4ad8-a1fd-ab5c64363269 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Xamarin.Forms;
namespace XF_TabbedPage
{
public class Page3 : ContentPage
{
public Page3()
{
NavigationPage.SetHasNavigationBar(this, false);
var label = new Label
{
Text = "Hello TabbedPage 3!",
TextColor = Color.FromHex("#666666"),
HorizontalTextAlignment = TextAlignment.Center
};
var button = new Button
{
Text = "GoTo NextPage",
Command = new Command(() =>
{
Navigation.PushAsync(new Page3());
})
};
Title = "TabPage 3";
BackgroundColor = Color.FromHex("#eeeeff");
Content = new StackLayout
{
Padding = 8,
VerticalOptions = LayoutOptions.CenterAndExpand,
Children =
{
label,
button
}
};
}
}
}
```
Add button to move to page1. it means both of destination page must set "HasNavigationBar=False" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Xamarin.Forms;
namespace XF_TabbedPage
{
public class Page3 : ContentPage
{
public Page3()
{
NavigationPage.SetHasNavigationBar(this, false);
var label = new Label
{
Text = "Hello TabbedPage 3!",
TextColor = Color.FromHex("#666666"),
HorizontalTextAlignment = TextAlignment.Center
};
var button1 = new Button
{
Text = "GoTo Page3",
Command = new Command(() =>
{
Navigation.PushAsync(new Page3());
})
};
var button2 = new Button
{
Text = "GoTo Page1",
Command = new Command(() =>
{
Navigation.PushAsync(new Page1());
})
};
Title = "TabPage 3";
BackgroundColor = Color.FromHex("#eeeeff");
Content = new StackLayout
{
Padding = 8,
VerticalOptions = LayoutOptions.CenterAndExpand,
Children =
{
label,
button1,
button2
}
};
}
}
}
``` |
d0ea42df-ea22-4b1c-ade6-75ed92e94bb2 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.General
{
public class ConfigImageTypes
{
[JsonProperty("base_url")]
public string BaseUrl { get; set; }
[JsonProperty("secure_base_url")]
public string SecureBaseUrl { get; set; }
[JsonProperty("poster_sizes")]
public List<string> PosterSizes { get; set; }
[JsonProperty("backdrop_sizes")]
public List<string> BackdropSizes { get; set; }
[JsonProperty("profile_sizes")]
public List<string> ProfileSizes { get; set; }
[JsonProperty("logo_sizes")]
public List<string> LogoSizes { get; set; }
}
}```
Add missing field to config | ```c#
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.General
{
public class ConfigImageTypes
{
[JsonProperty("base_url")]
public string BaseUrl { get; set; }
[JsonProperty("secure_base_url")]
public string SecureBaseUrl { get; set; }
[JsonProperty("poster_sizes")]
public List<string> PosterSizes { get; set; }
[JsonProperty("backdrop_sizes")]
public List<string> BackdropSizes { get; set; }
[JsonProperty("profile_sizes")]
public List<string> ProfileSizes { get; set; }
[JsonProperty("logo_sizes")]
public List<string> LogoSizes { get; set; }
[JsonProperty("still_sizes")]
public List<string> StillSizes { get; set; }
}
}``` |
ba3f37b1-1191-494c-a356-c5f57fea973e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace MonsterClicker
{
using Interfaces;
using System.Numerics;
using System.Windows.Forms;
public class Monster : IMonster
{
private BigInteger health;
private static BigInteger startHealth = 10;
private BigInteger nextLevelHealth = startHealth;
//private List<string> photosPaths;
private Random randomGenerator;
//TODO: exp and money - every next monster must have more money and exp
//TODO: exp must be part of health
//TODO: make class Boss
//TODO: make homework
//TODO: Timer
public Monster()
{
this.Health = startHealth;
//this.photosPaths = new List<string>();
this.randomGenerator = new System.Random();
}
public BigInteger Health
{
get { return this.health; }
set { this.health = value; }
}
public void TakeDamage(BigInteger damage)
{
this.Health -= damage;
}
public void GenerateHealth()
{
nextLevelHealth += (nextLevelHealth / 10);
this.health = nextLevelHealth;
}
public int GetRandomNumber()
{
var number = randomGenerator.Next(0, 5);
return number;
}
}
}```
Make a picture unque for every next level | ```c#
using System;
using System.Collections.Generic;
namespace MonsterClicker
{
using Interfaces;
using System.Numerics;
using System.Windows.Forms;
public class Monster : IMonster
{
private BigInteger health;
private static BigInteger startHealth = 10;
private BigInteger nextLevelHealth = startHealth;
//private List<string> photosPaths;
private Random randomGenerator;
//TODO: exp and money - every next monster must have more money and exp
//TODO: exp must be part of health
//TODO: make class Boss
//TODO: make homework
//TODO: Timer
public Monster()
{
this.Health = startHealth;
//this.photosPaths = new List<string>();
this.randomGenerator = new System.Random();
}
public BigInteger Health
{
get { return this.health; }
set { this.health = value; }
}
public void TakeDamage(BigInteger damage)
{
this.Health -= damage;
}
public void GenerateHealth()
{
nextLevelHealth += (nextLevelHealth / 10);
this.health = nextLevelHealth;
}
public int GetRandomNumber()
{
int firstNumber = 0;
var number = randomGenerator.Next(0, 5);
if (number == firstNumber)
{
while (number == firstNumber)
{
number = randomGenerator.Next(0, 5);
}
}
else
{
firstNumber = number;
}
return number;
}
}
}``` |
9e9352c4-6d62-4bcd-af5c-5e96074d53a7 | {
"language": "C#"
} | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}```
Allow to run build even if git repo informations are not available | ```c#
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
try
{
_versionContext.Git = GitVersion();
}
catch
{
_versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion();
}
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
``` |
620193e4-0ba1-4a81-be0c-aa53582f7301 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.IO;
internal class Mono50Compiler : Compiler
{
public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { }
public override string Name => "Mono C# 5.0";
protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile)
{
var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll");
string processArguments;
if (platform == Platform.Windows)
{
processArguments = $"-sdk:2 -debug+ -langversion:Future -r:\"{systemCoreDllPath}\" {responseFile}";
}
else
{
processArguments = $"-sdk:2 -debug+ -langversion:Future {responseFile}";
}
var process = new Process();
process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir);
return process;
}
}
```
Fix Mono 5.0 run under Unity 5.5+ | ```c#
using System.Diagnostics;
using System.IO;
using System.Linq;
internal class Mono50Compiler : Compiler
{
public Mono50Compiler(Logger logger, string compilerPath) : base(logger, compilerPath, null) { }
public override string Name => "Mono C# 5.0";
protected override Process CreateCompilerProcess(Platform platform, string monoProfileDir, string unityEditorDataDir, string responseFile)
{
var systemCoreDllPath = Path.Combine(monoProfileDir, "System.Core.dll");
string processArguments;
if (platform == Platform.Windows && GetSdkValue(responseFile) == "2.0")
{
// -sdk:2.0 requires System.Core.dll. but -sdk:unity doesn't.
processArguments = $"-r:\"{systemCoreDllPath}\" {responseFile}";
}
else
{
processArguments = responseFile;
}
var process = new Process();
process.StartInfo = CreateOSDependentStartInfo(platform, ProcessRuntime.CLR40, compilerPath, processArguments, unityEditorDataDir);
return process;
}
private string GetSdkValue(string responseFile)
{
var lines = File.ReadAllLines(responseFile.Substring(1));
var sdkArg = lines.FirstOrDefault(line => line.StartsWith("-sdk:"));
return (sdkArg != null) ? sdkArg.Substring(5) : "";
}
}
``` |
217c2273-eb54-43b2-ad1c-48b640697a13 | {
"language": "C#"
} | ```c#
@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel
@{
Layout = null;
var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant();
}
@foreach (var item in Model.Items)
{
<a id="i@(item.Sequence)" class="hidden" href="@(Url.Action("Details", new { id = item.ErrorId }))" data-href="@(Url.Action("Details", new { id = item.ErrorId }))?application={application}&host={host}&source={source}&type={type}&search={search}">@(item.Sequence)</a>
<tr data-forward-click="A#i@(item.Sequence)" style="cursor: pointer;">
<td>
@(item.Sequence)
<br /><small class="text-muted">@(item.RowNum)</small>
</td>
<td>
<span data-utctime="@(item.TimeUtc.Epoch())" data-format="@(dateFormat) hh:mm:ss">
@(item.TimeUtc.ToString()) (UTC)
</span>
<br />
<span class="floating-above"><small class="text-muted">@(item.TimeAgoText)</small></span>
<br />
</td>
<td>@item.Application</td>
<td>@item.Host</td>
<td>@item.Source</td>
<td>@item.Type</td>
<td>@item.Message</td>
</tr>
}```
Fix for email obfuscator of Cloudflare | ```c#
@model ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Models.Logs.ItemsModel
@{
Layout = null;
var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("yyyy", "yy").ToUpperInvariant();
}
@* Disable Email obfuscation by Cloudflare (which is not compatible with this rendering) *@
<!--email_off-->
@foreach (var item in Model.Items)
{
<a id="i@(item.Sequence)" class="hidden" href="@(Url.Action("Details", new { id = item.ErrorId }))" data-href="@(Url.Action("Details", new { id = item.ErrorId }))?application={application}&host={host}&source={source}&type={type}&search={search}">@(item.Sequence)</a>
<tr data-forward-click="A#i@(item.Sequence)" style="cursor: pointer;">
<td>
@(item.Sequence)
<br /><small class="text-muted">@(item.RowNum)</small>
</td>
<td>
<span data-utctime="@(item.TimeUtc.Epoch())" data-format="@(dateFormat) hh:mm:ss">
@(item.TimeUtc.ToString()) (UTC)
</span>
<br />
<span class="floating-above"><small class="text-muted">@(item.TimeAgoText)</small></span>
<br />
</td>
<td>@item.Application</td>
<td>@item.Host</td>
<td>@item.Source</td>
<td>@item.Type</td>
<td>@item.Message</td>
</tr>
}
<!--/email_off-->``` |
982d0ef3-cf21-4ef7-85b7-04c901e9e71c | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace PackageDiscovery.Finders
{
public sealed class NuGetPackageFinder : IPackageFinder
{
public const string Moniker = "NuGet";
public IReadOnlyCollection<Package> FindPackages(DirectoryInfo directory)
{
return directory
.GetFiles("packages.config", SearchOption.AllDirectories)
.Select(f => XDocument.Load(f.FullName))
.SelectMany(x => x.Root.Elements("package"))
.Select(x => new Package(Moniker, x.Attribute("id").Value, x.Attribute("version").Value))
.Distinct(p => new { p.Id, p.Version, p.IsDevelopmentPackage })
.OrderBy(p => p.Id)
.ThenBy(p => p.Version)
.ToList();
}
}
}
```
Enumerate packages.config file from repositories.config files. | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace PackageDiscovery.Finders
{
public sealed class NuGetPackageFinder : IPackageFinder
{
public const string Moniker = "NuGet";
public IReadOnlyCollection<Package> FindPackages(DirectoryInfo directory)
{
var packagesFromRepositories = (
from f in directory
.GetFiles("repositories.config", SearchOption.AllDirectories)
let x = XDocument.Load(f.FullName)
from r in x.Root.Elements("repository")
select new FileInfo(Path.Combine(f.Directory.FullName, r.Attribute("path").Value))
);
var standalonePackages = directory
.GetFiles("packages.config", SearchOption.AllDirectories);
return standalonePackages.Union(packagesFromRepositories)
.Select(f => XDocument.Load(f.FullName))
.SelectMany(x => x.Root.Elements("package"))
.Select(x => new Package(Moniker, x.Attribute("id").Value, x.Attribute("version").Value))
.Distinct(p => new { p.Id, p.Version, p.IsDevelopmentPackage })
.OrderBy(p => p.Id)
.ThenBy(p => p.Version)
.ToList();
}
}
}
``` |
78a2ef6a-c307-4ab6-a253-aaaf37b570d9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Contrib.MVC.Auth.Interfaces;
namespace Raven.Client.Contrib.MVC.Auth.Default
{
internal class BCryptSecurityEncoder : ISecurityEncoder
{
/// <summary>
/// Generates a unique token.
/// </summary>
/// <returns>The unique token.</returns>
public string GenerateToken()
{
return new Guid().ToString()
.ToLowerInvariant()
.Replace("-", "");
}
/// <summary>
/// Hashes the identifier with the provided salt.
/// </summary>
/// <param name="identifier">The identifier to hash.</param>
/// <returns>The hashed identifier.</returns>
public string Hash(string identifier)
{
return BCrypt.Net.BCrypt.HashPassword(identifier, workFactor: 10);
}
/// <summary>
/// Verifies if the identifier matches the hash.
/// </summary>
/// <param name="identifier">The identifier to check.</param>
/// <param name="hash">The hash to check against.</param>
/// <returns>true if the identifiers match, false otherwise.</returns>
public bool Verify(string identifier, string hash)
{
return BCrypt.Net.BCrypt.Verify(identifier, hash);
}
}
}
```
Include a pepper in the hashing algorithm. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Contrib.MVC.Auth.Interfaces;
namespace Raven.Client.Contrib.MVC.Auth.Default
{
internal class BCryptSecurityEncoder : ISecurityEncoder
{
/// <summary>
/// Generates a unique token.
/// </summary>
/// <returns>The unique token.</returns>
public string GenerateToken()
{
return new Guid().ToString()
.ToLowerInvariant()
.Replace("-", "");
}
/// <summary>
/// Hashes the identifier with the provided salt.
/// </summary>
/// <param name="identifier">The identifier to hash.</param>
/// <returns>The hashed identifier.</returns>
public string Hash(string identifier)
{
const string pepper = "BCryptSecurityEncoder";
string salt = BCrypt.Net.BCrypt.GenerateSalt(workFactor: 10);
return BCrypt.Net.BCrypt.HashPassword(identifier, salt + pepper);
}
/// <summary>
/// Verifies if the identifier matches the hash.
/// </summary>
/// <param name="identifier">The identifier to check.</param>
/// <param name="hash">The hash to check against.</param>
/// <returns>true if the identifiers match, false otherwise.</returns>
public bool Verify(string identifier, string hash)
{
return BCrypt.Net.BCrypt.Verify(identifier, hash);
}
}
}
``` |
837cb345-4ce4-4acb-b69b-81b718b76473 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
}
private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer)
{
var array = new JsonArray();
array.AddRange(list.Select(serializer.Serialize));
return array;
}
private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var list = new List<T>();
list.AddRange(json.Array.Select(serializer.Deserialize<T>));
return list;
}
}
}```
Decrease allocations in List Serializer | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Manatee.Json.Serialization.Internal.AutoRegistration
{
internal class ListSerializationDelegateProvider : SerializationDelegateProviderBase
{
public override bool CanHandle(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
}
private static JsonValue _Encode<T>(List<T> list, JsonSerializer serializer)
{
var array = new JsonValue[list.Count];
for (int ii = 0; ii < array.Length; ++ii)
{
array[ii] = serializer.Serialize(list[ii]);
}
return new JsonArray(array);
}
private static List<T> _Decode<T>(JsonValue json, JsonSerializer serializer)
{
var array = json.Array;
var list = new List<T>(array.Count);
for (int ii = 0; ii < array.Count; ++ii)
{
list.Add(serializer.Deserialize<T>(array[ii]));
}
return list;
}
}
}``` |
dc00fa53-1299-41b2-8b86-5c3f90770d8c | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Moq")]
[assembly: AssemblyDescription("Autofac Moq Integration")]
[assembly: ComVisible(false)]```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Moq")]
[assembly: ComVisible(false)]``` |
0f6a60b0-627e-42e8-8e8b-e8e47fac27da | {
"language": "C#"
} | ```c#
namespace MyStudio.ViewModels
{
using Catel;
using Catel.MVVM;
using MyStudio.Models;
using MyStudio.Services;
public class RibbonViewModel : ViewModelBase
{
private StudioStateModel model;
private ICommandsService commandsService;
public RibbonViewModel(StudioStateModel model,
ICommandsService commandsService)
{
Argument.IsNotNull(() => model);
Argument.IsNotNull(() => commandsService);
this.model = model;
this.commandsService = commandsService;
}
public Command StartCommand
{
get
{
return this.commandsService != null ? this.commandsService.StartCommand : null;
}
}
public Command UndoCommand
{
get
{
return this.commandsService != null ? this.commandsService.UndoCommand : null;
}
}
public Command RedoCommand
{
get
{
return this.commandsService != null ? this.commandsService.RedoCommand : null;
}
}
}
}
```
Add recently used items data | ```c#
namespace MyStudio.ViewModels
{
using System.Collections.Generic;
using Catel;
using Catel.MVVM;
using MyStudio.Models;
using MyStudio.Services;
using Orchestra.Models;
using Orchestra.Services;
public class RibbonViewModel : ViewModelBase
{
private StudioStateModel model;
private ICommandsService commandsService;
private IRecentlyUsedItemsService recentlyUsedItemsService;
public RibbonViewModel(StudioStateModel model,
ICommandsService commandsService,
IRecentlyUsedItemsService recentlyUsedItemsService)
{
Argument.IsNotNull(() => model);
Argument.IsNotNull(() => commandsService);
Argument.IsNotNull(() => recentlyUsedItemsService);
this.model = model;
this.commandsService = commandsService;
this.recentlyUsedItemsService = recentlyUsedItemsService;
this.RecentlyUsedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.Items);
this.PinnedItems = new List<RecentlyUsedItem>(this.recentlyUsedItemsService.PinnedItems);
}
public Command StartCommand
{
get
{
return this.commandsService != null ? this.commandsService.StartCommand : null;
}
}
public Command UndoCommand
{
get
{
return this.commandsService != null ? this.commandsService.UndoCommand : null;
}
}
public Command RedoCommand
{
get
{
return this.commandsService != null ? this.commandsService.RedoCommand : null;
}
}
public List<RecentlyUsedItem> RecentlyUsedItems { get; private set; }
public List<RecentlyUsedItem> PinnedItems { get; private set; }
}
}
``` |
207036b7-43de-4981-844d-9895850e881c | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using Spectre.Console;
namespace Spectre.Cli.Internal
{
[Description("Displays the CLI library version")]
[SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")]
internal sealed class VersionCommand : Command<VersionCommand.Settings>
{
private readonly IAnsiConsole _writer;
public VersionCommand(IConfiguration configuration)
{
_writer = configuration?.Settings?.Console ?? AnsiConsole.Console;
}
public sealed class Settings : CommandSettings
{
}
public override int Execute(CommandContext context, Settings settings)
{
var version = typeof(VersionCommand)?.Assembly?.GetName()?.Version?.ToString();
version ??= "?";
_writer.Write($"Spectre.Cli version {version}");
return 0;
}
}
}
```
Fix displayed version in built-in version command | ```c#
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Spectre.Console;
namespace Spectre.Cli.Internal
{
[Description("Displays the CLI library version")]
[SuppressMessage("Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Injected")]
internal sealed class VersionCommand : Command<VersionCommand.Settings>
{
private readonly IAnsiConsole _writer;
public VersionCommand(IConfiguration configuration)
{
_writer = configuration?.Settings?.Console ?? AnsiConsole.Console;
}
public sealed class Settings : CommandSettings
{
}
public override int Execute(CommandContext context, Settings settings)
{
_writer.MarkupLine(
"[yellow]Spectre.Cli[/] version [aqua]{0}[/]",
GetVersion(typeof(VersionCommand)?.Assembly));
_writer.MarkupLine(
"[yellow]Spectre.Console[/] version [aqua]{0}[/]",
GetVersion(typeof(IAnsiConsole)?.Assembly));
return 0;
}
[SuppressMessage("Design", "CA1031:Do not catch general exception types")]
private static string GetVersion(Assembly? assembly)
{
if (assembly == null)
{
return "?";
}
try
{
var info = FileVersionInfo.GetVersionInfo(assembly.Location);
return info.ProductVersion ?? "?";
}
catch
{
return "?";
}
}
}
}
``` |
bff22912-3342-471a-942b-83bed12b6450 | {
"language": "C#"
} | ```c#
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
```
Set the version to 1.3 since we're releasing. | ```c#
using System.Reflection;
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.