doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
cbd322b0-58cc-44e4-9b4a-e21619ceb06b | {
"language": "C#"
} | ```c#
using Umbraco.Core;
using Umbraco.Core.Components;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Implements an Application Event Handler for managing redirect urls tracking.
/// </summary>
/// <remarks>
/// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para>
/// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para>
/// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para>
/// </remarks>
[RuntimeLevel(MinLevel = RuntimeLevel.Run)]
public class RedirectTrackingComposer : ComponentComposer<RelateOnCopyComponent>, ICoreComposer
{ }
}
```
Fix the redirect tracking composer | ```c#
using Umbraco.Core;
using Umbraco.Core.Components;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Implements an Application Event Handler for managing redirect urls tracking.
/// </summary>
/// <remarks>
/// <para>when content is renamed or moved, we want to create a permanent 301 redirect from it's old url</para>
/// <para>not managing domains because we don't know how to do it - changing domains => must create a higher level strategy using rewriting rules probably</para>
/// <para>recycle bin = moving to and from does nothing: to = the node is gone, where would we redirect? from = same</para>
/// </remarks>
[RuntimeLevel(MinLevel = RuntimeLevel.Run)]
public class RedirectTrackingComposer : ComponentComposer<RedirectTrackingComponent>, ICoreComposer
{ }
}
``` |
1bdc12e0-095e-4490-a735-670178af8751 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using PdfSharp.Pdf.Advanced;
// ReSharper disable once CheckNamespace
namespace PdfSharp.Pdf
{
/// <summary>
/// Extension methods for the PdfSharp library PdfItem object.
/// </summary>
public static class PdfPageExtensions
{
/// <summary>
/// Get's all of the images from the specified page.
/// </summary>
/// <param name="page">The page to extract or retrieve images from.</param>
/// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param>
/// <returns>An enumeration of images contained on the page.</returns>
public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null)
{
if (page == null) throw new ArgumentNullException("item", "The provided PDF page was null.");
if (filter == null) filter = (pg, idx, img) => img;
int index = 0;
PdfDictionary resources = page.Elements.GetDictionary("/Resources");
if (resources != null) {
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null) {
ICollection<PdfItem> items = xObjects.Elements.Values;
foreach (PdfItem item in items) {
PdfReference reference = item as PdfReference;
if (reference != null) {
PdfDictionary xObject = reference.Value as PdfDictionary;
if (xObject.IsImage()) {
yield return filter.Invoke(page, index++, xObject.ToImage());
}
}
}
}
}
}
}
}```
Use var declaration. Fix ArgumentNullException parameter name. | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using PdfSharp.Pdf.Advanced;
// ReSharper disable once CheckNamespace
namespace PdfSharp.Pdf
{
/// <summary>
/// Extension methods for the PdfSharp library PdfItem object.
/// </summary>
public static class PdfPageExtensions
{
/// <summary>
/// Get's all of the images from the specified page.
/// </summary>
/// <param name="page">The page to extract or retrieve images from.</param>
/// <param name="filter">An optional filter to perform additional modifications or actions on the image.</param>
/// <returns>An enumeration of images contained on the page.</returns>
public static IEnumerable<Image> GetImages(this PdfPage page, Func<PdfPage, int, Image, Image> filter = null)
{
if (page == null) throw new ArgumentNullException("page", "The provided PDF page was null.");
if (filter == null) filter = (pg, idx, img) => img;
int index = 0;
var resources = page.Elements.GetDictionary("/Resources");
if (resources != null) {
var xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null) {
var items = xObjects.Elements.Values;
foreach (PdfItem item in items) {
var reference = item as PdfReference;
if (reference != null) {
var xObject = reference.Value as PdfDictionary;
if (xObject.IsImage()) {
yield return filter.Invoke(page, index++, xObject.ToImage());
}
}
}
}
}
}
}
}``` |
5bdc4a43-2217-4953-88d8-187818011c24 | {
"language": "C#"
} | ```c#
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.QuickAccessViewModel
<div class="page-admin-wrapper admin-wrapper">
@foreach (var category in Model.Categories)
{
<a href="@category.Link" class="button @category.CssClass @(category.LaunchModal ? "launch-modal" : "")" data-toggle="popover" data-placement="top" data-trigger="click" data-title="@(!string.IsNullOrWhiteSpace(category.Link) ? category.DesktopText : "")" data-container="body"><span class="click-through"><span class="@category.Icon" style="float: left;"></span><span class="hidden-xs visible-sm visible-md visible-lg" style="float: left;">@category.DesktopText</span><span class="visible-xs hidden-sm hidden-md hidden-lg" style="float: left;">@category.MobileText</span></span></a>
}
@foreach (var category in Model.Categories)
{
<div id="popover-@category.CssClass" class="list-group" style="display: none;">
<div class="popover-menu">
@foreach (var action in category.Actions)
{
<a class="list-group-item @(action.LaunchModal ? "launch-modal" : "")" onclick="@action.JavaScript" href="@action.Link" data-title="@action.Text"><span class="@action.Icon"></span>@action.Text</a>
}
</div>
</div>
}
</div>```
Bring Attention to the Quick Access Panel On Page Load | ```c#
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.QuickAccessViewModel
<div class="page-admin-wrapper admin-wrapper animated zoomInUp">
@foreach (var category in Model.Categories)
{
<a href="@category.Link" class="button @category.CssClass @(category.LaunchModal ? "launch-modal" : "")" data-toggle="popover" data-placement="top" data-trigger="click" data-title="@(!string.IsNullOrWhiteSpace(category.Link) ? category.DesktopText : "")" data-container="body"><span class="click-through"><span class="@category.Icon" style="float: left;"></span><span class="hidden-xs visible-sm visible-md visible-lg" style="float: left;">@category.DesktopText</span><span class="visible-xs hidden-sm hidden-md hidden-lg" style="float: left;">@category.MobileText</span></span></a>
}
@foreach (var category in Model.Categories)
{
<div id="popover-@category.CssClass" class="list-group" style="display: none;">
<div class="popover-menu">
@foreach (var action in category.Actions)
{
<a class="list-group-item @(action.LaunchModal ? "launch-modal" : "")" onclick="@action.JavaScript" href="@action.Link" data-title="@action.Text"><span class="@action.Icon"></span>@action.Text</a>
}
</div>
</div>
}
</div>``` |
3468c2ed-4454-431b-bb75-860994f55bb1 | {
"language": "C#"
} | ```c#
using System;
using MyTrips.DataObjects;
using MyTrips.DataStore.Abstractions;
using System.Threading.Tasks;
using MyTrips.Utils;
using System.Collections.Generic;
namespace MyTrips.DataStore.Azure.Stores
{
public class TripStore : BaseStore<Trip>, ITripStore
{
IPhotoStore photoStore;
public TripStore()
{
photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>();
}
public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false)
{
var items = await base.GetItemsAsync(skip, take, forceRefresh);
foreach (var item in items)
{
item.Photos = new List<Photo>();
var photos = await photoStore.GetTripPhotos(item.Id);
foreach(var photo in photos)
item.Photos.Add(photo);
}
return items;
}
public override async Task<Trip> GetItemAsync(string id)
{
var item = await base.GetItemAsync(id);
if (item.Photos == null)
item.Photos = new List<Photo>();
else
item.Photos.Clear();
var photos = await photoStore.GetTripPhotos(item.Id);
foreach(var photo in photos)
item.Photos.Add(photo);
return item;
}
}
}
```
Make sure we order by sequence | ```c#
using System;
using MyTrips.DataObjects;
using MyTrips.DataStore.Abstractions;
using System.Threading.Tasks;
using MyTrips.Utils;
using System.Collections.Generic;
using System.Linq;
namespace MyTrips.DataStore.Azure.Stores
{
public class TripStore : BaseStore<Trip>, ITripStore
{
IPhotoStore photoStore;
public TripStore()
{
photoStore = ServiceLocator.Instance.Resolve<IPhotoStore>();
}
public override async Task<IEnumerable<Trip>> GetItemsAsync(int skip = 0, int take = 100, bool forceRefresh = false)
{
var items = await base.GetItemsAsync(skip, take, forceRefresh);
foreach (var item in items)
{
item.Photos = new List<Photo>();
var photos = await photoStore.GetTripPhotos(item.Id);
foreach(var photo in photos)
item.Photos.Add(photo);
}
return items;
}
public override async Task<Trip> GetItemAsync(string id)
{
var item = await base.GetItemAsync(id);
if (item.Photos == null)
item.Photos = new List<Photo>();
else
item.Photos.Clear();
var photos = await photoStore.GetTripPhotos(item.Id);
foreach(var photo in photos)
item.Photos.Add(photo);
item.Points = item.Points.OrderBy(p => p.Sequence).ToArray();
return item;
}
}
}
``` |
b4353bac-52ed-4658-8b32-2abe1361160e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio {
public static class AggregatePackageSource {
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source) {
return source == Instance;
}
public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources());
}
public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
}
}
}```
Replace Enumerable.Repeat call with an one-element array. | ```c#
using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio {
public static class AggregatePackageSource {
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source) {
return source == Instance;
}
public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
return new[] { Instance }.Concat(provider.LoadPackageSources());
}
public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
}
}
}``` |
5fa58cad-3058-45fa-a53d-d918f2fba82b | {
"language": "C#"
} | ```c#
using static System.Console;
using System.Linq;
using CIV.Ccs;
using CIV.Hml;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
var prova = HmlFacade.ParseAll(hmlText);
WriteLine(prova.Check(processes["Prison"]));
}
}
}
```
Revert "Remove RandomTrace stuff from main" | ```c#
using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
``` |
216a6407-7ab9-4cc1-9328-1812ceb87bde | {
"language": "C#"
} | ```c#
using EOBot.Interpreter.Extensions;
using System.Collections.Generic;
using System.Linq;
namespace EOBot.Interpreter.States
{
public class StatementEvaluator : IScriptEvaluator
{
private readonly IEnumerable<IScriptEvaluator> _evaluators;
public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators)
{
_evaluators = evaluators;
}
public bool Evaluate(ProgramState input)
{
while (input.Current().TokenType == BotTokenType.NewLine)
input.Expect(BotTokenType.NewLine);
return (Evaluate<AssignmentEvaluator>(input)
|| Evaluate<KeywordEvaluator>(input)
|| Evaluate<LabelEvaluator>(input)
|| Evaluate<FunctionEvaluator>(input))
&& input.Expect(BotTokenType.NewLine);
}
private bool Evaluate<T>(ProgramState input)
where T : IScriptEvaluator
{
return _evaluators
.OfType<T>()
.Single()
.Evaluate(input);
}
}
}```
Allow statements to end with EOF instead of forcing a newline for every evaluated statement | ```c#
using EOBot.Interpreter.Extensions;
using System.Collections.Generic;
using System.Linq;
namespace EOBot.Interpreter.States
{
public class StatementEvaluator : IScriptEvaluator
{
private readonly IEnumerable<IScriptEvaluator> _evaluators;
public StatementEvaluator(IEnumerable<IScriptEvaluator> evaluators)
{
_evaluators = evaluators;
}
public bool Evaluate(ProgramState input)
{
while (input.Current().TokenType == BotTokenType.NewLine)
input.Expect(BotTokenType.NewLine);
return (Evaluate<AssignmentEvaluator>(input)
|| Evaluate<KeywordEvaluator>(input)
|| Evaluate<LabelEvaluator>(input)
|| Evaluate<FunctionEvaluator>(input))
&& (input.Expect(BotTokenType.NewLine) || input.Expect(BotTokenType.EOF));
}
private bool Evaluate<T>(ProgramState input)
where T : IScriptEvaluator
{
return _evaluators
.OfType<T>()
.Single()
.Evaluate(input);
}
}
}``` |
affd9dc6-f3a5-468b-9704-192f0850e8e8 | {
"language": "C#"
} | ```c#
namespace Sharpy.Core {
/// <summary>
/// <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para>
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> {
/// <summary>
/// <para>Generate next element.</para>
/// </summary>
/// <returns>
/// A generated element.
/// </returns>
new T Generate();
}
}```
Remove new keyword from interface | ```c#
namespace Sharpy.Core {
/// <summary>
/// <para>Represent a generator which can generate any amount of elements by invoking method <see cref="Generate" />.</para>
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> {
/// <summary>
/// <para>Generate next element.</para>
/// </summary>
/// <returns>
/// A generated element.
/// </returns>
T Generate();
}
}``` |
e2304e43-fb02-45b6-a20b-8edde68ef146 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Screens
{
public class EditorScreen : Container
{
public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
protected override Container<Drawable> Content => content;
private readonly Container content;
public EditorScreen()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = content = new Container { RelativeSizeAxes = Axes.Both };
}
protected override void LoadComplete()
{
base.LoadComplete();
this.ScaleTo(0.75f).FadeTo(0)
.Then()
.ScaleTo(1f, 500, Easing.OutQuint).FadeTo(1f, 250, Easing.OutQuint);
}
public void Exit()
{
this.ScaleTo(1.25f, 500).FadeOut(250).Expire();
}
}
}
```
Remove scale effect on editor screen switches | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Screens
{
public class EditorScreen : Container
{
public readonly Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
protected override Container<Drawable> Content => content;
private readonly Container content;
public EditorScreen()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = content = new Container { RelativeSizeAxes = Axes.Both };
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeTo(0)
.Then()
.FadeTo(1f, 250, Easing.OutQuint);
}
public void Exit()
{
this.FadeOut(250).Expire();
}
}
}
``` |
a3a18567-9dca-4446-8cb0-5d319c34b725 | {
"language": "C#"
} | ```c#
using System.Configuration;
namespace SchemaZen.test {
public class ConfigHelper {
public static string TestDB {
get { return ConfigurationManager.AppSettings["testdb"]; }
}
public static string TestSchemaDir {
get { return ConfigurationManager.AppSettings["test_schema_dir"]; }
}
public static string SqlDbDiffPath {
get { return ConfigurationManager.AppSettings["SqlDbDiffPath"]; }
}
}
}
```
Read environment variables for test settings. | ```c#
using System;
using System.Configuration;
namespace SchemaZen.test {
public class ConfigHelper {
public static string TestDB {
get { return GetSetting("testdb"); }
}
public static string TestSchemaDir {
get { return GetSetting("test_schema_dir"); }
}
public static string SqlDbDiffPath {
get { return GetSetting("SqlDbDiffPath"); }
}
private static string GetSetting(string key) {
var val = Environment.GetEnvironmentVariable(key);
return val ?? ConfigurationManager.AppSettings[key];
}
}
}
``` |
19735692-650d-4a36-8f21-b7f41563635a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public long[] AddressList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
```
Add extra property to use new long Id's | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public int[] AddressList { get; set; }
public long[] LocationList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
``` |
25ad385e-edad-4b9c-aa8c-4d6eba9f782e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpotiPeek.App
{
class TrackModel
{
public string SongTitle;
public string ArtistName;
public string AlbumTitle;
public string AlbumYear;
}
}
```
Remove unused property from Track model | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpotiPeek.App
{
class TrackModel
{
public string SongTitle;
public string ArtistName;
public string AlbumTitle;
}
}
``` |
f7dd0f55-3ee3-4212-9282-992ea8bfcfb0 | {
"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
using System.ComponentModel;
namespace osu.Game.GameModes.Play
{
public enum PlayMode
{
[Description(@"osu!")]
Osu = 0,
[Description(@"taiko")]
Taiko = 1,
[Description(@"catch")]
Catch = 2,
[Description(@"mania")]
Mania = 3
}
}
```
Add osu! prefix to mode descriptions. | ```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 System.ComponentModel;
namespace osu.Game.GameModes.Play
{
public enum PlayMode
{
[Description(@"osu!")]
Osu = 0,
[Description(@"osu!taiko")]
Taiko = 1,
[Description(@"osu!catch")]
Catch = 2,
[Description(@"osu!mania")]
Mania = 3
}
}
``` |
09f2bdd3-8af0-4e90-90e5-beadf133df30 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using Giles.Core.Utility;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
}```
Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
if (filters.Count() == 0)
remoteTestRunner.Run(listener);
else
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
}``` |
aa5d6d1b-aa27-41e4-a25c-3a4702c26dbf | {
"language": "C#"
} | ```c#
using System.Text;
using dot10.IO;
namespace dot10.dotNET {
/// <summary>
/// Represents the #Strings stream
/// </summary>
public class StringsStream : DotNetStream {
/// <inheritdoc/>
public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <summary>
/// Read a <see cref="string"/>
/// </summary>
/// <param name="offset">Offset of string</param>
/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
public string Read(uint offset) {
var data = imageStream.ReadBytesUntilByte(0);
if (data == null)
return null;
return Encoding.UTF8.GetString(data);
}
}
}
```
Return null if invalid offset and seek to the offset | ```c#
using System.Text;
using dot10.IO;
namespace dot10.dotNET {
/// <summary>
/// Represents the #Strings stream
/// </summary>
public class StringsStream : DotNetStream {
/// <inheritdoc/>
public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <summary>
/// Read a <see cref="string"/>
/// </summary>
/// <param name="offset">Offset of string</param>
/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
public string Read(uint offset) {
if (offset >= imageStream.Length)
return null;
imageStream.Position = offset;
var data = imageStream.ReadBytesUntilByte(0);
if (data == null)
return null;
return Encoding.UTF8.GetString(data);
}
}
}
``` |
8fa7e633-59e7-4a39-8c78-635d1abb7684 | {
"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.
namespace osu.Game.Online.Multiplayer
{
public enum RoomCategory
{
Normal,
Spotlight
}
}
```
Add realtime to room categories | ```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.
namespace osu.Game.Online.Multiplayer
{
public enum RoomCategory
{
Normal,
Spotlight,
Realtime,
}
}
``` |
01d167cf-abd5-403d-90f6-a2bdf2a3a506 | {
"language": "C#"
} | ```c#
using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height); }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
}```
Fix issue where ratio was always returning "1" | ```c#
using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height; }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
}``` |
65c5b04b-3928-4471-a6c4-6d2a7c545d21 | {
"language": "C#"
} | ```c#
using System;
namespace Stratis.Bitcoin.Features.Wallet
{
/// <summary>
/// An indicator on how fast a transaction will be accepted in a block
/// </summary>
public enum FeeType
{
/// <summary>
/// Slow.
/// </summary>
Low = 0,
/// <summary>
/// Avarage.
/// </summary>
Medium = 1,
/// <summary>
/// Fast.
/// </summary>
High = 105
}
public static class FeeParser
{
public static FeeType Parse(string value)
{
if (Enum.TryParse<FeeType>(value, true, out var ret))
return ret;
return FeeType.Medium;
}
/// <summary>
/// Map a fee type to the number of confirmations
/// </summary>
public static int ToConfirmations(this FeeType fee)
{
switch (fee)
{
case FeeType.Low:
return 50;
case FeeType.Medium:
return 20;
case FeeType.High:
return 5;
}
throw new WalletException("Invalid fee");
}
}
}
```
Make FeeParser throw if the fee parsed is not low, medium or high (previously defaulted to medium0 | ```c#
using System;
namespace Stratis.Bitcoin.Features.Wallet
{
/// <summary>
/// An indicator of how fast a transaction will be accepted in a block.
/// </summary>
public enum FeeType
{
/// <summary>
/// Slow.
/// </summary>
Low = 0,
/// <summary>
/// Avarage.
/// </summary>
Medium = 1,
/// <summary>
/// Fast.
/// </summary>
High = 105
}
public static class FeeParser
{
public static FeeType Parse(string value)
{
bool isParsed = Enum.TryParse<FeeType>(value, true, out var result);
if (!isParsed)
{
throw new FormatException($"FeeType {value} is not a valid FeeType");
}
return result;
}
/// <summary>
/// Map a fee type to the number of confirmations
/// </summary>
public static int ToConfirmations(this FeeType fee)
{
switch (fee)
{
case FeeType.Low:
return 50;
case FeeType.Medium:
return 20;
case FeeType.High:
return 5;
}
throw new WalletException("Invalid fee");
}
}
}
``` |
a17aa93c-e4c1-45d3-a100-3653152bb43d | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Infusion.EngineScripts
{
public sealed class ScriptEngine
{
private readonly IScriptEngine[] engines;
private string scriptRootPath;
public ScriptEngine(params IScriptEngine[] engines)
{
this.engines = engines;
}
public string ScriptRootPath
{
get => scriptRootPath;
set
{
scriptRootPath = value;
ForeachEngine(engine => engine.ScriptRootPath = value);
}
}
public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
}
public void Reset() => ForeachEngine(engine => engine.Reset());
private void ForeachEngine(Action<IScriptEngine> engineAction)
{
foreach (var engine in engines)
engineAction(engine);
}
private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
{
foreach (var engine in engines)
await engineAction(engine);
}
}
}
```
Set current directory for initial script. | ```c#
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Infusion.EngineScripts
{
public sealed class ScriptEngine
{
private readonly IScriptEngine[] engines;
private string scriptRootPath;
public ScriptEngine(params IScriptEngine[] engines)
{
this.engines = engines;
}
public string ScriptRootPath
{
get => scriptRootPath;
set
{
scriptRootPath = value;
ForeachEngine(engine => engine.ScriptRootPath = value);
}
}
public Task ExecuteInitialScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
var currentRoot = Path.GetDirectoryName(scriptPath);
Directory.SetCurrentDirectory(currentRoot);
ScriptRootPath = currentRoot;
return ExecuteScript(scriptPath, cancellationTokenSource);
}
public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
if (!File.Exists(scriptPath))
throw new FileNotFoundException($"Script file not found: {scriptPath}", scriptPath);
await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
}
public void Reset() => ForeachEngine(engine => engine.Reset());
private void ForeachEngine(Action<IScriptEngine> engineAction)
{
foreach (var engine in engines)
engineAction(engine);
}
private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
{
foreach (var engine in engines)
await engineAction(engine);
}
}
}
``` |
cfeb894f-bee4-4402-b026-4a709a22b786 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LazyLibrary.Storage.Memory
{
internal class MemoryRepository<T> : IRepository<T> where T : IStorable
{
private List<T> repository = new List<T>();
public T GetById(int id)
{
return this.repository.Where(x => x.Id == id).SingleOrDefault();
}
public IQueryable<T> Get(System.Func<T, bool> exp = null)
{
return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
}
public void Upsert(T item)
{
var obj = GetById(item.Id);
if (obj != null)
{
// Update
this.repository.Remove(obj);
this.repository.Add(item);
}
else
{
// Insert
var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
item.Id = nextId;
this.repository.Add(item);
}
}
public void Delete(T item)
{
var obj = GetById(item.Id);
this.repository.Remove(obj);
}
}
}```
Check for objects existing using their equals operation rather than Ids | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LazyLibrary.Storage.Memory
{
internal class MemoryRepository<T> : IRepository<T> where T : IStorable
{
private List<T> repository = new List<T>();
public T GetById(int id)
{
return this.repository.SingleOrDefault(x => x.Id == id);
}
public IQueryable<T> Get(System.Func<T, bool> exp = null)
{
return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
}
public void Upsert(T item)
{
if (repository.Contains(item))
{
// Update
var obj = repository.Single(x => x.Equals(item));
this.repository.Remove(obj);
this.repository.Add(item);
}
else
{
// Insert
var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
item.Id = nextId;
this.repository.Add(item);
}
}
public void Delete(T item)
{
var obj = GetById(item.Id);
this.repository.Remove(obj);
}
}
}``` |
9e25b5fa-bbc2-4f3d-85d1-0f7fc054bb6f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;
namespace Shark
{
public class WorkerRole : SharkNodeBase
{
protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
{
return WasbConfiguration.GetWasbConfigKeys();
}
}
}
```
Put the scratch and warehouse directories up on WASB in the Shark test service. This gets CTAS to work. | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;
namespace Shark
{
public class WorkerRole : SharkNodeBase
{
protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
{
var rootFs = String.Format("wasb://shark@{0}.blob.core.windows.net",
WasbConfiguration.ReadWasbAccountsFile().First());
return WasbConfiguration.GetWasbConfigKeys()
.Add("hive.exec.scratchdir", rootFs + "/scratch")
.Add("hive.metastore.warehouse.dir", rootFs + "/warehouse");
}
}
}
``` |
50a83e82-c7f3-4418-97fa-52da78aa18b0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;
namespace Oberon0.Compiler.Expressions.Arithmetic
{
[Export(typeof(ICalculatable))]
class SubExpression: BinaryExpression, ICalculatable
{
public SubExpression()
{
Operator = TokenType.Sub;
}
public override Expression Calc(Block block)
{
if (this.BinaryConstChecker(block) == null)
{
return null;
}
// 1. Easy as int
var lhi = (ConstantExpression)LeftHandSide;
var rhi = (ConstantExpression)RightHandSide;
if (rhi.BaseType == lhi.BaseType && lhi.BaseType == BaseType.IntType)
{
return new ConstantIntExpression(lhi.ToInt32() - rhi.ToInt32());
}
// at least one of them is double
return new ConstantDoubleExpression(lhi.ToDouble() - lhi.ToDouble());
}
}
}
```
Fix sonarqube markup that sub has lhs and rhs identical | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;
namespace Oberon0.Compiler.Expressions.Arithmetic
{
[Export(typeof(ICalculatable))]
class SubExpression: BinaryExpression, ICalculatable
{
public SubExpression()
{
Operator = TokenType.Sub;
}
public override Expression Calc(Block block)
{
if (this.BinaryConstChecker(block) == null)
{
return null;
}
// 1. Easy as int
var leftHandSide = (ConstantExpression)LeftHandSide;
var rightHandSide = (ConstantExpression)RightHandSide;
if (rightHandSide.BaseType == leftHandSide.BaseType && leftHandSide.BaseType == BaseType.IntType)
{
return new ConstantIntExpression(leftHandSide.ToInt32() - rightHandSide.ToInt32());
}
// at least one of them is double
return new ConstantDoubleExpression(leftHandSide.ToDouble() - rightHandSide.ToDouble());
}
}
}
``` |
559e70a1-949b-482c-8505-35ef41f657cb | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
public class BenchmarkBindableInstantiation
{
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
```
Add basic bindable instantiation benchmark | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkBindableInstantiation
{
[Benchmark]
public Bindable<int> Instantiate() => new Bindable<int>();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
``` |
eb806250-9743-4bf9-a402-ea8cfe2fc034 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;
namespace Microsoft.DotNet.Tools.NuGet
{
public class NuGetCommand
{
public static int Run(string[] args)
{
return Run(args, new NuGetCommandRunner());
}
public static int Run(string[] args, ICommandRunner nugetCommandRunner)
{
DebugHelper.HandleDebugSwitch(ref args);
if (nugetCommandRunner == null)
{
throw new ArgumentNullException(nameof(nugetCommandRunner));
}
return nugetCommandRunner.Run(args);
}
private class NuGetCommandRunner : ICommandRunner
{
public int Run(string[] args)
{
var nugetApp = new NuGetForwardingApp(args);
return nugetApp.Execute();
}
}
}
}
```
Add DOTNET_HOST_PATH for dotnet nuget commands | ```c#
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;
namespace Microsoft.DotNet.Tools.NuGet
{
public class NuGetCommand
{
public static int Run(string[] args)
{
return Run(args, new NuGetCommandRunner());
}
public static int Run(string[] args, ICommandRunner nugetCommandRunner)
{
DebugHelper.HandleDebugSwitch(ref args);
if (nugetCommandRunner == null)
{
throw new ArgumentNullException(nameof(nugetCommandRunner));
}
return nugetCommandRunner.Run(args);
}
private class NuGetCommandRunner : ICommandRunner
{
public int Run(string[] args)
{
var nugetApp = new NuGetForwardingApp(args);
nugetApp.WithEnvironmentVariable("DOTNET_HOST_PATH", GetDotnetPath());
return nugetApp.Execute();
}
}
private static string GetDotnetPath()
{
return new Muxer().MuxerPath;
}
}
}
``` |
1a4f50e1-65a5-4523-bb44-7836ca8f68a1 | {
"language": "C#"
} | ```c#
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private bool togglePrivate = false;
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.Button("Create");
}
GUILayout.EndHorizontal();
}
}
}
```
Add a dropdown for selecting organizations | ```c#
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.Button("Create");
}
GUILayout.EndHorizontal();
}
}
}
``` |
98976a9e-1a15-4bf1-894e-bef0416bce48 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
[BackgroundDependencyLoader]
private void load()
{
Add(new GameplayScreen());
Add(chat);
}
[Test]
public void TestWarmup()
{
checkScoreVisibility(false);
toggleWarmup();
checkScoreVisibility(true);
toggleWarmup();
checkScoreVisibility(false);
}
private void checkScoreVisibility(bool visible)
=> AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
() => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));
private void toggleWarmup()
=> AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
}
}
```
Add failing test coverage for tournament startup states | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
[Test]
public void TestStartupState([Values] TourneyState state)
{
AddStep("set state", () => IPCInfo.State.Value = state);
createScreen();
}
[Test]
public void TestWarmup()
{
createScreen();
checkScoreVisibility(false);
toggleWarmup();
checkScoreVisibility(true);
toggleWarmup();
checkScoreVisibility(false);
}
private void createScreen()
{
AddStep("setup screen", () =>
{
Remove(chat);
Children = new Drawable[]
{
new GameplayScreen(),
chat,
};
});
}
private void checkScoreVisibility(bool visible)
=> AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
() => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));
private void toggleWarmup()
=> AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
}
}
``` |
c3e1a66e-de34-4537-9e64-632584641392 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;
namespace Calamari.Integration.Substitutions
{
public class FileSubstituter : IFileSubstituter
{
readonly ICalamariFileSystem fileSystem;
public FileSubstituter(ICalamariFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables)
{
PerformSubstitution(sourceFile, variables, sourceFile);
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
{
var source = fileSystem.ReadFile(sourceFile);
var encoding = GetEncoding(sourceFile, variables);
var result = variables.Evaluate(source);
fileSystem.OverwriteFile(targetFile, result, encoding);
}
private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
{
var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
if (requestedEncoding == null)
{
return fileSystem.GetFileEncoding(sourceFile);
}
try
{
return Encoding.GetEncoding(requestedEncoding);
}
catch (ArgumentException)
{
return Encoding.GetEncoding(sourceFile);
}
}
}
}
```
Use existing file encoding if provided override is invalid | ```c#
using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;
namespace Calamari.Integration.Substitutions
{
public class FileSubstituter : IFileSubstituter
{
readonly ICalamariFileSystem fileSystem;
public FileSubstituter(ICalamariFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables)
{
PerformSubstitution(sourceFile, variables, sourceFile);
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
{
var source = fileSystem.ReadFile(sourceFile);
var encoding = GetEncoding(sourceFile, variables);
var result = variables.Evaluate(source);
fileSystem.OverwriteFile(targetFile, result, encoding);
}
private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
{
var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
if (requestedEncoding == null)
{
return fileSystem.GetFileEncoding(sourceFile);
}
try
{
return Encoding.GetEncoding(requestedEncoding);
}
catch (ArgumentException)
{
return fileSystem.GetFileEncoding(sourceFile);
}
}
}
}
``` |
162bdd90-e751-403d-889d-69368c53808c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static BoundExpression And(IEnumerable<BoundExpression> conditions)
{
return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return binary;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
}```
Fix bug when splitting conjunctions | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static BoundExpression And(IEnumerable<BoundExpression> conditions)
{
return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return current;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
}``` |
67c07207-7834-414b-826d-24772af11dc0 | {
"language": "C#"
} | ```c#
using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;
namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
/// <summary>
/// Helper class that executes a task with a progress bar
/// </summary>
public class ProgressHelper
{
private readonly IMvxMainThreadDispatcher _dispatcher;
public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
/// <summary>
/// Setup the execution of the task with a progress indicator
/// </summary>
/// <typeparam name="T">Type of task return value</typeparam>
/// <param name="task">Task that is executing</param>
/// <param name="onCompletion">Action that will be executed when the task is complete</param>
/// <param name="startProgressAction">Action that will show the progress indicator</param>
/// <param name="stopProgressAction">Action that will hide the progress indicator</param>
public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
{
_dispatcher.RequestMainThreadAction(startProgressAction);
task.ContinueWith(x =>
{
onCompletion(task);
_dispatcher.RequestMainThreadAction(stopProgressAction);
});
}
}
}
```
Modify progress helper so that activity indicator stops after last call ends | ```c#
using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;
namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
/// <summary>
/// Helper class that executes a task with a progress bar
/// </summary>
public class ProgressHelper
{
private readonly IMvxMainThreadDispatcher _dispatcher;
private int _progressIndicatorCount;
public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
/// <summary>
/// Setup the execution of the task with a progress indicator
/// </summary>
/// <typeparam name="T">Type of task return value</typeparam>
/// <param name="task">Task that is executing</param>
/// <param name="onCompletion">Action that will be executed when the task is complete</param>
/// <param name="startProgressAction">Action that will show the progress indicator</param>
/// <param name="stopProgressAction">Action that will hide the progress indicator</param>
public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
{
_progressIndicatorCount++;
_dispatcher.RequestMainThreadAction(startProgressAction);
task.ContinueWith(x =>
{
onCompletion(task);
if (--_progressIndicatorCount == 0)
{
_dispatcher.RequestMainThreadAction(stopProgressAction);
}
});
}
}
}
``` |
e8a7f601-2a4b-49ac-8cd8-b9d4c521591a | {
"language": "C#"
} | ```c#
#region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for Options.xaml
/// </summary>
public partial class Options : Window
{
public Options()
{
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Save();
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Reload();
DialogResult = true;
}
}
}```
Fix settings not saving when opening "Options" | ```c#
#region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for Options.xaml
/// </summary>
public partial class Options : Window
{
public Options()
{
InitializeComponent();
Settings.Default.Save();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Save();
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Reload();
DialogResult = true;
}
}
}``` |
a67b92a8-2752-46dc-87dd-22f096e780cb | {
"language": "C#"
} | ```c#
using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Tests.GeneratorAPI {
[TestFixture]
internal class GeneratorTests {
[SetUp]
public void Initiate() {
_generator = new Generator<Randomizer>(new Randomizer(Seed));
}
[TearDown]
public void Dispose() {
_generator = null;
}
private Generator<Randomizer> _generator;
private const int Seed = 100;
[Test(
Author = "Robert",
Description = "Checks that the result from Generate is not null"
)]
public void Test() {
var result = _generator.Generate(randomizer => randomizer.GetString());
Assert.IsNotNull(result);
}
[Test(
Author = "Robert",
Description = "Checks that provider is assigned in the constructor."
)]
public void Test_Provider_Is_not_Null() {
Assert.IsNotNull(_generator);
}
}
}```
Add tests for null checking | ```c#
using System;
using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Tests.GeneratorAPI {
[TestFixture]
internal class GeneratorTests {
[SetUp]
public void Initiate() {
_generator = new Generator<Randomizer>(new Randomizer(Seed));
}
[TearDown]
public void Dispose() {
_generator = null;
}
private Generator<Randomizer> _generator;
private const int Seed = 100;
[Test(
Author = "Robert",
Description = "Check that constructor throws exception if argument is null"
)]
public void Constructor_Null_Argument() {
Assert.Throws<ArgumentNullException>(() => new Generator<Randomizer>(null));
}
[Test(
Author = "Robert",
Description = "Checks that the result from Generate is not null"
)]
public void Generate_Does_Not_Return_With_Valid_Arg() {
var result = _generator.Generate(randomizer => randomizer.GetString());
Assert.IsNotNull(result);
}
[Test(
Author = "Robert",
Description = "Checks that an exception is thrown when generate argument is null"
)]
public void Generate_With_Null() {
Assert.Throws<ArgumentNullException>(() => _generator.Generate<string>(randomizer => null));
}
[Test(
Author = "Robert",
Description = "Checks that provider is assigned in the constructor."
)]
public void Provider_Is_not_Null() {
var result = _generator.Provider;
Assert.IsNotNull(result);
}
}
}``` |
6c2ad6a4-606f-4b45-b14c-31cf40e534a9 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse.Server.Configuration
{
public class DefaultMetadataProvider : IMetadataProvider
{
private readonly IResourceManager _resourceManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly GlimpseServerOptions _serverOptions;
private Metadata _metadata;
public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
{
_resourceManager = resourceManager;
_httpContextAccessor = httpContextAccessor;
_serverOptions = serverOptions.Value;
}
public Metadata BuildInstance()
{
if (_metadata != null)
return _metadata;
var request = _httpContextAccessor.HttpContext.Request;
var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
IDictionary<string, string> resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");
if (_serverOptions.OverrideResources != null)
_serverOptions.OverrideResources(resources);
return new Metadata(resources);
}
}
}```
Make sure metadata is set before being returned | ```c#
using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse.Server.Configuration
{
public class DefaultMetadataProvider : IMetadataProvider
{
private readonly IResourceManager _resourceManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly GlimpseServerOptions _serverOptions;
private Metadata _metadata;
public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
{
_resourceManager = resourceManager;
_httpContextAccessor = httpContextAccessor;
_serverOptions = serverOptions.Value;
}
public Metadata BuildInstance()
{
if (_metadata != null)
return _metadata;
var request = _httpContextAccessor.HttpContext.Request;
var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
var resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");
if (_serverOptions.OverrideResources != null)
_serverOptions.OverrideResources(resources);
_metadata = new Metadata(resources);
return _metadata;
}
}
}``` |
14f649e4-6eb8-4e25-9dc4-fea05a1d3023 | {
"language": "C#"
} | ```c#
using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;
namespace SolrNet.Cloud.Tests
{
public class UnityTests
{
private IUnityContainer Setup() {
return new SolrNetContainerConfiguration().ConfigureContainer(
new FakeProvider(),
new UnityContainer());
}
[Fact]
public void ShouldResolveBasicOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveOperationsFromStartupContainer() {
Assert.NotNull(
Setup().Resolve<ISolrOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
}
}
}```
Add test trying to recreate the issue | ```c#
using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;
namespace SolrNet.Cloud.Tests
{
public class UnityTests
{
private IUnityContainer Setup() {
return new SolrNetContainerConfiguration().ConfigureContainer(
new FakeProvider(),
new UnityContainer());
}
[Fact]
public void ShouldResolveBasicOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveOperationsFromStartupContainer() {
Assert.NotNull(
Setup().Resolve<ISolrOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveIOperations ()
{
using (var container = new UnityContainer())
{
var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container);
var obj = cont.Resolve<ISolrOperations<Camera>>();
}
}
public class Camera
{
[Attributes.SolrField("Name")]
public string Name { get; set; }
[Attributes.SolrField("UID")]
public int UID { get; set; }
[Attributes.SolrField("id")]
public string Id { get; set; }
}
}
}
``` |
4ddbd714-1dba-481c-807d-b96c54e93312 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;
namespace VersionOne.ServerConnector {
// TODO extract interface and inject into VersionOneProcessor
internal class EntityFactory {
private readonly IMetaModel metaModel;
private readonly IServices services;
private readonly IEnumerable<AttributeInfo> attributesToQuery;
internal EntityFactory(IMetaModel metaModel, IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
this.metaModel = metaModel;
this.services = services;
this.attributesToQuery = attributesToQuery;
}
internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
var assetType = metaModel.GetAssetType(assetTypeName);
var asset = services.New(assetType, Oid.Null);
foreach (var attributeValue in attributeValues) {
if(attributeValue is SingleAttributeValue) {
asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
} else if(attributeValue is MultipleAttributeValue) {
var values = ((MultipleAttributeValue) attributeValue).Values;
var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);
foreach (var value in values) {
asset.AddAttributeValue(attributeDefinition, value);
}
} else {
throw new NotSupportedException("Unknown Attribute Value type.");
}
}
foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
}
services.Save(asset);
return asset;
}
}
}```
Use the new 15.0 SDK to access meta via IServices | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;
namespace VersionOne.ServerConnector {
// TODO extract interface and inject into VersionOneProcessor
internal class EntityFactory {
private readonly IServices services;
private readonly IEnumerable<AttributeInfo> attributesToQuery;
internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
this.services = services;
this.attributesToQuery = attributesToQuery;
}
internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
var assetType = services.Meta.GetAssetType(assetTypeName);
var asset = services.New(assetType, Oid.Null);
foreach (var attributeValue in attributeValues) {
if(attributeValue is SingleAttributeValue) {
asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
} else if(attributeValue is MultipleAttributeValue) {
var values = ((MultipleAttributeValue) attributeValue).Values;
var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);
foreach (var value in values) {
asset.AddAttributeValue(attributeDefinition, value);
}
} else {
throw new NotSupportedException("Unknown Attribute Value type.");
}
}
foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
}
services.Save(asset);
return asset;
}
}
}``` |
02808cf0-a3b4-4f39-b4fb-69ad9ec2b62f | {
"language": "C#"
} | ```c#
// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Reflection;
using System.Resources;
[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]
// Version is generated on the build server.
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
```
Resolve line too long message on build server | ```c#
// <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Reflection;
using System.Resources;
[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]
// Version is generated on the build server.
#pragma warning disable MEN002 // Line is too long
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
#pragma warning restore MEN002 // Line is too long
``` |
1990ec0b-0f70-4c56-9aa5-1ac98386a7c0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Battlezeppelins.Models
{
public class ZeppelinType
{
public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);
public static IEnumerable<ZeppelinType> Values
{
get
{
yield return MOTHER;
yield return LEET;
yield return NIBBLET;
}
}
public static ZeppelinType getByName(string name) {
foreach (ZeppelinType type in Values)
{
if (type.name == name) return type;
}
return null;
}
[JsonProperty]
public string name { get; private set; }
[JsonProperty]
public int length { get; private set; }
private ZeppelinType() { }
ZeppelinType(string name, int length)
{
this.name = name;
this.length = length;
}
public override string ToString()
{
return name;
}
}
}```
Fix 'no multiple zeppelins of the same type' constraint server side. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Battlezeppelins.Models
{
public class ZeppelinType
{
public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);
public static IEnumerable<ZeppelinType> Values
{
get
{
yield return MOTHER;
yield return LEET;
yield return NIBBLET;
}
}
public static ZeppelinType getByName(string name) {
foreach (ZeppelinType type in Values)
{
if (type.name == name) return type;
}
return null;
}
[JsonProperty]
public string name { get; private set; }
[JsonProperty]
public int length { get; private set; }
private ZeppelinType() { }
ZeppelinType(string name, int length)
{
this.name = name;
this.length = length;
}
public override string ToString()
{
return name;
}
public override bool Equals(object zeppelin) {
return this == (ZeppelinType)zeppelin;
}
public static bool operator==(ZeppelinType z1, ZeppelinType z2)
{
return z1.name == z2.name;
}
public static bool operator !=(ZeppelinType z1, ZeppelinType z2)
{
return z1.name != z2.name;
}
}
}``` |
58127b71-33f2-435d-bfae-6e1f6f79c478 | {
"language": "C#"
} | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;
namespace CefSharp.BrowserSubprocess
{
public class Program
{
public static int Main(string[] args)
{
Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));
int result;
//MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
var commandLineArgs = new List<string>(args)
{
"--renderer-startup-dialog"
};
using (var subprocess = Create(commandLineArgs.ToArray()))
{
//if (subprocess is CefRenderProcess)
//{
// MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
result = subprocess.Run();
}
Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
return result;
}
public static CefSubProcess Create(IEnumerable<string> args)
{
const string typePrefix = "--type=";
var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));
var type = typeArgument.Substring(typePrefix.Length);
switch (type)
{
case "renderer":
return new CefRenderProcess(args);
case "gpu-process":
return new CefGpuProcess(args);
default:
return new CefSubProcess(args);
}
}
}
}
```
Revert to previous debugging method as change wasn't working correctly. | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;
namespace CefSharp.BrowserSubprocess
{
public class Program
{
public static int Main(string[] args)
{
Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));
int result;
using (var subprocess = Create(args))
{
//if (subprocess is CefRenderProcess)
//{
// MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
result = subprocess.Run();
}
Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
return result;
}
public static CefSubProcess Create(IEnumerable<string> args)
{
const string typePrefix = "--type=";
var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));
var type = typeArgument.Substring(typePrefix.Length);
switch (type)
{
case "renderer":
return new CefRenderProcess(args);
case "gpu-process":
return new CefGpuProcess(args);
default:
return new CefSubProcess(args);
}
}
}
}
``` |
3d91e3fd-3eb2-4d8b-a7df-b237ce879143 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.Common
{
public class ConsoleArguments
{
private List<string> _args;
public ConsoleArguments(IEnumerable<string> args)
{
_args = new List<string>(args);
}
public bool ContainsSwitch(string name)
{
return _args.Contains(name);
}
public string GetSwitchValue(string name)
{
if (!ContainsSwitch(name)) return null;
var switchIndex = _args.IndexOf(name);
if (_args.Count < switchIndex + 1) return null;
return _args[switchIndex + 1];
}
}
}
```
Fix a bug with the console arguments class | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.Common
{
public class ConsoleArguments
{
private List<string> _args;
public ConsoleArguments(IEnumerable<string> args)
{
_args = new List<string>(args);
}
public bool ContainsSwitch(string name)
{
return _args.Contains(name);
}
public string GetSwitchValue(string name)
{
if (!ContainsSwitch(name)) return null;
var switchIndex = _args.IndexOf(name);
if ((_args.Count - 1) < switchIndex + 1) return null;
return _args[switchIndex + 1];
}
}
}
``` |
6e4110ab-07e9-441e-aef0-4c5202b6e75b | {
"language": "C#"
} | ```c#
using System;
using System.IO;
namespace MultiMiner.Utility
{
public static class ApplicationPaths
{
public static string AppDataPath()
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
}
}
```
Support for running the app in a "portable" mode | ```c#
using System;
using System.IO;
namespace MultiMiner.Utility
{
public static class ApplicationPaths
{
public static string AppDataPath()
{
//if running in "portable" mode
if (IsRunningInPortableMode())
{
//store files in the working directory rather than AppData
return GetWorkingDirectory();
}
else
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
}
//simply check for a file named "portable" in the same folder
private static bool IsRunningInPortableMode()
{
string assemblyDirectory = GetWorkingDirectory();
string portableFile = Path.Combine(assemblyDirectory, "portable");
return File.Exists(portableFile);
}
private static string GetWorkingDirectory()
{
string assemblyFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
return Path.GetDirectoryName(assemblyFilePath);
}
}
}
``` |
92c8c164-dfe8-42bb-8263-005a6d99d7a0 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;
namespace Wox.Plugin.Program
{
public class Settings
{
public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};
public bool EnableStartMenuSource { get; set; } = true;
public bool EnableRegistrySource { get; set; } = true;
internal const char SuffixSeperator = ';';
/// <summary>
/// Contains user added folder location contents as well as all user disabled applications
/// </summary>
/// <remarks>
/// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
/// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
/// </remarks>
public class ProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
public class DisabledProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
}
}
```
Change DisabledProgramSource class to inherit ProgramSource | ```c#
using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;
namespace Wox.Plugin.Program
{
public class Settings
{
public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};
public bool EnableStartMenuSource { get; set; } = true;
public bool EnableRegistrySource { get; set; } = true;
internal const char SuffixSeperator = ';';
/// <summary>
/// Contains user added folder location contents as well as all user disabled applications
/// </summary>
/// <remarks>
/// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
/// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
/// </remarks>
public class ProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
public class DisabledProgramSource : ProgramSource { }
}
}
``` |
16769d5c-90e1-42b1-a1f4-8e81f7094610 | {
"language": "C#"
} | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
internal struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
```
Allow negative GAF frame offsets | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
internal struct GafFrameData
{
public ushort Width;
public ushort Height;
public short XPos;
public short YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadInt16();
e.YPos = b.ReadInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
``` |
73d02bb4-28f3-4fb9-bc69-18f77e8fa010 | {
"language": "C#"
} | ```c#
namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
}```
Fix bitmap serialization with indexed format bitmaps | ```c#
namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
}``` |
fb88885c-b517-4fb9-a04b-b5f466281fc4 | {
"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.Graphics;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneBeatmapOffsetControl : OsuTestScene
{
[Test]
public void TestDisplay()
{
Child = new PlayerSettingsGroup("Some settings")
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new BeatmapOffsetControl(TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(-4.5))
}
};
}
}
}
```
Add full testing flow for `BeatmapOffsetControl` | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Overlays.Settings;
using osu.Game.Scoring;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Visual.Ranking;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneBeatmapOffsetControl : OsuTestScene
{
private BeatmapOffsetControl offsetControl;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Create control", () =>
{
Child = new PlayerSettingsGroup("Some settings")
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
offsetControl = new BeatmapOffsetControl()
}
};
});
}
[Test]
public void TestDisplay()
{
const double average_error = -4.5;
AddAssert("Offset is neutral", () => offsetControl.Current.Value == 0);
AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
AddStep("Set reference score", () =>
{
offsetControl.ReferenceScore.Value = new ScoreInfo
{
HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents(average_error)
};
});
AddAssert("Has calibration button", () => offsetControl.ChildrenOfType<SettingsButton>().Any());
AddStep("Press button", () => offsetControl.ChildrenOfType<SettingsButton>().Single().TriggerClick());
AddAssert("Offset is adjusted", () => offsetControl.Current.Value == average_error);
AddStep("Remove reference score", () => offsetControl.ReferenceScore.Value = null);
AddAssert("No calibration button", () => !offsetControl.ChildrenOfType<SettingsButton>().Any());
}
}
}
``` |
ca109caa-dd12-4275-a489-1feafd41ff8d | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
var searchText = SearchText;
SearchText = string.Empty;
Process.Start($"{Settings.BaseUrl}{searchText}");
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
}```
Add "Search" widget no base url warning | ```c#
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
if (string.IsNullOrWhiteSpace(Settings.BaseUrl))
{
Popup.Show("You must setup a base url first.", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
var searchText = SearchText;
SearchText = string.Empty;
Process.Start($"{Settings.BaseUrl}{searchText}");
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
}``` |
524dd8c6-c1d8-4ebd-a0de-4312d2fdcab8 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;
namespace Sendgrid.Webhooks.Service
{
public class WebhookCategoryConverter : GenericListCreationJsonConverter<String>
{
}
}```
Use string instead of String | ```c#
using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Sendgrid.Webhooks.Converters;
namespace Sendgrid.Webhooks.Service
{
public class WebhookCategoryConverter : GenericListCreationJsonConverter<string>
{
}
}
``` |
d2863407-f495-4377-8983-be054d41fabc | {
"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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
}
}
}
}
```
Add back incorrectly removed parameter | ```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.Platform;
using osu.Framework.Platform.Linux;
using osu.Framework.Platform.MacOS;
using osu.Framework.Platform.Windows;
using System;
namespace osu.Framework
{
public static class Host
{
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false)
{
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.macOS:
return new MacOSGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Linux:
return new LinuxGameHost(gameName, bindIPC, portableInstallation);
case RuntimeInfo.Platform.Windows:
return new WindowsGameHost(gameName, bindIPC, portableInstallation);
default:
throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)}).");
}
}
}
}
``` |
95d35c5e-1dd7-423f-8205-b94994bc6912 | {
"language": "C#"
} | ```c#
using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;
namespace CertiPay.Services.PDF
{
public class Bootstrapper : DefaultNancyBootstrapper
{
private static String ABCPdfLicense
{
get { return ConfigurationManager.AppSettings["ABCPDF-License"]; }
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<IPDFService>(new PDFService(ABCPdfLicense));
}
}
}```
Check the environment variable for the license key | ```c#
using CertiPay.PDF;
using Nancy;
using Nancy.TinyIoc;
using System;
using System.Configuration;
namespace CertiPay.Services.PDF
{
public class Bootstrapper : DefaultNancyBootstrapper
{
private static String ABCPdfLicense
{
get
{
// Check the environment variables for the license key
String key = "ABCPDF-License";
if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User)))
{
return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
}
return ConfigurationManager.AppSettings[key];
}
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<IPDFService>(new PDFService(ABCPdfLicense));
}
}
}``` |
7348bdc3-064b-4833-9509-44d85042cede | {
"language": "C#"
} | ```c#
// This file was auto-generated based on version 1.0.0 of the canonical data.
using Xunit;
public class PrimeFactorsTest
{
[Fact]
public void No_factors()
{
Assert.Empty(PrimeFactors.Factors(1));
}
[Fact]
public void Prime_number()
{
Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
}
[Fact]
public void Square_of_a_prime()
{
Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
}
[Fact]
public void Cube_of_a_prime()
{
Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
}
[Fact]
public void Product_of_primes_and_non_primes()
{
Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
}
[Fact]
public void Product_of_primes()
{
Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
}
[Fact]
public void Factors_include_a_large_prime()
{
Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
}
}```
Add skips to prime factors test suite | ```c#
// This file was auto-generated based on version 1.0.0 of the canonical data.
using Xunit;
public class PrimeFactorsTest
{
[Fact]
public void No_factors()
{
Assert.Empty(PrimeFactors.Factors(1));
}
[Fact(Skip = "Remove to run test")]
public void Prime_number()
{
Assert.Equal(new[] { 2 }, PrimeFactors.Factors(2));
}
[Fact(Skip = "Remove to run test")]
public void Square_of_a_prime()
{
Assert.Equal(new[] { 3, 3 }, PrimeFactors.Factors(9));
}
[Fact(Skip = "Remove to run test")]
public void Cube_of_a_prime()
{
Assert.Equal(new[] { 2, 2, 2 }, PrimeFactors.Factors(8));
}
[Fact(Skip = "Remove to run test")]
public void Product_of_primes_and_non_primes()
{
Assert.Equal(new[] { 2, 2, 3 }, PrimeFactors.Factors(12));
}
[Fact(Skip = "Remove to run test")]
public void Product_of_primes()
{
Assert.Equal(new[] { 5, 17, 23, 461 }, PrimeFactors.Factors(901255));
}
[Fact(Skip = "Remove to run test")]
public void Factors_include_a_large_prime()
{
Assert.Equal(new[] { 11, 9539, 894119 }, PrimeFactors.Factors(93819012551));
}
}``` |
dc944b7b-ffca-4e85-94fb-2b2fc4f9b305 | {
"language": "C#"
} | ```c#
using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
[FileStringContentData("Files/FotosHochladen.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.CustomData);
Assert.NotNull(result.CustomData.Info);
Assert.NotNull(result.CustomData.Uploader);
Assert.NotNull(result.CustomData.SchemaVersion);
}
}
}
```
Add Test for SemVer Parsing | ```c#
using HolzShots.Net.Custom;
using Xunit;
namespace HolzShots.Core.Tests.Net.Custom
{
public class CustomUploaderLoaderTests
{
[Theory]
[FileStringContentData("Files/DirectUpload.net.hsjson")]
[FileStringContentData("Files/FotosHochladen.hsjson")]
public void ValidateTest(string content)
{
var parseResult = CustomUploader.TryParse(content, out var result);
Assert.True(parseResult);
Assert.NotNull(result);
Assert.NotNull(result.CustomData);
Assert.NotNull(result.CustomData.Info);
Assert.NotNull(result.CustomData.Uploader);
Assert.NotNull(result.CustomData.SchemaVersion);
Assert.True(result.CustomData.Info.Version == new Semver.SemVersion(1, 0, 0));
}
}
}
``` |
09b760e8-f1ae-42bc-8259-c3827c4ce54c | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using osu.Framework.Utils;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneShaking : TestSceneHitCircle
{
protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
{
var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);
Debug.Assert(drawableHitObject.HitObject.HitWindows != null);
double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay);
return drawableHitObject;
}
}
}
```
Fix scheduled tasks not being cleaned up between test steps | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Diagnostics;
using osu.Framework.Threading;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneShaking : TestSceneHitCircle
{
private readonly List<ScheduledDelegate> scheduledTasks = new List<ScheduledDelegate>();
protected override IBeatmap CreateBeatmapForSkinProvider()
{
// best way to run cleanup before a new step is run
foreach (var task in scheduledTasks)
task.Cancel();
scheduledTasks.Clear();
return base.CreateBeatmapForSkinProvider();
}
protected override TestDrawableHitCircle CreateDrawableHitCircle(HitCircle circle, bool auto)
{
var drawableHitObject = base.CreateDrawableHitCircle(circle, auto);
Debug.Assert(drawableHitObject.HitObject.HitWindows != null);
double delay = drawableHitObject.HitObject.StartTime - (drawableHitObject.HitObject.HitWindows.WindowFor(HitResult.Miss) + RNG.Next(0, 300)) - Time.Current;
scheduledTasks.Add(Scheduler.AddDelayed(() => drawableHitObject.TriggerJudgement(), delay));
return drawableHitObject;
}
}
}
``` |
6f936b04-18be-435c-b1f1-e4c4b7752ca2 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace NDeproxy
{
public static class SocketHelper
{
static readonly Logger log = new Logger("SocketHelper");
public static Socket Server(int port, int listenQueue=5)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(listenQueue);
return s;
}
public static Socket Client(string remoteHost, int port)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteHost, port);
return s;
}
public static int GetLocalPort(this Socket socket)
{
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
public static int GetRemotePort(this Socket socket)
{
return ((IPEndPoint)socket.RemoteEndPoint).Port;
}
}
}
```
Add an optional timeout for connection attempts. | ```c#
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace NDeproxy
{
public static class SocketHelper
{
static readonly Logger log = new Logger("SocketHelper");
public static Socket Server(int port, int listenQueue=5)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(listenQueue);
return s;
}
public static Socket Client(string remoteHost, int port, int timeout=Timeout.Infinite)
{
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (timeout == Timeout.Infinite)
{
s.Connect(remoteHost, port);
return s;
}
else
{
var result = s.BeginConnect(remoteHost, port, (_result) => { s.EndConnect(_result); }, s);
if (result.AsyncWaitHandle.WaitOne(timeout))
{
return s;
}
else
{
throw new SocketException((int)SocketError.TimedOut);
}
}
}
public static int GetLocalPort(this Socket socket)
{
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
public static int GetRemotePort(this Socket socket)
{
return ((IPEndPoint)socket.RemoteEndPoint).Port;
}
}
}
``` |
6aa99be1-5b15-40cc-89a5-cf5454c4c95b | {
"language": "C#"
} | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Collections.Generic;
namespace Lunet.Core
{
/// <summary>
/// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
/// </summary>
/// <seealso cref="ManagerBase" />
public class MetaManager : ManagerBase
{
public const string MetaDirectoryName = "_meta";
/// <summary>
/// Initializes a new instance of the <see cref="MetaManager"/> class.
/// </summary>
/// <param name="site">The site.</param>
public MetaManager(SiteObject site) : base(site)
{
Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
}
public FolderInfo Directory { get; }
public FolderInfo PrivateDirectory { get; }
public IEnumerable<FolderInfo> Directories
{
get
{
yield return Directory;
foreach (var theme in Site.Extends.CurrentList)
{
yield return theme.Directory.GetSubFolder(MetaDirectoryName);
}
}
}
}
}```
Add support for builtins directory from the assembly folder/_meta | ```c#
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Lunet.Core
{
/// <summary>
/// Manages the meta information associated to a site (from the `_meta` directory and `.lunet` directory)
/// </summary>
/// <seealso cref="ManagerBase" />
public class MetaManager : ManagerBase
{
public const string MetaDirectoryName = "_meta";
/// <summary>
/// Initializes a new instance of the <see cref="MetaManager"/> class.
/// </summary>
/// <param name="site">The site.</param>
public MetaManager(SiteObject site) : base(site)
{
Directory = Site.BaseDirectory.GetSubFolder(MetaDirectoryName);
PrivateDirectory = Site.PrivateBaseDirectory.GetSubFolder(MetaDirectoryName);
BuiltinDirectory = Path.GetDirectoryName(typeof(MetaManager).GetTypeInfo().Assembly.Location);
}
public FolderInfo Directory { get; }
public FolderInfo BuiltinDirectory { get; }
public FolderInfo PrivateDirectory { get; }
public IEnumerable<FolderInfo> Directories
{
get
{
yield return Directory;
foreach (var theme in Site.Extends.CurrentList)
{
yield return theme.Directory.GetSubFolder(MetaDirectoryName);
}
// Last one is the builtin directory
yield return new DirectoryInfo(Path.Combine(BuiltinDirectory, MetaDirectoryName));
}
}
}
}``` |
f4b6f691-c948-4bc4-b423-344e26386674 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Owin;
namespace Connect.Owin.Examples.Hello
{
// OWIN application delegate
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(new Func<AppFunc, AppFunc>(next => async env =>
{
env["owin.ResponseStatusCode"] = 200;
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Type", new string[] { "text/html" });
StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
await w.FlushAsync();
}));
}
}
}
```
Set `Content-Length` in the `hello` sample | ```c#
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Owin;
namespace Connect.Owin.Examples.Hello
{
// OWIN application delegate
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(new Func<AppFunc, AppFunc>(next => async env =>
{
env["owin.ResponseStatusCode"] = 200;
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Length", new string[] { "53" });
((IDictionary<string, string[]>)env["owin.ResponseHeaders"]).Add(
"Content-Type", new string[] { "text/html" });
StreamWriter w = new StreamWriter((Stream)env["owin.ResponseBody"]);
w.Write("Hello, from C#. Time on server is " + DateTime.Now.ToString());
await w.FlushAsync();
}));
}
}
}
``` |
47ddd437-e217-48ee-8ab5-56d1dc0a925c | {
"language": "C#"
} | ```c#
using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) : base(factory)
{
Transaction = session.BeginTransaction(isolationLevel);
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
```
Add boolean to figure out is the uow is made with the session | ```c#
using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session,
IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
{
if (sessionOnlyForThisUnitOfWork)
{
Session = session;
}
Transaction = session.BeginTransaction(isolationLevel);
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
``` |
045dfa80-971c-4c43-9a55-dbe9b0074ef6 | {
"language": "C#"
} | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.ServiceModel;
namespace CefSharp.Internals
{
[ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
public interface IBrowserProcess
{
[OperationContract]
BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);
[OperationContract]
BrowserProcessResponse GetProperty(long objectId, string name);
[OperationContract]
BrowserProcessResponse SetProperty(long objectId, string name, object value);
[OperationContract]
JavascriptRootObject GetRegisteredJavascriptObjects();
[OperationContract]
void Connect();
}
}```
Add service ServiceKnownTypes for object[] and Dictionary<string, object> so that basic arrays can be passed two and from functions | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Generic;
using System.ServiceModel;
namespace CefSharp.Internals
{
[ServiceContract(CallbackContract = typeof(IRenderProcess), SessionMode = SessionMode.Required)]
[ServiceKnownType(typeof(object[]))]
[ServiceKnownType(typeof(Dictionary<string, object>))]
public interface IBrowserProcess
{
[OperationContract]
BrowserProcessResponse CallMethod(long objectId, string name, object[] parameters);
[OperationContract]
BrowserProcessResponse GetProperty(long objectId, string name);
[OperationContract]
BrowserProcessResponse SetProperty(long objectId, string name, object value);
[OperationContract]
JavascriptRootObject GetRegisteredJavascriptObjects();
[OperationContract]
void Connect();
}
}``` |
fa5fb606-5021-4b4a-9f8b-e7a26e92977c | {
"language": "C#"
} | ```c#
using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * m_Percentage / 100);
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
}```
Tidy up sum a bit by moving where we cast and negate to the line below. | ```c#
using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = Math.Ceiling(item.Price * m_Percentage / 100);
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), (int) -discountToApply);
}
}
return discountedBasket;
}
}
}``` |
76227fef-4936-4dbe-bba0-96184c395de3 | {
"language": "C#"
} | ```c#
using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;
namespace WampSharp.V2
{
public class DefaultWampChannelFactory : WampChannelFactory
{
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampTextBinding<TMessage> binding)
{
var connection =
new WebSocket4NetTextConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampBinaryBinding<TMessage> binding)
{
var connection =
new WebSocket4NetBinaryConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateJsonChannel(string address,
string realm)
{
JTokenBinding binding = new JTokenBinding();
return this.CreateChannel(address, realm, binding);
}
public IWampChannel CreateMsgpackChannel(string address,
string realm)
{
MessagePackObjectBinding binding = new MessagePackObjectBinding();
return this.CreateChannel(address, realm, binding);
}
}
}```
Use the same reference for all method calls | ```c#
using WampSharp.Binding;
using WampSharp.V2.Binding;
using WampSharp.V2.Client;
using WampSharp.WebSocket4Net;
namespace WampSharp.V2
{
public class DefaultWampChannelFactory : WampChannelFactory
{
private readonly MessagePackObjectBinding mMsgpackBinding = new MessagePackObjectBinding();
private readonly JTokenBinding mJsonBinding = new JTokenBinding();
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampTextBinding<TMessage> binding)
{
var connection =
new WebSocket4NetTextConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateChannel<TMessage>(string address,
string realm,
IWampBinaryBinding<TMessage> binding)
{
var connection =
new WebSocket4NetBinaryConnection<TMessage>(address, binding);
return this.CreateChannel(realm, connection, binding);
}
public IWampChannel CreateJsonChannel(string address,
string realm)
{
return this.CreateChannel(address, realm, mJsonBinding);
}
public IWampChannel CreateMsgpackChannel(string address,
string realm)
{
return this.CreateChannel(address, realm, mMsgpackBinding);
}
}
}``` |
5eb1ac23-0b0b-43c2-b87b-bf1ace98b335 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;
namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
[TestFixture]
public class LimitedModeCharacterCounterTests
{
[Test]
public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
{
const int NumConcurrent = 10;
ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);
// To solve the exercise, you may need to pass additional synchronisation information to the constructor.
var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();
// When you've succeeded, try changing this to use AsParallel(). Does it still work? It didn't for me. Explain why!
Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
Task.WaitAll(tasks);
}
}
}
```
Add an Explicit test that tries to use AsParallel(). It will hang after the exercise is completed, if the solution is the same as mine. | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;
namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
[TestFixture]
public class LimitedModeCharacterCounterTests
{
[Test]
public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
{
LimitedModeCharacterCounter[] counters = CreateCounters();
Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
Task.WaitAll(tasks);
}
[Test, Explicit("This will probably hang, once you make it use your Barrier-based solution. Can you work out why?")]
public void GetCharCounts_UsingAsParallel()
{
LimitedModeCharacterCounter[] counters = CreateCounters();
var results = counters.AsParallel().Select(c => c.GetCharCounts()).ToArray();
Assert.That(results, Is.Not.Empty);
}
private static LimitedModeCharacterCounter[] CreateCounters()
{
const int NumConcurrent = 10;
ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);
// To solve the exercise, you may need to pass additional synchronisation information to the constructor.
var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();
return counters;
}
}
}
``` |
c13817a5-b1d3-4740-b8ab-c5539d924d69 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Timers;
using StatoBot.Core;
namespace StatoBot.Analytics
{
public class AnalyzerBot : TwitchBot
{
public ChatAnalyzer Analyzer;
public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
{
Analyzer = new ChatAnalyzer();
OnMessageReceived += AnalyzeMessage;
}
private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
{
Analyzer
.AnalyzeAsync(args)
.Start();
}
}
}
```
Use Task.Run instead of .Start() | ```c#
using System;
using System.IO;
using System.Timers;
using System.Threading.Tasks;
using StatoBot.Core;
namespace StatoBot.Analytics
{
public class AnalyzerBot : TwitchBot
{
public ChatAnalyzer Analyzer;
public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
{
Analyzer = new ChatAnalyzer();
OnMessageReceived += AnalyzeMessage;
}
private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
{
Task.Run(() =>
Analyzer
.AnalyzeAsync(args)
);
}
}
}
``` |
bb19ef39-bbb4-4bec-99ec-8e7234e7ef4c | {
"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.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
where THitObject : CatchHitObject, new()
{
protected new THitObject HitObject => (THitObject)base.HitObject;
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
public CatchPlacementBlueprint()
: base(new THitObject())
{
}
}
}
```
Fix hit object placement not receiving input when outside playfield | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
where THitObject : CatchHitObject, new()
{
protected new THitObject HitObject => (THitObject)base.HitObject;
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
public CatchPlacementBlueprint()
: base(new THitObject())
{
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
}
}
``` |
9c59fd10-5107-4342-90bb-bbc1f275eec8 | {
"language": "C#"
} | ```c#
using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;
namespace WTM.Api.Controllers
{
public class UserController : ApiController
{
private readonly IUserService userService;
public UserController()
{
var webClient = new WebClientWTM();
var htmlParser = new HtmlParser();
userService = new UserService(webClient, htmlParser);
}
public UserController(IUserService userService)
{
this.userService = userService;
}
// GET api/User/Login?username={username}&password={password}
[Route("api/User/Login")]
[HttpGet]
public User Login([FromUri]string username, [FromUri]string password)
{
return userService.Login(username, password);
}
}
}```
Add methods intto User Api | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;
namespace WTM.Api.Controllers
{
public class UserController : ApiController
{
private readonly IUserService userService;
public UserController()
{
var webClient = new WebClientWTM();
var htmlParser = new HtmlParser();
userService = new UserService(webClient, htmlParser);
}
public UserController(IUserService userService)
{
this.userService = userService;
}
// GET api/User/Login?username={username}&password={password}
[Route("api/User/Login")]
[HttpGet]
public User Login([FromUri]string username, [FromUri]string password)
{
return userService.Login(username, password);
}
[Route("api/User/{username}")]
[HttpGet]
public User Get(string username)
{
return userService.GetByUsername(username);
}
//[Route("api/User/Search")]
[HttpGet]
public List<UserSummary> Search(string search, [FromUri]int? page = null)
{
return userService.Search(search, page).ToList();
}
}
}``` |
a97e77a1-c4b8-4656-8f00-35e06f7e79a7 | {
"language": "C#"
} | ```c#
namespace Parsley;
public static class ReadOnlySpanExtensions
{
public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
=> length >= input.Length
? input.Slice(0)
: input.Slice(0, length);
public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
{
var traversed = input.Peek(length);
input = input.Slice(traversed.Length);
index += traversed.Length;
}
public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
{
int i = 0;
while (i < input.Length && test(input[i]))
i++;
return input.Peek(i);
}
}
```
Reduce the number of slice operations performed during an Advance, when those slices were used only for their length. | ```c#
namespace Parsley;
public static class ReadOnlySpanExtensions
{
public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
=> length >= input.Length
? input.Slice(0)
: input.Slice(0, length);
public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
{
var traversed = length >= input.Length
? input.Length
: length;
input = input.Slice(traversed);
index += traversed;
}
public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
{
int i = 0;
while (i < input.Length && test(input[i]))
i++;
return input.Peek(i);
}
}
``` |
7ec06cbd-7423-4664-9b98-149391093c58 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
return true;
}
}
}
return false;
}
}
}```
Introduce caching of ShouldIgnore request so that the ignorer pipeline is only executed once per request | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.JsonPatch.Helpers;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var result = GetCachedResult(context);
if (result == null)
{
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
result = true;
break;
}
}
}
if (!result.HasValue)
{
result = false;
}
SetCachedResult(context, result);
}
return result.Value;
}
private bool? GetCachedResult(HttpContext context)
{
return context.Items["Glimpse.ShouldIgnoreRequest"] as bool?;
}
private void SetCachedResult(HttpContext context, bool? value)
{
context.Items["Glimpse.ShouldIgnoreRequest"] = value;
}
}
}``` |
26fa7942-aa9f-4357-8c8f-81a3a4ca28e3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Splat;
namespace Akavache
{
internal interface IWantsToRegisterStuff
{
void Register(IMutableDependencyResolver resolverToUse);
}
public static class DependencyResolverMixin
{
/// <summary>
/// Initializes a ReactiveUI dependency resolver with classes that
/// Akavache uses internally.
/// </summary>
public static void InitializeAkavache(this IMutableDependencyResolver This)
{
var namespaces = new[] {
"Akavache",
"Akavache.Mac",
"Akavache.Mobile",
"Akavache.Sqlite3",
};
var fdr = typeof(DependencyResolverMixin);
var assmName = new AssemblyName(
fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));
foreach (var ns in namespaces)
{
var targetType = ns + ".Registrations";
string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);
var registerTypeClass = Type.GetType(fullName, false);
if (registerTypeClass == null) continue;
var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
registerer.Register(This);
};
}
}
}
```
Make sure we register stuff | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Splat;
namespace Akavache
{
internal interface IWantsToRegisterStuff
{
void Register(IMutableDependencyResolver resolverToUse);
}
public static class DependencyResolverMixin
{
/// <summary>
/// Initializes a ReactiveUI dependency resolver with classes that
/// Akavache uses internally.
/// </summary>
public static void InitializeAkavache(this IMutableDependencyResolver This)
{
var namespaces = new[] {
"Akavache",
"Akavache.Mac",
"Akavache.Deprecated",
"Akavache.Mobile",
"Akavache.Http",
"Akavache.Sqlite3",
};
var fdr = typeof(DependencyResolverMixin);
var assmName = new AssemblyName(
fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));
foreach (var ns in namespaces)
{
var targetType = ns + ".Registrations";
string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);
var registerTypeClass = Type.GetType(fullName, false);
if (registerTypeClass == null) continue;
var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
registerer.Register(This);
};
}
}
}
``` |
c79ad90a-338b-48d0-a08e-335944ae24c5 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Contract Security Types
/// </summary>
[Serializable()]
public enum SecurityType
{
/// <summary>
/// Stock
/// </summary>
[Description("STK")] Stock,
/// <summary>
/// Option
/// </summary>
[Description("OPT")] Option,
/// <summary>
/// Future
/// </summary>
[Description("FUT")] Future,
/// <summary>
/// Indice
/// </summary>
[Description("IND")] Index,
/// <summary>
/// FOP = options on futures
/// </summary>
[Description("FOP")] FutureOption,
/// <summary>
/// Cash
/// </summary>
[Description("CASH")] Cash,
/// <summary>
/// For Combination Orders - must use combo leg details
/// </summary>
[Description("BAG")] Bag,
/// <summary>
/// Bond
/// </summary>
[Description("BOND")] Bond,
/// <summary>
/// Undefined Security Type
/// </summary>
[Description("")] Undefined
}
}```
Add the warrant security type. | ```c#
using System;
using System.ComponentModel;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Contract Security Types
/// </summary>
[Serializable()]
public enum SecurityType
{
/// <summary>
/// Stock
/// </summary>
[Description("STK")] Stock,
/// <summary>
/// Option
/// </summary>
[Description("OPT")] Option,
/// <summary>
/// Future
/// </summary>
[Description("FUT")] Future,
/// <summary>
/// Indice
/// </summary>
[Description("IND")] Index,
/// <summary>
/// FOP = options on futures
/// </summary>
[Description("FOP")] FutureOption,
/// <summary>
/// Cash
/// </summary>
[Description("CASH")] Cash,
/// <summary>
/// For Combination Orders - must use combo leg details
/// </summary>
[Description("BAG")] Bag,
/// <summary>
/// Bond
/// </summary>
[Description("BOND")] Bond,
/// <summary>
/// Warrant
/// </summary>
[Description("WAR")] Warrant,
/// <summary>
/// Undefined Security Type
/// </summary>
[Description("")] Undefined
}
}``` |
4563c76e-6469-4b9f-a2e1-f5527ab14cc5 | {
"language": "C#"
} | ```c#
using Content.Shared.Maths;
namespace Content.Shared.Utility
{
public static class TemperatureHelpers
{
public static float CelsiusToKelvin(float celsius)
{
return celsius + PhysicalConstants.ZERO_CELCIUS;
}
public static float KelvinToCelsius(float kelvin)
{
return kelvin - PhysicalConstants.ZERO_CELCIUS;
}
}
}
```
Add helpers for converting to and from Fahrenheit | ```c#
using Content.Shared.Maths;
namespace Content.Shared.Utility
{
public static class TemperatureHelpers
{
public static float CelsiusToKelvin(float celsius)
{
return celsius + PhysicalConstants.ZERO_CELCIUS;
}
public static float CelsiusToFahrenheit(float celsius)
{
return celsius * 9 / 5 + 32;
}
public static float KelvinToCelsius(float kelvin)
{
return kelvin - PhysicalConstants.ZERO_CELCIUS;
}
public static float KelvinToFahrenheit(float kelvin)
{
var celsius = KelvinToCelsius(kelvin);
return CelsiusToFahrenheit(celsius);
}
public static float FahrenheitToCelsius(float fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
public static float FahrenheitToKelvin(float fahrenheit)
{
var celsius = FahrenheitToCelsius(fahrenheit);
return CelsiusToKelvin(celsius);
}
}
}
``` |
533c8610-9853-4333-bd85-b9bb336349e4 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
}
}
```
Write some more tests for secret splitting | ```c#
using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
``` |
d5ce23b4-0b9c-490f-b9d0-47db5db4df82 | {
"language": "C#"
} | ```c#
#region
using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;
#endregion
namespace RtfFile
{
internal class RtfFileExporter : ITablatureFileExporter
{
private Font _font;
private RichTextBox _rtb;
#region Implementation of ITablatureFileExporter
public FileType FileType { get; private set; }
public Version Version
{
get { return new Version("1.0"); }
}
public void Export(ITablatureFile file, string fileName)
{
if (_font == null)
_font = new Font("Courier New", 9F);
if (_rtb == null)
_rtb = new RichTextBox {Font = new Font("Courier New", 9F), Text = file.Contents};
_rtb.SaveFile(fileName);
_rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
}
#endregion
public RtfFileExporter()
{
FileType = new FileType("Rich Text Format File", ".rtf");
}
~RtfFileExporter()
{
if (_font != null)
_font.Dispose();
if (_rtb != null && !_rtb.IsDisposed)
_rtb.Dispose();
}
}
}```
Use specified font for RTF exporting | ```c#
#region
using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;
#endregion
namespace RtfFile
{
internal class RtfFileExporter : ITablatureFileExporter
{
private RichTextBox _rtb;
#region Implementation of ITablatureFileExporter
public FileType FileType { get; private set; }
public Version Version
{
get { return new Version("1.0"); }
}
public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args)
{
if (_rtb == null)
_rtb = new RichTextBox {Font = args.Font, Text = file.Contents};
_rtb.SaveFile(fileName);
_rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
}
#endregion
public RtfFileExporter()
{
FileType = new FileType("Rich Text Format File", ".rtf");
}
~RtfFileExporter()
{
if (_rtb != null && !_rtb.IsDisposed)
_rtb.Dispose();
}
}
}``` |
bc7d5c7f-c4b8-4bc3-9257-b20084af5cbc | {
"language": "C#"
} | ```c#
using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
return value.ToFingerPrintMd5Hash();
}
}
}```
Disable adding redundant arguments for getting machine id | ```c#
using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
return ComputerId.Value.ToFingerPrintMd5Hash();
}
}
}``` |
fd2c3b74-ae18-4cc3-8513-b712961dfcd9 | {
"language": "C#"
} | ```c#
using System;
using ChamberLib.Content;
using System.IO;
namespace ChamberLib.OpenTK
{
public class GlslShaderImporter
{
public GlslShaderImporter(ShaderStageImporter next=null)
{
this.next = next;
}
readonly ShaderStageImporter next;
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (File.Exists(filename))
{
}
else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
{
filename += ".vert";
}
else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
{
filename += ".frag";
}
else if (next != null)
{
return next(filename, type, importer);
}
else
{
throw new FileNotFoundException(
string.Format(
"The {0} shader file could not be found: {1}",
type,
filename),
filename);
}
var source = File.ReadAllText(filename);
return new ShaderContent(
vs: (type == ShaderType.Vertex ? source : null),
fs: (type == ShaderType.Fragment ? source : null),
name: filename,
type: ShaderType.Vertex);
}
}
}
```
Set the right shader type. | ```c#
using System;
using ChamberLib.Content;
using System.IO;
namespace ChamberLib.OpenTK
{
public class GlslShaderImporter
{
public GlslShaderImporter(ShaderStageImporter next=null)
{
this.next = next;
}
readonly ShaderStageImporter next;
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (File.Exists(filename))
{
}
else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
{
filename += ".vert";
}
else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
{
filename += ".frag";
}
else if (next != null)
{
return next(filename, type, importer);
}
else
{
throw new FileNotFoundException(
string.Format(
"The {0} shader file could not be found: {1}",
type,
filename),
filename);
}
var source = File.ReadAllText(filename);
return new ShaderContent(
vs: (type == ShaderType.Vertex ? source : null),
fs: (type == ShaderType.Fragment ? source : null),
name: filename,
type: type);
}
}
}
``` |
739bd9b9-c111-47fd-96f4-57db645b2e0f | {
"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;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneScheduleScreen : TournamentTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
Add(new ScheduleScreen());
}
}
}
```
Add tests for time display | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneScheduleScreen : TournamentTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
Add(new ScheduleScreen());
}
[Test]
public void TestCurrentMatchTime()
{
setMatchDate(TimeSpan.FromDays(-1));
setMatchDate(TimeSpan.FromSeconds(5));
setMatchDate(TimeSpan.FromMinutes(4));
setMatchDate(TimeSpan.FromHours(3));
}
private void setMatchDate(TimeSpan relativeTime)
// Humanizer cannot handle negative timespans.
=> AddStep($"start time is {relativeTime}", () =>
{
var match = CreateSampleMatch();
match.Date.Value = DateTimeOffset.Now + relativeTime;
Ladder.CurrentMatch.Value = match;
});
}
}
``` |
f09518c0-8c09-47f8-96fb-c018da3a529a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Configuration;
namespace uSync.Core
{
/// <summary>
/// a centralized way of telling if the current version of umbraco has
/// certain features or not.
/// </summary>
public class uSyncCapabilityChecker
{
private readonly IUmbracoVersion _version;
public uSyncCapabilityChecker(IUmbracoVersion version)
{
_version = version;
}
/// <summary>
/// History cleanup was introduced in Umbraco 9.1
/// </summary>
/// <remarks>
/// anything above v9.1 has history cleanup.
/// </remarks>
public bool HasHistoryCleanup
=> _version.Version.Major != 9 || _version.Version.Minor >= 1;
/// <summary>
/// Has a runtime mode introduced in v10.1
/// </summary>
/// <remarks>
/// Runtime mode of Production means you can't update views etc.
/// </remarks>
public bool HasRuntimeMode
=> _version.Version.Major > 10 ||
_version.Version.Major == 10 && _version.Version.Minor > 1;
}
}
```
Update compatibility checks for user language permissions | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Configuration;
namespace uSync.Core
{
/// <summary>
/// a centralized way of telling if the current version of umbraco has
/// certain features or not.
/// </summary>
public class uSyncCapabilityChecker
{
private readonly IUmbracoVersion _version;
public uSyncCapabilityChecker(IUmbracoVersion version)
{
_version = version;
}
/// <summary>
/// History cleanup was introduced in Umbraco 9.1
/// </summary>
/// <remarks>
/// anything above v9.1 has history cleanup.
/// </remarks>
public bool HasHistoryCleanup
=> _version.Version.Major != 9 || _version.Version.Minor >= 1;
/// <summary>
/// Has a runtime mode introduced in v10.1
/// </summary>
/// <remarks>
/// Runtime mode of Production means you can't update views etc.
/// </remarks>
public bool HasRuntimeMode
=> _version.Version.Major > 10 ||
_version.Version.Major == 10 && _version.Version.Minor > 1;
/// <summary>
/// User groups has Language Permissions - introduced in Umbraco 10.2.0
/// </summary>
public bool HasGroupLanguagePermissions => _version.Version >= new Version(10, 2, 0);
}
}
``` |
896f0132-6b68-4f72-ba52-3d0faef9e0e8 | {
"language": "C#"
} | ```c#
@using System.Security.Principal
@if (User.IsSignedIn())
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}```
Correct namespace to fix failure | ```c#
@using System.Security.Claims
@if (User.IsSignedIn())
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}``` |
61b4fc0a-9e87-4064-986d-adb7992223d1 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;
namespace Azuria.Middleware
{
/// <summary>
/// Adds some static headers to the request. They indicate things like application, version and api key used.
/// </summary>
public class StaticHeaderMiddleware : IMiddleware
{
private readonly IDictionary<string, string> _staticHeaders;
/// <summary>
///
/// </summary>
/// <param name="staticHeaders"></param>
public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
{
this._staticHeaders = staticHeaders;
}
/// <inheritdoc />
public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this._staticHeaders), cancellationToken);
}
/// <inheritdoc />
public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
MiddlewareAction<T> next, CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this._staticHeaders), cancellationToken);
}
}
}```
Make header of header middleware publicly accessible | ```c#
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;
namespace Azuria.Middleware
{
/// <summary>
/// Adds some static headers to the request. They indicate things like application, version and api key used.
/// </summary>
public class StaticHeaderMiddleware : IMiddleware
{
/// <summary>
///
/// </summary>
/// <param name="staticHeaders"></param>
public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
{
this.Header = staticHeaders;
}
/// <summary>
///
/// </summary>
/// <value></value>
public IDictionary<string, string> Header { get; }
/// <inheritdoc />
public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this.Header), cancellationToken);
}
/// <inheritdoc />
public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
MiddlewareAction<T> next, CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this.Header), cancellationToken);
}
}
}``` |
21ca9d76-d150-472a-b09e-9f6666ef29cc | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;
namespace SIM.Pipelines.Install.Containers
{
public enum Topology
{
Xm1,
Xp0,
Xp1
}
public static class StringExtentions
{
public static Topology ToTopology(this string tpl)
{
if (tpl.Equals("xp0", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xp0;
}
if (tpl.Equals("xp1", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xp1;
}
if (tpl.Equals("xm1", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xm1;
}
throw new InvalidOperationException("Topology cannot be resolved from '" + tpl + "'");
}
}
public class InstallContainerArgs : ProcessorArgs
{
public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
{
this.EnvModel = model;
this.FilesRoot = filesRoot;
this.Destination = destination;
this.Topology = topology.ToTopology();
}
public EnvModel EnvModel { get; }
public string Destination
{
get; set;
}
public Topology Topology { get; }
public string FilesRoot
{
get;
}
}
}
```
Simplify parsing string to Topology enum | ```c#
using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;
namespace SIM.Pipelines.Install.Containers
{
public enum Topology
{
Xm1,
Xp0,
Xp1
}
public class InstallContainerArgs : ProcessorArgs
{
public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
{
this.EnvModel = model;
this.FilesRoot = filesRoot;
this.Destination = destination;
this.Topology = (Topology)Enum.Parse(typeof(Topology), topology, true);
}
public EnvModel EnvModel { get; }
public string Destination
{
get; set;
}
public Topology Topology { get; }
public string FilesRoot
{
get;
}
}
}
``` |
b32dfcc8-7eed-448b-93ab-a3480f6537d3 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
public class JournalFileHeader : JournalEntry
{
public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
{
GameVersion = Tools.GetStringDef(evt["gameversion"]);
Build = Tools.GetStringDef(evt["build"]);
Language = Tools.GetStringDef(evt["language"]);
}
public string GameVersion { get; set; }
public string Build { get; set; }
public string Language { get; set; }
}
}
```
Add Beta property on FleaHeader event | ```c#
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
public class JournalFileHeader : JournalEntry
{
public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
{
GameVersion = Tools.GetStringDef(evt["gameversion"]);
Build = Tools.GetStringDef(evt["build"]);
Language = Tools.GetStringDef(evt["language"]);
}
public string GameVersion { get; set; }
public string Build { get; set; }
public string Language { get; set; }
public bool Beta
{
get
{
if (GameVersion.Contains("Beta"))
return true;
if (GameVersion.Equals("2.2") && Build.Contains("r121645/r0"))
return true;
return false;
}
}
}
}
``` |
4fb0e129-eac2-48b4-9ffb-95384e5697f1 | {
"language": "C#"
} | ```c#
using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
namespace Ets.Mobile.Pages.Account
{
public partial class LoginPage : IViewFor<LoginViewModel>
{
#region IViewFor<T>
public LoginViewModel ViewModel
{
get { return (LoginViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (LoginViewModel)value; }
}
#endregion
public LoginPage()
{
InitializeComponent();
// When ViewModel is set
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Subscribe(x =>
{
#if DEBUG
ViewModel.UserName = "";
ViewModel.Password = "";
#endif
Login.Click += (sender, arg) => { ErrorMessage.Visibility = Visibility.Collapsed; };
});
// Error Handling
UserError.RegisterHandler(ue =>
{
ErrorMessage.Text = ue.ErrorMessage;
ErrorMessage.Visibility = Visibility.Visible;
return Observable.Return(RecoveryOptionResult.CancelOperation);
});
this.BindCommand(ViewModel, x => x.Login, x => x.Login);
PartialInitialize();
}
partial void PartialInitialize();
}
}```
Use ReactiveUI Events for Click Handler | ```c#
using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
namespace Ets.Mobile.Pages.Account
{
public partial class LoginPage : IViewFor<LoginViewModel>
{
#region IViewFor<T>
public LoginViewModel ViewModel
{
get { return (LoginViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (LoginViewModel)value; }
}
#endregion
public LoginPage()
{
InitializeComponent();
// When ViewModel is set
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Subscribe(x =>
{
Login.Events().Click.Subscribe(arg => ErrorMessage.Visibility = Visibility.Collapsed);
});
// Error Handling
UserError.RegisterHandler(ue =>
{
ErrorMessage.Text = ue.ErrorMessage;
ErrorMessage.Visibility = Visibility.Visible;
return Observable.Return(RecoveryOptionResult.CancelOperation);
});
PartialInitialize();
}
partial void PartialInitialize();
}
}``` |
a34cd053-bf24-418c-a8b6-0d62a9f5fc50 | {
"language": "C#"
} | ```c#
using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;
namespace AllReady.UnitTest
{
/// <summary>
/// Inherit from this type to implement tests that
/// have access to a service provider, empty in-memory
/// database, and basic configuration.
/// </summary>
public abstract class TestBase
{
protected IServiceProvider ServiceProvider { get; private set; }
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services.AddEntityFramework()
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
}
}
```
Fix for EFCore using the same InMemoryDatabase Instance when running tests. | ```c#
using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;
namespace AllReady.UnitTest
{
/// <summary>
/// Inherit from this type to implement tests that
/// have access to a service provider, empty in-memory
/// database, and basic configuration.
/// </summary>
public abstract class TestBase
{
protected IServiceProvider ServiceProvider { get; private set; }
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
}
}
``` |
df0cf315-b89f-4bf6-b594-30457a67e2bb | {
"language": "C#"
} | ```c#
using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.SpaFallback
{
public class SpaFallbackOptions
{
public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = _ => "/index.html";
public bool AllowFileExtensions { get; set; } = false;
public bool ThrowIfFallbackFails { get; set; } = true;
}
}
```
Make default fallback path factory static | ```c#
using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.SpaFallback
{
public class SpaFallbackOptions
{
private static readonly Func<HttpContext, PathString> DefaultFallbackPathFactory = _ => "/index.html";
public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = DefaultFallbackPathFactory;
public bool AllowFileExtensions { get; set; } = false;
public bool ThrowIfFallbackFails { get; set; } = true;
}
}
``` |
d2aee105-e631-4f86-8ae8-8450c86e9ec2 | {
"language": "C#"
} | ```c#
using System;
using NHibernate.Cfg;
using NUnit.Framework;
namespace NHibernate.Test.CfgTest
{
/// <summary>
/// Summary description for ConfigurationFixture.
/// </summary>
[TestFixture]
public class ConfigurationFixture
{
[SetUp]
public void SetUp()
{
System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
}
[TearDown]
public void TearDown()
{
System.IO.File.Delete("hibernate.cfg.xml");
}
/// <summary>
/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
/// file and that the values override what is in the app.config.
/// </summary>
[Test]
public void ReadCfgXmlFromDefaultFile()
{
Configuration cfg = new Configuration();
cfg.Configure();
Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);
}
}
}
```
Test now restores Environment properties back to their original values. | ```c#
using System;
using NHibernate.Cfg;
using NUnit.Framework;
namespace NHibernate.Test.CfgTest
{
/// <summary>
/// Summary description for ConfigurationFixture.
/// </summary>
[TestFixture]
public class ConfigurationFixture
{
[SetUp]
public void SetUp()
{
System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
}
[TearDown]
public void TearDown()
{
System.IO.File.Delete("hibernate.cfg.xml");
}
/// <summary>
/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
/// file and that the values override what is in the app.config.
/// </summary>
[Test]
public void ReadCfgXmlFromDefaultFile()
{
string origQuerySubst = Cfg.Environment.Properties[Cfg.Environment.QuerySubstitutions] as string;
string origConnString = Cfg.Environment.Properties[Cfg.Environment.ConnectionString] as string;
Configuration cfg = new Configuration();
cfg.Configure();
Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);
cfg.Properties[Cfg.Environment.QuerySubstitutions] = origQuerySubst;
cfg.Properties[Cfg.Environment.ConnectionString] = origConnString;
}
}
}
``` |
68ddb02d-7ddf-4dfe-9323-293311c3f56c | {
"language": "C#"
} | ```c#
@model List<Post>
<section class="home-latest-posts">
<h3 class="header-surround-bar"><span>Latest Posts</span></h3>
<div class="row width-100">
@foreach (var post in Model.Take(4))
{
<div class="large-3 columns end">
@Html.Partial("_HomePostCard", post)
</div>
}
</div>
<div class="row width-100">
@foreach (var post in Model.Skip(4))
{
<div class="large-3 columns end">
@Html.Partial("_HomePostCard", post)
</div>
}
</div>
</section>```
Add medium breakpoint to home latests posts. | ```c#
@model List<Post>
<section class="home-latest-posts">
<h3 class="header-surround-bar"><span>Latest Posts</span></h3>
<div class="row width-100">
@foreach (var post in Model.Take(4))
{
<div class="large-3 medium-6 columns end">
@Html.Partial("_HomePostCard", post)
</div>
}
</div>
<div class="row width-100">
@foreach (var post in Model.Skip(4))
{
<div class="large-3 medium-6 columns end">
@Html.Partial("_HomePostCard", post)
</div>
}
</div>
</section>``` |
a45b8f9a-ff89-4f49-bd7a-d6e74874542f | {
"language": "C#"
} | ```c#
namespace GitTools.IssueTrackers.Jira
{
public static class StringExtensions
{
public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND")
{
if (!string.IsNullOrWhiteSpace(value))
{
value += string.Format(" {0} ", joinText);
}
else
{
value = string.Empty;
}
value += additionalValue;
return value;
}
}
}```
Change class visibility from public to internal for Jira string extensions | ```c#
namespace GitTools.IssueTrackers.Jira
{
internal static class StringExtensions
{
public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND")
{
if (!string.IsNullOrWhiteSpace(value))
{
value += string.Format(" {0} ", joinText);
}
else
{
value = string.Empty;
}
value += additionalValue;
return value;
}
}
}``` |
6f00f896-867f-45de-90e3-345c85eb33a7 | {
"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;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Argon
{
public class ArgonSliderScorePoint : CircularContainer
{
private Bindable<Color4> accentColour = null!;
private const float size = 12;
[BackgroundDependencyLoader]
private void load(DrawableHitObject hitObject)
{
Masking = true;
Origin = Anchor.Centre;
Size = new Vector2(size);
BorderThickness = 3;
BorderColour = Color4.White;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
AlwaysPresent = true,
Alpha = 0,
};
accentColour = hitObject.AccentColour.GetBoundCopy();
accentColour.BindValueChanged(accent => BorderColour = accent.NewValue);
}
}
}
```
Fix slider tick colour not being applied properly | ```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;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Argon
{
public class ArgonSliderScorePoint : CircularContainer
{
private Bindable<Color4> accentColour = null!;
private const float size = 12;
[BackgroundDependencyLoader]
private void load(DrawableHitObject hitObject)
{
Masking = true;
Origin = Anchor.Centre;
Size = new Vector2(size);
BorderThickness = 3;
BorderColour = Color4.White;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
AlwaysPresent = true,
Alpha = 0,
};
accentColour = hitObject.AccentColour.GetBoundCopy();
accentColour.BindValueChanged(accent => BorderColour = accent.NewValue, true);
}
}
}
``` |
58d07988-e081-47ba-a83d-9f055b99c5d4 | {
"language": "C#"
} | ```c#
using System;
using Xunit;
using Zuehlke.Eacm.Web.Backend.CQRS;
namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel
{
public class EventAggregatorExtensionsFixture
{
[Fact]
public void PublishEvent_()
{
// arrange
// act
// assert
}
private class TestEvent : IEvent
{
public Guid CorrelationId
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public Guid Id
{
get
{
throw new NotImplementedException();
}
}
public Guid SourceId
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public DateTime Timestamp
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
}
```
Implement tests for the EventAggregatorExtensions class. | ```c#
using System;
using Xunit;
using Zuehlke.Eacm.Web.Backend.CQRS;
using Zuehlke.Eacm.Web.Backend.Utils.PubSubEvents;
namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel
{
public class EventAggregatorExtensionsFixture
{
[Fact]
public void PublishEvent_EventAggregatorIsNull_ThrowsException()
{
// arrange
IEventAggregator eventAggegator = null;
IEvent e = new TestEvent();
// act
Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e));
}
[Fact]
public void PublishEvent_EventIsNull_ThrowsException()
{
// arrange
IEventAggregator eventAggegator = new EventAggregator();
IEvent e = null;
// act
Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e));
}
[Fact]
public void PublishEvent_WithEventSubscription_HandlerGetsCalleds()
{
// arrange
IEventAggregator eventAggegator = new EventAggregator();
IEvent e = new TestEvent();
bool executed = false;
eventAggegator.Subscribe<TestEvent>(ev => executed = true);
// act
CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e);
Assert.True(executed);
}
private class TestEvent : IEvent
{
public Guid CorrelationId
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public Guid Id
{
get
{
throw new NotImplementedException();
}
}
public Guid SourceId
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public DateTime Timestamp
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
}
``` |
f54b468d-be20-452c-ab7e-186066a1f37f | {
"language": "C#"
} | ```c#
using Aurora.Profiles.Generic.GSI.Nodes;
using Aurora.Profiles.TModLoader.GSI.Nodes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aurora.Profiles.TModLoader.GSI {
public class GameState_TModLoader : GameState<GameState_TModLoader> {
public ProviderNode Provider => NodeFor<ProviderNode>("provider");
public WorldNode World => NodeFor<WorldNode>("world");
public PlayerNode Player => NodeFor<PlayerNode>("player");
public GameState_TModLoader() : base() { }
/// <summary>
/// Creates a GameState_Terraria instance based on the passed JSON data.
/// </summary>
/// <param name="JSONstring"></param>
public GameState_TModLoader(string JSONstring) : base(JSONstring) { }
}
}
```
Fix error with merge on TModLoader GameState. | ```c#
using Aurora.Profiles.Generic.GSI.Nodes;
using Aurora.Profiles.TModLoader.GSI.Nodes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aurora.Profiles.TModLoader.GSI {
public class GameState_TModLoader : GameState {
public ProviderNode Provider => NodeFor<ProviderNode>("provider");
public WorldNode World => NodeFor<WorldNode>("world");
public PlayerNode Player => NodeFor<PlayerNode>("player");
public GameState_TModLoader() : base() { }
/// <summary>
/// Creates a GameState_Terraria instance based on the passed JSON data.
/// </summary>
/// <param name="JSONstring"></param>
public GameState_TModLoader(string JSONstring) : base(JSONstring) { }
}
}
``` |
90a3acd5-62ca-401d-b0da-81acae89a31c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
/*var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);*/
//Commenting the above code and using the below line gets rid of the master mobile site.
routes.EnableFriendlyUrls();
}
}
}
```
Switch the settings back for the mobile site. Fix this later | ```c#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
//Commenting the above code and using the below line gets rid of the master mobile site.
//routes.EnableFriendlyUrls();
}
}
}
``` |
fa7e9d3b-4557-4f88-b4ef-1682a009ab40 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class SimpleLinkedList<T> : IEnumerable<T>
{
public SimpleLinkedList(T value) :
this(new[] { value })
{
}
public SimpleLinkedList(IEnumerable<T> values)
{
var array = values.ToArray();
if (array.Length == 0)
{
throw new ArgumentException("Cannot create tree from empty list");
}
Value = array[0];
Next = null;
foreach (var value in array.Skip(1))
{
Add(value);
}
}
public T Value { get; }
public SimpleLinkedList<T> Next { get; private set; }
public SimpleLinkedList<T> Add(T value)
{
var last = this;
while (last.Next != null)
{
last = last.Next;
}
last.Next = new SimpleLinkedList<T>(value);
return this;
}
public SimpleLinkedList<T> Reverse()
{
return new SimpleLinkedList<T>(this.AsEnumerable().Reverse());
}
public IEnumerator<T> GetEnumerator()
{
yield return Value;
foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>())
{
yield return next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}```
Remove unnecessary Reverse() method in simple-linked-list | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class SimpleLinkedList<T> : IEnumerable<T>
{
public SimpleLinkedList(T value) :
this(new[] { value })
{
}
public SimpleLinkedList(IEnumerable<T> values)
{
var array = values.ToArray();
if (array.Length == 0)
{
throw new ArgumentException("Cannot create tree from empty list");
}
Value = array[0];
Next = null;
foreach (var value in array.Skip(1))
{
Add(value);
}
}
public T Value { get; }
public SimpleLinkedList<T> Next { get; private set; }
public SimpleLinkedList<T> Add(T value)
{
var last = this;
while (last.Next != null)
{
last = last.Next;
}
last.Next = new SimpleLinkedList<T>(value);
return this;
}
public IEnumerator<T> GetEnumerator()
{
yield return Value;
foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>())
{
yield return next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}``` |
f932779b-4bdc-45b4-aaee-095a079b3698 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using MessagePack;
using Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
[MessagePackObject]
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
[Key(0)]
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly float? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, float? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
```
Add signalr messagepack key attribute | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using MessagePack;
using Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
[MessagePackObject]
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
[Key(0)]
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
[Key(1)]
public readonly float? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, float? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
``` |
805cfa96-3ee0-488c-9055-c4b5cd78b586 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EpubSharp.Tests
{
[TestClass]
public class EpubWriterTests
{
[TestMethod]
public void SaveTest()
{
var book = EpubReader.Read(@"../../Samples/epub-assorted/iOS Hackers Handbook.epub");
var writer = new EpubWriter(book);
writer.Save("saved.epub");
}
}
}
```
Use smaller epub for saving test, so that online validators accept the size. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EpubSharp.Tests
{
[TestClass]
public class EpubWriterTests
{
[TestMethod]
public void SaveTest()
{
var book = EpubReader.Read(@"../../Samples/epub-assorted/Inversions - Iain M. Banks.epub");
var writer = new EpubWriter(book);
writer.Save("saved.epub");
}
}
}
``` |
06d284d2-bf81-4409-93b6-bd175e56acc6 | {
"language": "C#"
} | ```c#
using CefSharp.Internals;
using System.Collections.Generic;
using System.ServiceModel;
namespace CefSharp.BrowserSubprocess
{
public class CefRenderProcess : CefSubProcess, IRenderProcess
{
private DuplexChannelFactory<IBrowserProcess> channelFactory;
private CefBrowserBase browser;
public CefBrowserBase Browser
{
get { return browser; }
}
public CefRenderProcess(IEnumerable<string> args)
: base(args)
{
}
protected override void DoDispose(bool isDisposing)
{
//DisposeMember(ref renderprocess);
DisposeMember(ref browser);
base.DoDispose(isDisposing);
}
public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper)
{
browser = cefBrowserWrapper;
if (ParentProcessId == null)
{
return;
}
channelFactory = new DuplexChannelFactory<IBrowserProcess>(
this,
new NetNamedPipeBinding(),
new EndpointAddress(RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId))
);
channelFactory.Open();
Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects());
}
public object EvaluateScript(int frameId, string script, double timeout)
{
var result = Browser.EvaluateScript(frameId, script, timeout);
return result;
}
public override IBrowserProcess CreateBrowserProxy()
{
return channelFactory.CreateChannel();
}
}
}
```
Move serviceName to variable - makes for easier debugging | ```c#
using CefSharp.Internals;
using System.Collections.Generic;
using System.ServiceModel;
namespace CefSharp.BrowserSubprocess
{
public class CefRenderProcess : CefSubProcess, IRenderProcess
{
private DuplexChannelFactory<IBrowserProcess> channelFactory;
private CefBrowserBase browser;
public CefBrowserBase Browser
{
get { return browser; }
}
public CefRenderProcess(IEnumerable<string> args)
: base(args)
{
}
protected override void DoDispose(bool isDisposing)
{
//DisposeMember(ref renderprocess);
DisposeMember(ref browser);
base.DoDispose(isDisposing);
}
public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper)
{
browser = cefBrowserWrapper;
if (ParentProcessId == null)
{
return;
}
var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId);
channelFactory = new DuplexChannelFactory<IBrowserProcess>(
this,
new NetNamedPipeBinding(),
new EndpointAddress(serviceName)
);
channelFactory.Open();
Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects());
}
public object EvaluateScript(int frameId, string script, double timeout)
{
var result = Browser.EvaluateScript(frameId, script, timeout);
return result;
}
public override IBrowserProcess CreateBrowserProxy()
{
return channelFactory.CreateChannel();
}
}
}
``` |
d75abff9-c280-454a-9480-942fd0c4879e | {
"language": "C#"
} | ```c#
using System;
using App.Services;
using App.Services.Contracts;
using App.ViewModels;
using App.ViewModels.Contracts;
using Microsoft.Practices.Unity;
namespace App.Infrastructure
{
// ReSharper disable once InconsistentNaming
public sealed class UWPBootstrapper : CaliburnBootstrapper
{
public UWPBootstrapper(Action createWindow) : base(createWindow)
{
}
protected override void Configure()
{
base.Configure();
this.UnityContainer.RegisterType<IOpenFolderService, OpenFolderService>();
this.UnityContainer.RegisterType<IShellViewModel, ShellViewModel>();
}
public override void Dispose()
{
base.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.SuppressFinalize(this);
}
}
}```
Use the chain way for registering services and view models. | ```c#
using System;
using App.Services;
using App.Services.Contracts;
using App.ViewModels;
using App.ViewModels.Contracts;
using Microsoft.Practices.Unity;
namespace App.Infrastructure
{
// ReSharper disable once InconsistentNaming
public sealed class UWPBootstrapper : CaliburnBootstrapper
{
public UWPBootstrapper(Action createWindow) : base(createWindow)
{
}
protected override void Configure()
{
base.Configure();
this.UnityContainer
.RegisterType<IOpenFolderService, OpenFolderService>()
.RegisterType<IShellViewModel, ShellViewModel>();
}
public override void Dispose()
{
base.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.SuppressFinalize(this);
}
}
}``` |
a0cd3aad-4101-4acc-839d-e1881ef2ba9c | {
"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.
#if NET5_0
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using OpenTabletDriver;
using osu.Framework.Input.Handlers.Tablet;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTabletDriver : BenchmarkTest
{
private TabletDriver driver;
public override void SetUp()
{
var collection = new DriverServiceCollection()
.AddTransient<TabletDriver>();
var serviceProvider = collection.BuildServiceProvider();
driver = serviceProvider.GetRequiredService<TabletDriver>();
}
[Benchmark]
public void DetectBenchmark()
{
driver.Detect();
}
}
}
#endif
```
Fix remaining usage of DI instead of direct `Create()` call | ```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.
#if NET5_0
using BenchmarkDotNet.Attributes;
using osu.Framework.Input.Handlers.Tablet;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTabletDriver : BenchmarkTest
{
private TabletDriver driver;
public override void SetUp()
{
driver = TabletDriver.Create();
}
[Benchmark]
public void DetectBenchmark()
{
driver.Detect();
}
}
}
#endif
``` |
2bccd40d-55cd-45e9-9766-a142adbd5a1a | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Beatmaps.Drawables
{
/// <summary>
/// Display a baetmap background from a local source, but fallback to online source if not available.
/// </summary>
public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo>
{
public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>();
[Resolved]
private BeatmapManager beatmaps { get; set; }
public UpdateableBeatmapBackgroundSprite()
{
Beatmap.BindValueChanged(b => Model = b);
}
protected override Drawable CreateDrawable(BeatmapInfo model)
{
Drawable drawable;
var localBeatmap = beatmaps.GetWorkingBeatmap(model);
if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null)
drawable = new BeatmapSetCover(model.BeatmapSet);
else
drawable = new BeatmapBackgroundSprite(localBeatmap);
drawable.RelativeSizeAxes = Axes.Both;
drawable.Anchor = Anchor.Centre;
drawable.Origin = Anchor.Centre;
drawable.FillMode = FillMode.Fill;
return drawable;
}
protected override double FadeDuration => 400;
}
}
```
Fix covers being loaded even when off-screen | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Beatmaps.Drawables
{
/// <summary>
/// Display a baetmap background from a local source, but fallback to online source if not available.
/// </summary>
public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo>
{
public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>();
[Resolved]
private BeatmapManager beatmaps { get; set; }
public UpdateableBeatmapBackgroundSprite()
{
Beatmap.BindValueChanged(b => Model = b);
}
protected override Drawable CreateDrawable(BeatmapInfo model)
{
return new DelayedLoadUnloadWrapper(() => {
Drawable drawable;
var localBeatmap = beatmaps.GetWorkingBeatmap(model);
if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null)
drawable = new BeatmapSetCover(model.BeatmapSet);
else
drawable = new BeatmapBackgroundSprite(localBeatmap);
drawable.RelativeSizeAxes = Axes.Both;
drawable.Anchor = Anchor.Centre;
drawable.Origin = Anchor.Centre;
drawable.FillMode = FillMode.Fill;
drawable.OnLoadComplete = d => d.FadeInFromZero(400);
return drawable;
}, 500, 10000);
}
protected override double FadeDuration => 0;
}
}
``` |
c2310590-def0-4723-93a6-dc99f16a3fa4 | {
"language": "C#"
} | ```c#
using FluentAssertions;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Integration
{
[TestFixture]
public class UsingDefaultConfigFilePath
{
[Test]
#if NETCOREAPP
[Ignore("Buggy interaction between the test runner and System.Configuration.ConfigurationManager, see https://github.com/nunit/nunit3-vs-adapter/issues/356")]
#endif
public void Mapping_from_the_default_file_path()
{
var foo = AutoConfig.Map<IFoo>();
var bar = AutoConfig.Map<IFoo>("bar");
foo.Should().NotBeNull();
foo.Name.Should().Be("foo");
bar.Should().NotBeNull();
bar.Name.Should().Be("bar");
}
public interface IFoo
{
string Name { get; }
}
}
}
```
Use a workaround to make Mapping_from_the_default_file_path pass on .NET Core | ```c#
using FluentAssertions;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Integration
{
[TestFixture]
public class UsingDefaultConfigFilePath
#if NETCOREAPP
: System.IDisposable
{
private readonly string _configFilePath;
// In order to workaround flaky interaction between the test runner and System.Configuration.ConfigurationManager
// See https://github.com/nunit/nunit3-vs-adapter/issues/356#issuecomment-700754225
public UsingDefaultConfigFilePath()
{
_configFilePath = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath;
System.IO.File.Copy($"{System.Reflection.Assembly.GetExecutingAssembly().Location}.config", _configFilePath, overwrite: true);
}
public void Dispose()
{
System.IO.File.Delete(_configFilePath);
}
#else
{
#endif
[Test]
public void Mapping_from_the_default_file_path()
{
var foo = AutoConfig.Map<IFoo>();
var bar = AutoConfig.Map<IFoo>("bar");
foo.Should().NotBeNull();
foo.Name.Should().Be("foo");
bar.Should().NotBeNull();
bar.Name.Should().Be("bar");
}
public interface IFoo
{
string Name { get; }
}
}
}
``` |
c0e5f1b7-9e62-440f-9fb0-1e61623c6b63 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Antlr4;
using Antlr4.Runtime;
namespace Rubberduck.Math
{
public static class Calculator
{
public static int Evaluate(string expression)
{
var lexer = new BasicMathLexer(new AntlrInputStream(expression));
lexer.RemoveErrorListeners();
lexer.AddErrorListener(new ThrowExceptionErrorListener());
var tokens = new CommonTokenStream(lexer);
var parser = new BasicMathParser(tokens);
var tree = parser.compileUnit();
var visitor = new IntegerMathVisitor();
return visitor.Visit(tree);
}
}
}
```
Throw exception if more than one expression is passed to Evaluate | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Antlr4;
using Antlr4.Runtime;
namespace Rubberduck.Math
{
public static class Calculator
{
public static int Evaluate(string expression)
{
var lexer = new BasicMathLexer(new AntlrInputStream(expression));
lexer.RemoveErrorListeners();
lexer.AddErrorListener(new ThrowExceptionErrorListener());
var tokens = new CommonTokenStream(lexer);
var parser = new BasicMathParser(tokens);
var tree = parser.compileUnit();
var exprCount = tree.expression().Count;
if (exprCount > 1)
{
throw new ArgumentException(String.Format("Too many expressions. Only one can be evaluated. {0} expressions were entered.", exprCount));
}
var visitor = new IntegerMathVisitor();
return visitor.Visit(tree);
}
}
}
``` |
e20f5f0f-9727-4cd3-8ed7-4cbb9f8b5aad | {
"language": "C#"
} | ```c#
using System.IO;
using UnityEditor;
using UnityEngine;
namespace DTCommandPalette {
public abstract class GameObjectCommand : ICommand {
// PRAGMA MARK - ICommand
public string DisplayTitle {
get {
return _obj.name;
}
}
public string DisplayDetailText {
get {
return _obj.FullName();
}
}
public abstract Texture2D DisplayIcon {
get;
}
public bool IsValid() {
return _obj != null;
}
public abstract void Execute();
// PRAGMA MARK - Constructors
public GameObjectCommand(GameObject obj) {
_obj = obj;
}
// PRAGMA MARK - Internal
protected GameObject _obj;
}
}```
Fix null references when game object is destroyed | ```c#
using System.IO;
using UnityEditor;
using UnityEngine;
namespace DTCommandPalette {
public abstract class GameObjectCommand : ICommand {
// PRAGMA MARK - ICommand
public string DisplayTitle {
get {
if (!IsValid()) {
return "";
}
return _obj.name;
}
}
public string DisplayDetailText {
get {
if (!IsValid()) {
return "";
}
return _obj.FullName();
}
}
public abstract Texture2D DisplayIcon {
get;
}
public bool IsValid() {
return _obj != null;
}
public abstract void Execute();
// PRAGMA MARK - Constructors
public GameObjectCommand(GameObject obj) {
_obj = obj;
}
// PRAGMA MARK - Internal
protected GameObject _obj;
}
}``` |
8679fe52-09fe-42b5-802c-48494a3fcd96 | {
"language": "C#"
} | ```c#
using System;
namespace Pixie
{
/// <summary>
/// A base class for markup nodes: composable elements that can
/// be rendered.
/// </summary>
public abstract class MarkupNode
{
/// <summary>
/// Gets a fallback version of this node for when the renderer
/// doesn't know how to render this node's type. Null is
/// returned if no reasonable fallback can be provided.
/// </summary>
/// <returns>The node's fallback version, or <c>null</c>.</returns>
public abstract MarkupNode Fallback { get; }
/// <summary>
/// Applies a mapping to this markup node's children and returns
/// a new instance of this node's type that contains the modified
/// children.
/// </summary>
/// <param name="mapping">A mapping function.</param>
/// <returns>A new markup node.</returns>
public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping);
}
}```
Define an implicit conversion from strings to markup nodes | ```c#
using System;
using Pixie.Markup;
namespace Pixie
{
/// <summary>
/// A base class for markup nodes: composable elements that can
/// be rendered.
/// </summary>
public abstract class MarkupNode
{
/// <summary>
/// Gets a fallback version of this node for when the renderer
/// doesn't know how to render this node's type. Null is
/// returned if no reasonable fallback can be provided.
/// </summary>
/// <returns>The node's fallback version, or <c>null</c>.</returns>
public abstract MarkupNode Fallback { get; }
/// <summary>
/// Applies a mapping to this markup node's children and returns
/// a new instance of this node's type that contains the modified
/// children.
/// </summary>
/// <param name="mapping">A mapping function.</param>
/// <returns>A new markup node.</returns>
public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping);
/// <summary>
/// Creates a text markup node from a string of characters.
/// </summary>
/// <param name="text">
/// The text to wrap in a text markup node.
/// </param>
public static implicit operator MarkupNode(string text)
{
return new Text(text);
}
}
}
``` |
d33cc389-3ddb-4d9a-968d-083eb57f083f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Avalonia.Data;
namespace Avalonia
{
internal static class ClassBindingManager
{
private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties =
new Dictionary<string, AvaloniaProperty>();
public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor)
{
if (!s_RegisteredProperties.TryGetValue(className, out var prop))
s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className);
return target.Bind(prop, source, anchor);
}
private static AvaloniaProperty RegisterClassProxyProperty(string className)
{
var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className);
prop.Changed.Subscribe(args =>
{
var enable = args.NewValue.GetValueOrDefault();
var classes = ((IStyledElement)args.Sender).Classes;
if (enable)
{
if (!classes.Contains(className))
classes.Add(className);
}
else
classes.Remove(className);
});
return prop;
}
}
}
```
Simplify the code a bit | ```c#
using System;
using System.Collections.Generic;
using Avalonia.Data;
namespace Avalonia
{
internal static class ClassBindingManager
{
private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties =
new Dictionary<string, AvaloniaProperty>();
public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor)
{
if (!s_RegisteredProperties.TryGetValue(className, out var prop))
s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className);
return target.Bind(prop, source, anchor);
}
private static AvaloniaProperty RegisterClassProxyProperty(string className)
{
var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className);
prop.Changed.Subscribe(args =>
{
var classes = ((IStyledElement)args.Sender).Classes;
classes.Set(className, args.NewValue.GetValueOrDefault());
});
return prop;
}
}
}
``` |
5bd37150-5a1e-4819-a340-9f13515eab0a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Plugin.Scraping.TheGamesDb;
using Snowflake.Scraping;
using Snowflake.Scraping.Extensibility;
using Xunit;
namespace Snowflake.Scraping.Tests
{
public class ScraperIntegrationTests
{
[Fact]
public async Task TGDBScraping_Test()
{
var tgdb = new TheGamesDbScraper();
var scrapeJob = new ScrapeJob(new SeedContent[] {
("platform", "NINTENDO_NES"),
("search_title", "Super Mario Bros."),
}, new[] { tgdb }, new ICuller[] { });
while (await scrapeJob.Proceed());
}
}
}
```
Disable TGDB Tests for now | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Plugin.Scraping.TheGamesDb;
using Snowflake.Scraping;
using Snowflake.Scraping.Extensibility;
using Xunit;
namespace Snowflake.Scraping.Tests
{
public class ScraperIntegrationTests
{
// [Fact]
// public async Task TGDBScraping_Test()
// {
// var tgdb = new TheGamesDbScraper();
// var scrapeJob = new ScrapeJob(new SeedContent[] {
// ("platform", "NINTENDO_NES"),
// ("search_title", "Super Mario Bros."),
// }, new[] { tgdb }, new ICuller[] { });
// while (await scrapeJob.Proceed());
// }
}
}
``` |
64a9cb34-4833-42e3-89ad-55a2ae197275 | {
"language": "C#"
} | ```c#
namespace alert_roster.web.Migrations
{
using alert_roster.web.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
ContextKey = "alert_roster.web.Models.AlertRosterDbContext";
}
protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context)
{
// This method will be called after migrating to the latest version.
//context.Messages.AddOrUpdate(
// m => m.Content,
// new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" }
// );
}
}
}
```
Allow dataloss... shouldn't be necesssary? | ```c#
namespace alert_roster.web.Migrations
{
using alert_roster.web.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "alert_roster.web.Models.AlertRosterDbContext";
}
protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context)
{
// This method will be called after migrating to the latest version.
//context.Messages.AddOrUpdate(
// m => m.Content,
// new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" }
// );
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.