doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
fe89d640-c7b2-48e9-bad5-79b86e47ac67 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.Quality = Selected;
Close();
}
}
}```
Add bindings in settings viewmodel for user alert | ```c#
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
private bool _checked;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
Checked = _settings.UserAlert;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public bool Checked
{
get { return _checked; }
set
{
_checked = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.UserAlert = Checked;
_settings.Quality = Selected;
Close();
}
}
}``` |
9c8c0837-31f4-45a4-9473-2cd61048da06 | {
"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.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[SetUp]
public void SetUp() => Schedule(() =>
{
StarRatingDisplay changingStarRating;
Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
};
Scheduler.AddDelayed(() =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 500, true);
});
}
}
```
Use regular test steps rather than one-time set up and scheduling | ```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.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[Test]
public void TestDisplay()
{
StarRatingDisplay changingStarRating = null;
AddStep("load displays", () => Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
});
AddRepeatStep("change bottom rating", () =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 10);
}
}
}
``` |
b4786aa6-9572-4dc4-b242-6ca09be5faa8 | {
"language": "C#"
} | ```c#
@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options
@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultures = LocOptions.Value.SupportedUICultures
.Skip(1)
.Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
.ToArray();
}
<h2>Global categories</h2>
<table class="table">
<thead>
<tr>
<th>Default name</th>
@foreach (var culture in cultures)
{
<th>@culture.Name translate</th>
}
</tr>
</thead>
<tbody>
@foreach (var category in Model)
{
<tr>
<td>
@category.Name
<div class="input-group colorpicker colorpicker-component" data-id="@category.Id">
<input type="text" value="name" class="form-control" />
<input type="hidden" value="#@category.Color.ToString("X6")" />
<span class="input-group-addon"><i></i></span>
</div>
</td>
@foreach (var culture in cultures)
{
var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
if (locName != null)
{
<td>@locName.Name</td>
}
else
{
<td class="empty">@category.Name</td>
}
}
</tr>
}
</tbody>
</table>```
Make global categories colors are display only | ```c#
@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options
@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultures = LocOptions.Value.SupportedUICultures
.Skip(1)
.Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
.ToArray();
}
<h2>Global categories</h2>
<table class="table">
<thead>
<tr>
<th class="fit"></th>
<th>Default name</th>
@foreach (var culture in cultures)
{
<th>@culture.Name translate</th>
}
</tr>
</thead>
<tbody>
@foreach (var category in Model)
{
<tr>
<td>
<span class="label category-color" style="background-color: #@(category.Color.ToString("X6"))"> </span>
</td>
<td>
@category.Name
</td>
@foreach (var culture in cultures)
{
var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
if (locName != null)
{
<td>@locName.Name</td>
}
else
{
<td class="empty">@category.Name</td>
}
}
</tr>
}
</tbody>
</table>``` |
756273da-3c33-4eac-9f18-3e950c7c426b | {
"language": "C#"
} | ```c#
using FogCreek.Plugins;
[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FBExtendedEvents")]
```
Add new plugin repository URL | ```c#
using FogCreek.Plugins;
[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FogBugz-ExtendedEvents")]
``` |
43a78f63-a8bc-4e4b-a7d0-53e9cc5dae12 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
namespace BatteryCommander.Web.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Jobs()
{
return View(JobManager.AllSchedules);
}
}
}```
Add simple JSON endpoint for soldiers with access | ```c#
using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Jobs()
{
return View(JobManager.AllSchedules);
}
public async Task<IActionResult> Users()
{
var soldiers_with_access =
await db
.Soldiers
.Where(soldier => soldier.CanLogin)
.Select(soldier => new
{
soldier.FirstName,
soldier.LastName,
soldier.CivilianEmail
})
.ToListAsync();
return Json(soldiers_with_access);
}
}
}``` |
85b82657-e857-47a9-9b1f-1d12cdddb28a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
namespace BleLab.Services
{
public class CharacteristicSubscriptionService
{
private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();
public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;
public bool Subscribe(GattCharacteristic characteristic)
{
if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
return false;
characteristic.ValueChanged += CharacteristicOnValueChanged;
_subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
return true;
}
public bool Unsubscribe(GattCharacteristic characteristic)
{
if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
return false;
characteristic.ValueChanged -= CharacteristicOnValueChanged;
_subscribedCharacteristics.Remove(characteristic.Uuid);
return true;
}
public bool IsSubscribed(GattCharacteristic characteristic)
{
return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
}
public void DeviceDisconnected(BluetoothLEDevice device)
{
if (device == null)
return;
var deviceId = device.DeviceId;
var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.DeviceId == deviceId).ToList();
foreach (var characteristic in characteristics)
{
try
{
Unsubscribe(characteristic);
}
catch
{
}
}
}
private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
ValueChanged?.Invoke(sender, args);
}
}
}
```
Fix of not unsubscribing to characteristics on disconnect | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
namespace BleLab.Services
{
public class CharacteristicSubscriptionService
{
private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();
public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;
public bool Subscribe(GattCharacteristic characteristic)
{
if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
return false;
characteristic.ValueChanged += CharacteristicOnValueChanged;
_subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
return true;
}
public bool Unsubscribe(GattCharacteristic characteristic)
{
if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
return false;
characteristic.ValueChanged -= CharacteristicOnValueChanged;
_subscribedCharacteristics.Remove(characteristic.Uuid);
return true;
}
public bool IsSubscribed(GattCharacteristic characteristic)
{
return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
}
public void DeviceDisconnected(BluetoothLEDevice device)
{
if (device == null)
return;
var deviceId = device.DeviceId;
var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.Device.DeviceId == deviceId).ToList();
foreach (var characteristic in characteristics)
{
try
{
Unsubscribe(characteristic);
}
catch
{
}
}
}
private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
ValueChanged?.Invoke(sender, args);
}
}
}
``` |
4cd4aa0a-0fea-4ff7-9a38-1918b8d01748 | {
"language": "C#"
} | ```c#
using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var registry = new Registry();
registry.IncludeRegistry<InfrastructureRegistry>();
var container = new Container(registry);
var createPersonCommandHandler = container.GetInstance<IHandler<CreatePersonCommand>>();
createPersonCommandHandler.Handle(new CreatePersonCommand());
var getPersonQueryHandler = container.GetInstance<IHandler<GetPersonQuery, GetPersonReadModel>>();
var person = getPersonQueryHandler.Handle(new GetPersonQuery());
Console.WriteLine($"Hello {person.Name} !");
Console.ReadKey();
}
}
}
```
Switch direct handling by a syncrhonous dispatching in console sample | ```c#
using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
var registry = new Registry();
registry.IncludeRegistry<InfrastructureRegistry>();
var container = new Container(registry);
var dispatcher = container.GetInstance<IDispatcher>();
dispatcher.Dispatch(new CreatePersonCommand());
var person = dispatcher.Dispatch<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery());
Console.WriteLine($"Hello {person.Name} !");
Console.ReadKey();
}
}
}
``` |
0250290b-6c1f-4894-b3e5-3f6bd7773c2e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Alogs
{
public static class GiftExtensions
{
public static double DistanceTo(this Gift one, Gift two)
{
var phyOne = one.Latitude / 360 * Math.PI * 2;
//var phyTwo
return 0;
}
private static double ToRadiant(double degrees)
{
return degrees / 360 * Math.PI * 2;
}
}
}
```
Create algo to calculate distance between gift points | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Alogs
{
public static class GiftExtensions
{
public static double DistanceTo(this Gift one, Gift two)
{
const double radius = 6371000;
var phyOne = ToRadiant(one.Latitude);
var phyTwo = ToRadiant(two.Latitude);
var lambdaOne = ToRadiant(one.Longitude);
var lambdaTwo = ToRadiant(two.Longitude);
var underRoot =
PowTwo(Math.Sin((phyTwo - phyOne)/2))
+ Math.Cos(phyOne)
* Math.Cos(phyTwo)
* PowTwo(Math.Sin((lambdaTwo - lambdaOne)/2));
var arg = Math.Sqrt(underRoot);
return
2
* radius
* Math.Asin(arg);
}
private static double PowTwo(double input)
{
return Math.Pow(input, 2);
}
private static double ToRadiant(double degrees)
{
return degrees / 360 * Math.PI * 2;
}
}
}
``` |
43e703ac-ef9c-4a59-89db-c4d44d4c6024 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
public GlimpseMiddleware(RequestDelegate innerNext)
{
_innerNext = innerNext;
}
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context);
await _innerNext(context);
}
}
}```
Add agent to the web middleware | ```c#
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;
using Glimpse.Agent.Web;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
private readonly WebAgentRuntime _runtime;
public GlimpseMiddleware(RequestDelegate innerNext)
{
_innerNext = innerNext;
_runtime = new WebAgentRuntime(); // TODO: This shouldn't have this direct depedency
}
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context);
_runtime.Begin(newContext);
await _innerNext(context);
_runtime.End(newContext);
}
}
}``` |
f3d594a7-28a1-4d01-89e5-c04f7405bba9 | {
"language": "C#"
} | ```c#
// ReSharper disable once CheckNamespace
namespace IdParser
{
public enum Version : byte
{
PreStandard = 0,
Aamva2000 = 1,
Aamva2003 = 2,
Aamva2005 = 3,
Aamva2009 = 4,
Aamva2010 = 5,
Aamva2011 = 6,
Aamva2012 = 7,
Aamva2013 = 8,
Aamva2016 = 9,
Future = 99
}
}```
Add 2020 standard to version enum | ```c#
// ReSharper disable once CheckNamespace
namespace IdParser
{
public enum Version : byte
{
PreStandard = 0,
Aamva2000 = 1,
Aamva2003 = 2,
Aamva2005 = 3,
Aamva2009 = 4,
Aamva2010 = 5,
Aamva2011 = 6,
Aamva2012 = 7,
Aamva2013 = 8,
Aamva2016 = 9,
Aamva2020 = 10,
Future = 99
}
}``` |
dd0769f5-bb36-4495-b11e-00617f3c28a9 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public class ExpandingToolboxContainer : ExpandingContainer
{
protected override double HoverExpansionDelay => 250;
public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
: base(contractedWidth, expandedWidth)
{
RelativeSizeAxes = Axes.Y;
FillFlow.Spacing = new Vector2(10);
}
protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);
private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);
protected override bool OnMouseDown(MouseDownEvent e) => true;
protected override bool OnClick(ClickEvent e) => true;
}
}
```
Adjust paddings to feel better now that backgrounds are visible of toolboxes | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public class ExpandingToolboxContainer : ExpandingContainer
{
protected override double HoverExpansionDelay => 250;
public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
: base(contractedWidth, expandedWidth)
{
RelativeSizeAxes = Axes.Y;
FillFlow.Spacing = new Vector2(5);
Padding = new MarginPadding { Vertical = 5 };
}
protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);
private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);
protected override bool OnMouseDown(MouseDownEvent e) => true;
protected override bool OnClick(ClickEvent e) => true;
}
}
``` |
15881ee6-28e0-469d-addf-64c96ebd9d6d | {
"language": "C#"
} | ```c#
using System.IO;
namespace AWTY.Http.IntegrationTests
{
/// <summary>
/// A non-optimised version of <see cref="MemoryStream"/> for use in tests.
/// </summary>
/// <remarks>
/// <see cref="MemoryStream"/> performs a bunch of optimisations unless subclassed.
///
/// Unfortunately, these optimisations break the tests.
/// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
/// </remarks>
public sealed class DumbMemoryStream
: MemoryStream
{
public DumbMemoryStream()
: base()
{
}
}
}```
Add link to MemoryStream.CopyToAsync source link. | ```c#
using System.IO;
namespace AWTY.Http.IntegrationTests
{
/// <summary>
/// A non-optimised version of <see cref="MemoryStream"/> for use in tests.
/// </summary>
/// <remarks>
/// <see cref="MemoryStream"/>'s CopyToAsync performs a bunch of optimisations unless subclassed.
/// https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/memorystream.cs#L450
///
/// Unfortunately, these optimisations break some of our tests.
/// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
/// </remarks>
public sealed class DumbMemoryStream
: MemoryStream
{
public DumbMemoryStream()
: base()
{
}
}
}``` |
b381a282-7e2b-47c0-a220-653d424e52b9 | {
"language": "C#"
} | ```c#
// -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// The GitReview application.
/// </summary>
public class GitReviewApplication : HttpApplication
{
/// <summary>
/// Gets the path of the shared repository.
/// </summary>
public static string RepositoryPath
{
get { return ConfigurationManager.AppSettings["RepositoryPath"]; }
}
/// <summary>
/// Starts the application.
/// </summary>
protected virtual void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
Initialize git repo on startup. | ```c#
// -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using LibGit2Sharp;
/// <summary>
/// The GitReview application.
/// </summary>
public class GitReviewApplication : HttpApplication
{
/// <summary>
/// Gets the path of the shared repository.
/// </summary>
public static string RepositoryPath
{
get { return HostingEnvironment.MapPath(ConfigurationManager.AppSettings["RepositoryPath"]); }
}
/// <summary>
/// Starts the application.
/// </summary>
protected virtual void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
var path = GitReviewApplication.RepositoryPath;
if (!Directory.Exists(path))
{
Repository.Init(path, isBare: true);
}
}
}
}
``` |
14c7decc-c90e-46f0-8640-4f02871ee6ab | {
"language": "C#"
} | ```c#
@using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>
<div class="tab-pane active" id="Transactions">
<table id="table-Transactions">
<thead>
<tr>
<th></th>
<th>Transaction</th>
<th>Quantity</th>
<th>Amount</th>
<th>Payment Type</th>
<th>Paid</th>
<th>Active Eh</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Where(a => a.ParentTransaction == null))
{
<tr>
<td>
@using (Html.BeginForm<ItemManagementController>
(x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
{
@Html.AntiForgeryToken()
<a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a>
}
</td>
<td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td>
<td>@Html.DisplayFor(modelItem => item.Quantity)</td>
<td>@Html.DisplayFor(modelItem => item.Amount)</td>
<td>@Html.DisplayFor(modelItem => item.Credit)</td>
<td>@Html.DisplayFor(modelItem => item.Paid)</td>
<td>@Html.DisplayFor(modelItem => item.IsActive)</td>
</tr>
}
</tbody>
</table>
</div>
```
Remove Canadian Styling of bool | ```c#
@using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>
<div class="tab-pane active" id="Transactions">
<table id="table-Transactions">
<thead>
<tr>
<th></th>
<th>Transaction</th>
<th>Quantity</th>
<th>Amount</th>
<th>Payment Type</th>
<th>Paid</th>
<th>Active</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Where(a => a.ParentTransaction == null))
{
<tr>
<td>
@using (Html.BeginForm<ItemManagementController>
(x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
{
@Html.AntiForgeryToken()
<a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a>
}
</td>
<td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td>
<td>@Html.DisplayFor(modelItem => item.Quantity)</td>
<td>@Html.DisplayFor(modelItem => item.Amount)</td>
<td>@Html.DisplayFor(modelItem => item.Credit)</td>
<td>@Html.DisplayFor(modelItem => item.Paid)</td>
<td>@Html.DisplayFor(modelItem => item.IsActive)</td>
</tr>
}
</tbody>
</table>
</div>
``` |
31d480a2-a28e-4ec1-a8e9-05af7183403d | {
"language": "C#"
} | ```c#
using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class UserConstructorTests
{
[Test]
public void Constructor_Should_InitializeUserCorrectly()
{
var user = new User();
Assert.IsNotNull(user);
}
[Test]
public void Constructor_Should_BeInstanceOfIdentityUser()
{
var user = new User();
Assert.IsInstanceOf<IdentityUser>(user);
}
}
}
```
Add new user constructor tests | ```c#
using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class UserConstructorTests
{
[Test]
public void Constructor_Should_InitializeUserCorrectly()
{
var user = new User();
Assert.IsNotNull(user);
}
[Test]
public void Constructor_Should_BeInstanceOfIdentityUser()
{
var user = new User();
Assert.IsInstanceOf<IdentityUser>(user);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetUsernameCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(username, user.UserName);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetNameCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(name, user.Name);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSeEmailCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(email, user.Email);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetPhoneNumberCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(phoneNumber, user.PhoneNumber);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetAddressCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(address, user.Address);
}
}
}
``` |
95601084-50ff-46df-95f4-50e59c96748a | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.MessageBus.Handlers
{
using System;
using Its.Configuration;
using Naos.Database.MessageBus.Contract;
using Naos.Database.Tools;
using Naos.Database.Tools.Backup;
using Naos.MessageBus.HandlingContract;
/// <summary>
/// Naos.MessageBus handler for BackupMessages.
/// </summary>
public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
{
/// <inheritdoc />
public void Handle(BackupDatabaseMessage message)
{
Action<string> logAction = s => { };
var settings = Settings.Get<MessageHandlerSettings>();
var backupDetails = new BackupDetails()
{
Name = message.BackupName,
BackupTo = new Uri(settings.BackupDirectory),
ChecksumOption = ChecksumOption.Checksum,
Cipher = Cipher.NoEncryption,
CompressionOption = CompressionOption.NoCompression,
Description = message.Description,
Device = Device.Disk,
ErrorHandling = ErrorHandling.StopOnError,
};
DatabaseManager.BackupFull(
settings.LocalhostConnectionString,
message.DatabaseName,
backupDetails,
settings.DefaultTimeout,
logAction);
}
}
}
```
Fix issue where the file name wasn't getting specified. | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.MessageBus.Handlers
{
using System;
using System.IO;
using Its.Configuration;
using Naos.Database.MessageBus.Contract;
using Naos.Database.Tools;
using Naos.Database.Tools.Backup;
using Naos.MessageBus.HandlingContract;
/// <summary>
/// Naos.MessageBus handler for BackupMessages.
/// </summary>
public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
{
/// <inheritdoc />
public void Handle(BackupDatabaseMessage message)
{
Action<string> logAction = s => { };
var settings = Settings.Get<MessageHandlerSettings>();
var backupFileName = Path.Combine(settings.BackupDirectory, message.BackupName) + ".bak";
var backupDetails = new BackupDetails()
{
Name = message.BackupName,
BackupTo = new Uri(backupFileName),
ChecksumOption = ChecksumOption.Checksum,
Cipher = Cipher.NoEncryption,
CompressionOption = CompressionOption.NoCompression,
Description = message.Description,
Device = Device.Disk,
ErrorHandling = ErrorHandling.StopOnError,
};
DatabaseManager.BackupFull(
settings.LocalhostConnectionString,
message.DatabaseName,
backupDetails,
settings.DefaultTimeout,
logAction);
}
}
}
``` |
bd02ee2d-33fb-4f7e-b101-3dcd8a7547b8 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
namespace PlayerRank
{
public class PlayerScore
{
public string Name { get; set; }
public Points Points { get; internal set; }
public PlayerScore(string name)
{
Name = name;
Points = new Points(0);
}
internal void AddPoints(Points points)
{
Points += points;
}
/// Obsolete V1 API
[Obsolete("Please use Points instead")]
public double Score
{
get { return Points.GetValue(); }
internal set { Points = new Points(value); }
}
}
}```
Add method to subtract points from player | ```c#
using System;
using System.Runtime.InteropServices;
namespace PlayerRank
{
public class PlayerScore
{
public string Name { get; set; }
public Points Points { get; internal set; }
public PlayerScore(string name)
{
Name = name;
Points = new Points(0);
}
internal void AddPoints(Points points)
{
Points += points;
}
internal void SubtractPoints(Points points)
{
Points -= points;
}
/// Obsolete V1 API
[Obsolete("Please use Points instead")]
public double Score
{
get { return Points.GetValue(); }
internal set { Points = new Points(value); }
}
}
}``` |
edd685d6-0fcd-436c-a8fb-55c62b57a308 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Media.Capture;
namespace ZXing.Net.Mobile
{
public class NotSupported
{
// Windows Phone 8.1 Native and Windows 8 RT are not supported
// Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code
// Which is what ZXing.Net.Mobile needs to work
// You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead!
}
}
namespace ZXing.Mobile
{
public class MobileBarcodeScanner : MobileBarcodeScannerBase
{
NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!");
public override Task<Result> Scan(MobileBarcodeScanningOptions options)
{
throw ex;
}
public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
{
throw ex;
}
public override void Cancel()
{
throw ex;
}
public override void AutoFocus()
{
throw ex;
}
public override void Torch(bool on)
{
throw ex;
}
public override void ToggleTorch()
{
throw ex;
}
public override bool IsTorchOn
{
get
{
throw ex;
}
}
}
}
```
Fix PCL contract for Pause/Resume analysis change | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Media.Capture;
namespace ZXing.Net.Mobile
{
public class NotSupported
{
// Windows Phone 8.1 Native and Windows 8 RT are not supported
// Microsoft left out the ability to (easily) marshal Camera Preview frames to managed code
// Which is what ZXing.Net.Mobile needs to work
// You should upgrade your wpa81 / win8 projects to use Windows Universal (UWP) instead!
}
}
namespace ZXing.Mobile
{
public class MobileBarcodeScanner : MobileBarcodeScannerBase
{
NotSupportedException ex = new NotSupportedException("Windows Phone 8.1 Native (wpa81) and Windows 8 Store (win8) are not supported, please use Windows Universal (UWP) instead!");
public override Task<Result> Scan(MobileBarcodeScanningOptions options)
{
throw ex;
}
public override void ScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
{
throw ex;
}
public override void Cancel()
{
throw ex;
}
public override void AutoFocus()
{
throw ex;
}
public override void Torch(bool on)
{
throw ex;
}
public override void ToggleTorch()
{
throw ex;
}
public override void PauseAnalysis()
{
throw ex;
}
public override void ResumeAnalysis()
{
throw ex;
}
public override bool IsTorchOn
{
get
{
throw ex;
}
}
}
}
``` |
84422f02-e7ab-417b-98e7-ca81842b6f3e | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PerfView.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PerfView.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Disable test parallelization for PerfView tests | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PerfView.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PerfView.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
``` |
5ef417f8-a970-4857-bf13-6ee03aa5698c | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace Admo.Utilities
{
public class SoftwareUtils
{
public static string GetChromeVersion()
{
var path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
if (path != null)
return FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion;
return String.Empty;
}
}
}
```
Handle system wide installs of chrome | ```c#
using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace Admo.Utilities
{
public class SoftwareUtils
{
public static string GetChromeVersion()
{
//Handle both system wide and user installs of chrome
var pathLocal = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
var pathMachine = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
if (pathLocal != null)
{
return FileVersionInfo.GetVersionInfo(pathLocal.ToString()).FileVersion;
}
if (pathMachine != null)
{
return FileVersionInfo.GetVersionInfo(pathMachine.ToString()).FileVersion;
}
return String.Empty;
}
}
}
``` |
f25617fd-cbaf-4a3a-8ef4-63fa3388ab2d | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public ExecutionResult Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
using (var fileStream = new FileStream("C:\\output2.dll", FileMode.Truncate))
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return new ExecutionResult { Result = "[Compilation failed]" };
}
compilation.Emit(fileStream);
compiledAssembly = stream.ToArray();
}
using (var sandbox = new Sandbox(compiledAssembly))
{
return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
}
}
}
```
Remove fileStream used for debugging | ```c#
using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public ExecutionResult Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return new ExecutionResult { Result = "[Compilation failed]" };
}
compiledAssembly = stream.ToArray();
}
using (var sandbox = new Sandbox(compiledAssembly))
{
return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
}
}
}
``` |
30a980bb-f18c-4a5d-924a-2d2621b5ab59 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Owin;
namespace JSNLog
{
public static class AppBuilderExtensions
{
public static void UseJSNLog(this IAppBuilder app, string loggerUrlRegex = null)
{
app.Use<JsnlogMiddlewareComponent>(loggerUrlRegex);
}
}
}
```
Remove second parameter, bug not picked up by compiler | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Owin;
namespace JSNLog
{
public static class AppBuilderExtensions
{
public static void UseJSNLog(this IAppBuilder app)
{
app.Use<JsnlogMiddlewareComponent>();
}
}
}
``` |
af9fd89f-11f8-40cc-b8a7-250cc8f8018a | {
"language": "C#"
} | ```c#
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta05")]```
Set nuget package version to 1.0.0 | ```c#
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]``` |
c9ea438d-df9b-474f-980b-e7dc80fe540f | {
"language": "C#"
} | ```c#
@Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")
@if (UserHelper.IsAdmin)
{
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
}```
Load Confirmation plugin in PageBuilder | ```c#
@Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")
@if (UserHelper.IsAdmin)
{
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
}``` |
f7e0db74-3c4b-40e6-a664-df90b25466ce | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTransformUpdate : BenchmarkTest
{
private TestBox target;
public override void SetUp()
{
base.SetUp();
const int transforms_count = 10000;
ManualClock clock;
target = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };
// transform one target member over a long period
target.RotateTo(360, transforms_count * 2);
// transform another over the same period many times
for (int i = 0; i < transforms_count; i++)
target.Delay(i).MoveTo(new Vector2(0.01f), 1f);
clock.CurrentTime = target.LatestTransformEndTime;
target.Clock.ProcessFrame();
}
[Benchmark]
public void UpdateTransformsWithManyPresent()
{
for (int i = 0; i < 10000; i++)
target.UpdateTransforms();
}
private class TestBox : Box
{
public override bool RemoveCompletedTransforms => false;
public new void UpdateTransforms() => base.UpdateTransforms();
}
}
}
```
Add benchmark of updating transforms when none are added | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTransformUpdate : BenchmarkTest
{
private TestBox target;
private TestBox targetNoTransforms;
public override void SetUp()
{
base.SetUp();
const int transforms_count = 10000;
ManualClock clock;
targetNoTransforms = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };
target = new TestBox { Clock = new FramedClock(clock) };
// transform one target member over a long period
target.RotateTo(360, transforms_count * 2);
// transform another over the same period many times
for (int i = 0; i < transforms_count; i++)
target.Delay(i).MoveTo(new Vector2(0.01f), 1f);
clock.CurrentTime = target.LatestTransformEndTime;
target.Clock.ProcessFrame();
}
[Benchmark]
public void UpdateTransformsWithNonePresent()
{
for (int i = 0; i < 10000; i++)
targetNoTransforms.UpdateTransforms();
}
[Benchmark]
public void UpdateTransformsWithManyPresent()
{
for (int i = 0; i < 10000; i++)
target.UpdateTransforms();
}
private class TestBox : Box
{
public override bool RemoveCompletedTransforms => false;
public new void UpdateTransforms() => base.UpdateTransforms();
}
}
}
``` |
3af3e4f0-67ab-4434-910d-efea66e1b6bd | {
"language": "C#"
} | ```c#
using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(object __result)
{
ComputerLookup.PopulateLookups((Computer) __result);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(Computer), nameof(Computer.load))]
internal static void PopulateOnComputerLoad(Computer __result)
{
ComputerLookup.PopulateLookups(__result);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
}```
Fix node lookup not adding saved computers to dict | ```c#
using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[Util.Initialize]
internal static void Initialize()
{
EventManager<SaveComputerLoadedEvent>.AddHandler(PopulateOnComputerLoad);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(object __result)
{
if (__result == null)
return;
ComputerLookup.PopulateLookups((Computer) __result);
}
internal static void PopulateOnComputerLoad(SaveComputerLoadedEvent args)
{
ComputerLookup.PopulateLookups(args.Comp);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
}``` |
053090b4-7628-480b-a119-0b435c3823a8 | {
"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.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Edit.Masks
{
public class HitCircleSelectionMask : SelectionMask
{
public HitCircleSelectionMask(DrawableHitCircle hitCircle)
: base(hitCircle)
{
Origin = Anchor.Centre;
AutoSizeAxes = Axes.Both;
Position = hitCircle.Position;
InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);
hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.Position;
}
}
}
```
Fix hitcircle selections not responding to stacking changes | ```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.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Edit.Masks
{
public class HitCircleSelectionMask : SelectionMask
{
public HitCircleSelectionMask(DrawableHitCircle hitCircle)
: base(hitCircle)
{
Origin = Anchor.Centre;
AutoSizeAxes = Axes.Both;
Position = hitCircle.Position;
InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);
hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.HitObject.StackedPosition;
hitCircle.HitObject.StackHeightChanged += _ => Position = hitCircle.HitObject.StackedPosition;
}
}
}
``` |
8a272903-7ea5-406a-918c-04e22af5032a | {
"language": "C#"
} | ```c#
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace FFImageLoading.Helpers
{
public class MD5Helper : IMD5Helper
{
public string MD5(Stream stream)
{
var hashProvider = new MD5CryptoServiceProvider();
var bytes = hashProvider.ComputeHash(stream);
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
public string MD5(string input)
{
var hashProvider = new MD5CryptoServiceProvider();
var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
}```
Put MD5CryptoServiceProvider into using clause | ```c#
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace FFImageLoading.Helpers
{
public class MD5Helper : IMD5Helper
{
public string MD5(Stream stream)
{
using (var hashProvider = new MD5CryptoServiceProvider())
{
var bytes = hashProvider.ComputeHash(stream);
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
public string MD5(string input)
{
using (var hashProvider = new MD5CryptoServiceProvider())
{
var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
}
}``` |
aff34cb1-70e9-4f31-9b82-f8585136cf50 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
public class Person
{
//---------------------------------------------------------------------------
public int Id { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public List<Status> Status { get; set; }
//---------------------------------------------------------------------------
public Person()
{
Status = new List<Status>();
}
//---------------------------------------------------------------------------
}```
Update code references: extension -> contact | ```c#
using System.Collections.Generic;
public class Person
{
//---------------------------------------------------------------------------
public int Id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public List<Status> Status { get; set; }
//---------------------------------------------------------------------------
public Person()
{
Status = new List<Status>();
}
//---------------------------------------------------------------------------
}``` |
bc951bd4-7611-4c96-850e-69ce74ab603f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
namespace poshring
{
public class CredentialsManager
{
public IEnumerable<Credential> GetCredentials()
{
int count;
IntPtr ptr;
if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var credentials = Enumerable.Range(0, count)
.Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
.Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
return credentials;
}
public void AddPasswordCredential(string targetName, string userName, string password, string comment)
{
using (var credential = new Credential
{
TargetName = targetName,
UserName = userName,
CredentialBlob = password,
Comment = comment
})
{
credential.Save();
}
}
public void DeleteCredential(Credential credential)
{
if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
{
var error = (CredentialErrors)Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not delete credential.");
}
}
}
}```
Return empty result when there are no credentials on the system. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
namespace poshring
{
public class CredentialsManager
{
public IEnumerable<Credential> GetCredentials()
{
int count;
IntPtr ptr;
if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
{
var error = (CredentialErrors) Marshal.GetLastWin32Error();
switch (error)
{
case CredentialErrors.NotFound:
return Enumerable.Empty<Credential>();
case CredentialErrors.NoSuchLogonSession:
case CredentialErrors.InvalidFlags:
throw new Win32Exception((int)error);
default:
throw new InvalidOperationException("Unexpected error while fetching credentials.");
}
}
var credentials = Enumerable.Range(0, count)
.Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
.Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
return credentials;
}
public void AddPasswordCredential(string targetName, string userName, string password, string comment)
{
using (var credential = new Credential
{
TargetName = targetName,
UserName = userName,
CredentialBlob = password,
Comment = comment
})
{
credential.Save();
}
}
public void DeleteCredential(Credential credential)
{
if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
{
var error = (CredentialErrors)Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not delete credential.");
}
}
}
}``` |
f5b83f26-af92-4ff9-93bd-db846498fcba | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Module1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
```
Fix Module1 to run as independent app | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Modules;
namespace Module1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(services =>
{
services.AddSingleton(new ModuleInstanceIdProvider("Module1"));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
``` |
c8defc52-740f-4ef3-bd91-88da51757ecd | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using UrlShortenerApi.Models;
namespace UrlShortenerApi.Repositories
{
public interface IHeaderRepository
{
void Add(Microsoft.AspNetCore.Http.IHeaderDictionary request, int urlID);
void Add(Header item);
}
}
```
Update variable name on Header Repository Interface | ```c#
using System.Collections.Generic;
using UrlShortenerApi.Models;
namespace UrlShortenerApi.Repositories
{
public interface IHeaderRepository
{
void Add(Microsoft.AspNetCore.Http.IHeaderDictionary headers, int urlID);
void Add(Header item);
}
}
``` |
cac9f828-24c1-4674-b875-ce1d0c03b3c4 | {
"language": "C#"
} | ```c#
using Voxalia.ServerGame.WorldSystem;
namespace Voxalia.ServerGame.EntitySystem
{
public abstract class EntityLiving: PhysicsEntity, EntityDamageable
{
public EntityLiving(Region tregion, bool ticks, float maxhealth)
: base(tregion, ticks)
{
MaxHealth = maxhealth;
Health = maxhealth;
}
public float Health = 100;
public float MaxHealth = 100;
public virtual float GetHealth()
{
return Health;
}
public virtual float GetMaxHealth()
{
return MaxHealth;
}
public virtual void SetHealth(float health)
{
Health = health;
if (MaxHealth != 0 && Health <= 0)
{
Die();
}
}
public virtual void Damage(float amount)
{
SetHealth(GetHealth() - amount);
}
public virtual void SetMaxHealth(float maxhealth)
{
MaxHealth = maxhealth;
}
public abstract void Die();
}
}
```
CLean a potential hole in entityliving | ```c#
using System;
using Voxalia.ServerGame.WorldSystem;
namespace Voxalia.ServerGame.EntitySystem
{
public abstract class EntityLiving: PhysicsEntity, EntityDamageable
{
public EntityLiving(Region tregion, bool ticks, float maxhealth)
: base(tregion, ticks)
{
MaxHealth = maxhealth;
Health = maxhealth;
}
public float Health = 100;
public float MaxHealth = 100;
public virtual float GetHealth()
{
return Health;
}
public virtual float GetMaxHealth()
{
return MaxHealth;
}
public virtual void SetHealth(float health)
{
Health = Math.Min(health, MaxHealth);
if (MaxHealth != 0 && Health <= 0)
{
Die();
}
}
public virtual void Damage(float amount)
{
SetHealth(GetHealth() - amount);
}
public virtual void SetMaxHealth(float maxhealth)
{
MaxHealth = maxhealth;
}
public abstract void Die();
}
}
``` |
6edc8a4f-6acb-4496-9cfe-8fa9d5800370 | {
"language": "C#"
} | ```c#
using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;
namespace AppGet.Installers
{
public abstract class InstallerWhispererBase : IInstallerWhisperer
{
private readonly IProcessController _processController;
private readonly Logger _logger;
protected InstallerWhispererBase(IProcessController processController, Logger logger)
{
_processController = processController;
_logger = logger;
}
public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
public abstract bool CanHandle(InstallMethodType installMethod);
protected virtual int Execute(string exectuable, string args)
{
var process = _processController.Start(exectuable, args, OnOutputDataReceived, OnErrorDataReceived);
_processController.WaitForExit(process);
return process.ExitCode;
}
protected virtual void OnOutputDataReceived(string message)
{
_logger.Info(message);
}
protected virtual void OnErrorDataReceived(string message)
{
_logger.Error(message);
}
}
}
```
Throw error if installer returns a non-zero exist code. | ```c#
using System.ComponentModel;
using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Exceptions;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;
namespace AppGet.Installers
{
public abstract class InstallerWhispererBase : IInstallerWhisperer
{
private readonly IProcessController _processController;
private readonly Logger _logger;
protected InstallerWhispererBase(IProcessController processController, Logger logger)
{
_processController = processController;
_logger = logger;
}
public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
public abstract bool CanHandle(InstallMethodType installMethod);
protected virtual void Execute(string executable, string args)
{
try
{
var process = _processController.Start(executable, args, OnOutputDataReceived, OnErrorDataReceived);
_processController.WaitForExit(process);
if (process.ExitCode != 0)
{
throw new AppGetException($"Installer '{process.ProcessName}' returned with a non-zero exit code. code: {process.ExitCode}");
}
}
catch (Win32Exception e)
{
_logger.Error($"{e.Message}, try running AppGet as an administartor");
throw;
}
}
protected virtual void OnOutputDataReceived(string message)
{
_logger.Info(message);
}
protected virtual void OnErrorDataReceived(string message)
{
_logger.Error(message);
}
}
}
``` |
aceee565-8ea8-4bb9-94a5-16baacf639ef | {
"language": "C#"
} | ```c#
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class NetworkManager : MonoBehaviour {
public List<string> ChatMessages;
// Goal #1: Create a reasonable chat system using the NEW UI System
public void AddChatMessage(string message) {
PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
}
[RPC]
private void AddChatMessageRPC(string message) {
// TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
while (ChatMessages.Count >= maxChatMessages) {
ChatMessages.RemoveAt(0);
}
ChatMessages.Add(message);
}
void Start() {
PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
ChatMessages = new List<string>();
Connect();
}
void Update() {
}
void Connect() {
PhotonNetwork.ConnectUsingSettings("FPS Test v001");
}
void OnGUI() {
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}
void OnJoinedLobby() {
Debug.Log("OnJoinedLobby");
PhotonNetwork.JoinRandomRoom();
}
void OnPhotonRandomJoinFailed() {
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null);
}
void OnJoinedRoom() {
Debug.Log("OnJoinedRoom");
AddChatMessage("[SYSTEM] OnJoinedRoom!");
}
const int maxChatMessages = 7;
}
```
Enable offline mode by default. | ```c#
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class NetworkManager : MonoBehaviour {
public List<string> ChatMessages;
public bool IsOfflineMode;
// Goal #1: Create a reasonable chat system using the NEW UI System
public void AddChatMessage(string message) {
PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
}
[RPC]
private void AddChatMessageRPC(string message) {
// TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
while (ChatMessages.Count >= maxChatMessages) {
ChatMessages.RemoveAt(0);
}
ChatMessages.Add(message);
}
void Start() {
PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
ChatMessages = new List<string>();
if (IsOfflineMode) {
PhotonNetwork.offlineMode = true;
OnJoinedLobby();
} else {
Connect();
}
}
void Update() {
}
void Connect() {
PhotonNetwork.ConnectUsingSettings("FPS Test v001");
}
void OnGUI() {
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}
void OnJoinedLobby() {
Debug.Log("OnJoinedLobby");
PhotonNetwork.JoinRandomRoom();
}
void OnPhotonRandomJoinFailed() {
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null);
}
void OnJoinedRoom() {
Debug.Log("OnJoinedRoom");
AddChatMessage("[SYSTEM] OnJoinedRoom!");
}
const int maxChatMessages = 7;
}
``` |
d9c12e74-1958-43ef-bc61-fd82dc17f3a0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerHub.Client.API.Students.Experiences {
public class ExperienceModel {
public int ID { get; set; }
public string Title { get; set; }
public string Organisation { get; set; }
public string Description { get; set; }
public string ContactName { get; set; }
public string ContactEmail { get; set; }
public string ContactPhone { get; set; }
public DateTime StartUtc { get; set; }
public DateTime? EndUtc { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public string Type { get; set; }
public string Hours { get; set; }
}
}
```
Add extra properties to experience model | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerHub.Client.API.Students.Experiences {
public class ExperienceModel {
public int ID { get; set; }
public string Title { get; set; }
public string Organisation { get; set; }
public string Description { get; set; }
public string ContactName { get; set; }
public string ContactEmail { get; set; }
public string ContactPhone { get; set; }
public DateTime StartUtc { get; set; }
public DateTime? EndUtc { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public int? TypeID { get; set; }
public string Type { get; set; }
public int? HoursID { get; set; }
public string Hours { get; set; }
}
}
``` |
45c5bc70-9b75-4a40-accd-2dc1bb474d0b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;
namespace Phoebe.FormClient
{
static class Program
{
/// <summary>
/// 全局操作
/// </summary>
public static GlobalControl GC = new GlobalControl();
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginForm login = new LoginForm();
if (login.ShowDialog() == DialogResult.OK)
{
Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息
Application.Run(new MainForm());
}
}
}
}
```
Add global exception handle, not enable. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;
namespace Phoebe.FormClient
{
static class Program
{
/// <summary>
/// 全局操作
/// </summary>
public static GlobalControl GC = new GlobalControl();
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
LoginForm login = new LoginForm();
if (login.ShowDialog() == DialogResult.OK)
{
Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息
Application.Run(new MainForm());
}
}
/// <summary>
/// 异常消息处理
/// </summary>
/// <param name="sender"></param>
/// <param name="ex"></param>
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
{
string message = string.Format("{0}\r\n操作发生错误,您需要退出系统么?", ex.Exception.Message);
if (MessageUtil.ConfirmYesNo(message) == DialogResult.Yes)
{
Application.Exit();
}
}
}
}
``` |
2d8b514d-e84a-4a62-83a4-89329f7b4085 | {
"language": "C#"
} | ```c#
using UnityEngine;
public class RollFudgeDie : RollSpecialDie
{
public override string Examine(Vector3 worldPos = default)
{
return $"It is showing side {GetFudgeMessage()}";
}
protected override string GetMessage()
{
return $"The {dieName} lands a {GetFudgeMessage()}";
}
private string GetFudgeMessage()
{
if (result == 2)
{
return specialFaces[1].ToString();
}
return $"{specialFaces[result - 1]}.";
}
}
```
Clarify FudgeDie special case's formatting | ```c#
using UnityEngine;
public class RollFudgeDie : RollSpecialDie
{
public override string Examine(Vector3 worldPos = default)
{
return $"It is showing {GetFudgeMessage()}";
}
protected override string GetMessage()
{
return $"The {dieName} lands {GetFudgeMessage()}";
}
private string GetFudgeMessage()
{
// Result 2 is a strange side, we modify the formatting such that it reads "a... what?".
if (result == 2)
{
return $"a{specialFaces[1]}";
}
return $"a {specialFaces[result - 1]}.";
}
}
``` |
d6b3a59a-f575-4a67-b9db-f423d0160fb0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
allFiles = allFiles.Concat(GetFiles(current, pattern));
foreach (var subdirectory in GetSubdirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
}
return allFiles;
}
private IEnumerable<string> GetFiles(string path, string pattern)
{
try
{
return Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
private IEnumerable<string> GetSubdirectories(string path)
{
try
{
return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
}
}
```
Simplify file enumeration and correctly handle path too long exceptions when enumerating sub directories | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
var files = Directory.GetFiles(current, pattern);
allFiles = allFiles.Concat(files);
foreach (var subdirectory in Directory.EnumerateDirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", current));
}
}
return allFiles;
}
}
}
``` |
bf702d7c-10a9-46af-bc9b-fb547eef76f1 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;
namespace MonoHaven
{
public class Audio : IDisposable
{
private readonly AudioContext context;
private readonly OggStreamer streamer;
public Audio()
{
context = new AudioContext();
streamer = new OggStreamer();
}
public void Play(Delayed<Resource> res)
{
if (res.Value == null)
return;
var audio = res.Value.GetLayer<AudioData>();
var ms = new MemoryStream(audio.Bytes);
var oggStream = new OggStream(ms);
oggStream.Play();
}
public void Dispose()
{
if (streamer != null)
streamer.Dispose();
if (context != null)
context.Dispose();
}
}
}
```
Use separate task to queue sound effects so they can be played when they're loaded | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;
namespace MonoHaven
{
public class Audio : IDisposable
{
private readonly AudioContext context;
private readonly OggStreamer streamer;
private readonly AudioPlayer player;
public Audio()
{
context = new AudioContext();
streamer = new OggStreamer();
player = new AudioPlayer();
player.Run();
}
public void Play(Delayed<Resource> res)
{
player.Queue(res);
}
public void Dispose()
{
player.Stop();
if (streamer != null)
streamer.Dispose();
if (context != null)
context.Dispose();
}
private class AudioPlayer : BackgroundTask
{
private readonly Queue<Delayed<Resource>> queue;
public AudioPlayer() : base("Audio Player")
{
queue = new Queue<Delayed<Resource>>();
}
protected override void OnStart()
{
while (!IsCancelled)
{
lock (queue)
{
var item = queue.Count > 0 ? queue.Peek() : null;
if (item != null && item.Value != null)
{
queue.Dequeue();
var audio = item.Value.GetLayer<AudioData>();
if (audio != null)
{
var ms = new MemoryStream(audio.Bytes);
var oggStream = new OggStream(ms);
oggStream.Play();
}
}
Monitor.Wait(queue, TimeSpan.FromMilliseconds(100));
}
}
}
public void Queue(Delayed<Resource> res)
{
lock (queue)
{
queue.Enqueue(res);
Monitor.PulseAll(queue);
}
}
}
}
}
``` |
a0498b87-51ee-4cda-a872-d101f68e59d5 | {
"language": "C#"
} | ```c#
using System;
namespace Braintree
{
public class VenmoAccount : PaymentMethod
{
public string Token { get; protected set; }
public string Username { get; protected set; }
public string VenmoUserId { get; protected set; }
public string SourceDescription { get; protected set; }
public string ImageUrl { get; protected set; }
public bool? IsDefault { get; protected set; }
public string CustomerId { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Subscription[] Subscriptions { get; protected set; }
protected internal VenmoAccount(NodeWrapper node, BraintreeGateway gateway)
{
Token = node.GetString("token");
Username = node.GetString("username");
VenmoUserId = node.GetString("venmo-user-id");
SourceDescription = node.GetString("source-description");
ImageUrl = node.GetString("image-url");
IsDefault = node.GetBoolean("default");
CustomerId = node.GetString("customer-id");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
}
}
}
}
```
Add mock changes to new Venmo class | ```c#
using System;
namespace Braintree
{
public class VenmoAccount : PaymentMethod
{
public string Token { get; protected set; }
public string Username { get; protected set; }
public string VenmoUserId { get; protected set; }
public string SourceDescription { get; protected set; }
public string ImageUrl { get; protected set; }
public bool? IsDefault { get; protected set; }
public string CustomerId { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Subscription[] Subscriptions { get; protected set; }
protected internal VenmoAccount(NodeWrapper node, IBraintreeGateway gateway)
{
Token = node.GetString("token");
Username = node.GetString("username");
VenmoUserId = node.GetString("venmo-user-id");
SourceDescription = node.GetString("source-description");
ImageUrl = node.GetString("image-url");
IsDefault = node.GetBoolean("default");
CustomerId = node.GetString("customer-id");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
}
}
[Obsolete("Mock Use Only")]
protected internal VenmoAccount() { }
}
}
``` |
ee061521-e4ab-4d65-a782-4c5a213b5965 | {
"language": "C#"
} | ```c#
namespace ChessDotNet
{
public enum Event
{
Check,
Checkmate,
Stalemate,
Draw,
Custom,
Resign,
VariantEnd, // to be used for chess variants, which can be derived from ChessGame
None
}
public class GameStatus
{
public Event Event
{
get;
private set;
}
public Player PlayerWhoCausedEvent
{
get;
private set;
}
public string EventExplanation
{
get;
private set;
}
public GameStatus(Event _event, Player whoCausedEvent, string eventExplanation)
{
Event = _event;
PlayerWhoCausedEvent = whoCausedEvent;
EventExplanation = eventExplanation;
}
}
}
```
Remove underscore from parameter name | ```c#
namespace ChessDotNet
{
public enum Event
{
Check,
Checkmate,
Stalemate,
Draw,
Custom,
Resign,
VariantEnd, // to be used for chess variants, which can be derived from ChessGame
None
}
public class GameStatus
{
public Event Event
{
get;
private set;
}
public Player PlayerWhoCausedEvent
{
get;
private set;
}
public string EventExplanation
{
get;
private set;
}
public GameStatus(Event @event, Player whoCausedEvent, string eventExplanation)
{
Event = @event;
PlayerWhoCausedEvent = whoCausedEvent;
EventExplanation = eventExplanation;
}
}
}
``` |
6ca1ac9a-3839-4972-b358-e74d8d138c64 | {
"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.Logging;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Game.IO
{
public class OsuStorage : WrappedStorage
{
public OsuStorage(GameHost host)
: base(host.Storage, string.Empty)
{
var storageConfig = new StorageConfigManager(host.Storage);
var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);
if (!string.IsNullOrEmpty(customStoragePath))
{
ChangeTargetStorage(host.GetStorage(customStoragePath));
Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
}
}
}
}
```
Add basic blocking migration, move not copy | ```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 System.IO;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Game.IO
{
public class OsuStorage : WrappedStorage
{
private readonly GameHost host;
private readonly StorageConfigManager storageConfig;
public OsuStorage(GameHost host)
: base(host.Storage, string.Empty)
{
this.host = host;
storageConfig = new StorageConfigManager(host.Storage);
var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);
if (!string.IsNullOrEmpty(customStoragePath))
{
ChangeTargetStorage(host.GetStorage(customStoragePath));
Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
}
}
public void Migrate(string newLocation)
{
string oldLocation = GetFullPath(".");
// ensure the new location has no files present, else hard abort
if (Directory.Exists(newLocation))
{
if (Directory.GetFiles(newLocation).Length > 0)
throw new InvalidOperationException("Migration destination already has files present");
Directory.Delete(newLocation, true);
}
Directory.Move(oldLocation, newLocation);
Directory.CreateDirectory(newLocation);
// temporary
Directory.CreateDirectory(oldLocation);
// move back exceptions for now
Directory.Move(Path.Combine(newLocation, "cache"), Path.Combine(oldLocation, "cache"));
File.Move(Path.Combine(newLocation, "framework.ini"), Path.Combine(oldLocation, "framework.ini"));
ChangeTargetStorage(host.GetStorage(newLocation));
storageConfig.Set(StorageConfig.FullPath, newLocation);
storageConfig.Save();
}
}
}
``` |
98d043f3-c821-4784-8f23-ba73f02c38b5 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneParticleExplosion : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
AddStep(@"display", () =>
{
Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200)
};
});
}
}
}
```
Make test run multiple times | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneParticleExplosion : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
AddRepeatStep(@"display", () =>
{
Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(400)
};
}, 10);
}
}
}
``` |
d78b0cb3-a0d1-4699-a0ba-a7e96a7db5a7 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.IO.Pipelines
{
public class DuplexPipe : IDuplexPipe
{
public DuplexPipe(PipeReader reader, PipeWriter writer)
{
Input = reader;
Output = writer;
}
public PipeReader Input { get; }
public PipeWriter Output { get; }
public void Dispose()
{
}
public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions)
{
var input = new Pipe(inputOptions);
var output = new Pipe(outputOptions);
var transportToApplication = new DuplexPipe(output.Reader, input.Writer);
var applicationToTransport = new DuplexPipe(input.Reader, output.Writer);
return new DuplexPipePair(applicationToTransport, transportToApplication);
}
// This class exists to work around issues with value tuple on .NET Framework
public struct DuplexPipePair
{
public IDuplexPipe Transport { get; private set; }
public IDuplexPipe Application { get; private set; }
public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application)
{
Transport = transport;
Application = application;
}
}
}
}
```
Change namespace to avoid conflict | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO.Pipelines;
namespace Microsoft.AspNetCore.Sockets
{
public class DuplexPipe : IDuplexPipe
{
public DuplexPipe(PipeReader reader, PipeWriter writer)
{
Input = reader;
Output = writer;
}
public PipeReader Input { get; }
public PipeWriter Output { get; }
public void Dispose()
{
}
public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions)
{
var input = new Pipe(inputOptions);
var output = new Pipe(outputOptions);
var transportToApplication = new DuplexPipe(output.Reader, input.Writer);
var applicationToTransport = new DuplexPipe(input.Reader, output.Writer);
return new DuplexPipePair(applicationToTransport, transportToApplication);
}
// This class exists to work around issues with value tuple on .NET Framework
public struct DuplexPipePair
{
public IDuplexPipe Transport { get; private set; }
public IDuplexPipe Application { get; private set; }
public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application)
{
Transport = transport;
Application = application;
}
}
}
}
``` |
69fa186a-3291-4ed7-b112-e300a8b602e1 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using HandlebarsDotNet.MemberAccessors;
using HandlebarsDotNet.ObjectDescriptors;
using HandlebarsDotNet.PathStructure;
namespace HandlebarsDotNet
{
public readonly ref struct ObjectAccessor
{
private readonly object _data;
private readonly ObjectDescriptor _descriptor;
private readonly IMemberAccessor _memberAccessor;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ObjectAccessor(object data, ObjectDescriptor descriptor)
{
_data = data;
_descriptor = descriptor;
_memberAccessor = _descriptor.MemberAccessor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ObjectAccessor(object data)
{
_data = data;
if (data == null || !ObjectDescriptorFactory.Current.TryGetDescriptor(data.GetType(), out _descriptor))
{
_descriptor = ObjectDescriptor.Empty;
_memberAccessor = null;
}
else
{
_memberAccessor = _descriptor.MemberAccessor;
}
}
public IEnumerable<ChainSegment> Properties => _descriptor
.GetProperties(_descriptor, _data)
.OfType<object>()
.Select(ChainSegment.Create);
public object this[ChainSegment segment] =>
_memberAccessor != null && _memberAccessor.TryGetValue(_data, segment, out var value)
? value
: null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetValue(ChainSegment segment, out object value) =>
_memberAccessor.TryGetValue(_data, segment, out value);
}
}```
Fix `NullReferenceException` when `IMemberAccessor` was not resolved Related to Handlebars-Net/Handlebars.Net/issues/399 | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using HandlebarsDotNet.MemberAccessors;
using HandlebarsDotNet.ObjectDescriptors;
using HandlebarsDotNet.PathStructure;
namespace HandlebarsDotNet
{
public readonly ref struct ObjectAccessor
{
private readonly object _data;
private readonly ObjectDescriptor _descriptor;
private readonly IMemberAccessor _memberAccessor;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ObjectAccessor(object data, ObjectDescriptor descriptor)
{
_data = data;
_descriptor = descriptor;
_memberAccessor = _descriptor.MemberAccessor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ObjectAccessor(object data)
{
_data = data;
if (data == null || !ObjectDescriptorFactory.Current.TryGetDescriptor(data.GetType(), out _descriptor))
{
_descriptor = ObjectDescriptor.Empty;
_memberAccessor = null;
}
else
{
_memberAccessor = _descriptor.MemberAccessor;
}
}
public IEnumerable<ChainSegment> Properties => _descriptor
.GetProperties(_descriptor, _data)
.OfType<object>()
.Select(ChainSegment.Create);
public object this[ChainSegment segment] =>
_memberAccessor != null && _memberAccessor.TryGetValue(_data, segment, out var value)
? value
: null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetValue(ChainSegment segment, out object value)
{
if (_memberAccessor == null)
{
value = null;
return false;
}
return _memberAccessor.TryGetValue(_data, segment, out value);
}
}
}``` |
0840df65-84f2-43d1-bc5c-3ef78b0d9516 | {
"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.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
if (judgement != null)
{
switch (judgement.Result)
{
case HitResult.Hit:
Combo.Value++;
Health.Value += 0.1f;
break;
case HitResult.Miss:
Combo.Value = 0;
Health.Value -= 0.2f;
break;
}
}
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
```
Fix osu! mode adding combos twice. | ```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.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
``` |
9e9ef3f5-4eb6-4df8-b06b-d089970c5035 | {
"language": "C#"
} | ```c#
using System.IO;
using EnvDTE;
namespace NuGet.VisualStudio
{
/// <summary>
/// This project system represents the JavaScript Metro project in Windows8
/// </summary>
public class JsProjectSystem : VsProjectSystem
{
public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) :
base(project, fileSystemProvider)
{
}
public override string ProjectName
{
get
{
return Project.GetName();
}
}
public override void AddFile(string path, Stream stream)
{
Project.GetProjectItems(path, createIfNotExists: true);
base.AddFile(path, stream);
}
protected override void AddFileToContainer(string fullPath, ProjectItems container)
{
container.AddFromFile(fullPath);
}
}
}```
Fix bug not able to install packages to JS Metro project. Work items: 1986 | ```c#
using System.IO;
using EnvDTE;
namespace NuGet.VisualStudio
{
/// <summary>
/// This project system represents the JavaScript Metro project in Windows8
/// </summary>
public class JsProjectSystem : VsProjectSystem
{
public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) :
base(project, fileSystemProvider)
{
}
public override string ProjectName
{
get
{
return Project.GetName();
}
}
public override void AddFile(string path, Stream stream)
{
// ensure the parent folder is created before adding file to the project
Project.GetProjectItems(Path.GetDirectoryName(path), createIfNotExists: true);
base.AddFile(path, stream);
}
protected override void AddFileToContainer(string fullPath, ProjectItems container)
{
container.AddFromFile(fullPath);
}
}
}``` |
dbcc2879-1f0b-4b37-ab9c-ba18c079f35d | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel
{
public class Body
{
[XmlAttribute("bookcreationtype")]
public string BookCreationType;
[XmlAttribute("class")]
public string Class;
[XmlElement("div")]
public List<Div> Divs;
}
}```
Make published books "motion book"s | ```c#
using System.Collections.Generic;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel
{
public class Body
{
// REVIEW: I don't think these two are necessary/useful
[XmlAttribute("bookcreationtype")]
public string BookCreationType;
[XmlAttribute("class")]
public string Class;
// Features used to make this a "motion book"
[XmlAttribute("data-bfautoadvance")]
public string BloomFeature_AutoAdvance = "landscape;bloomReader";
[XmlAttribute("data-bfcanrotate")]
public string BloomFeature_CanRotate = "allOrientations;bloomReader";
[XmlAttribute("data-bfplayanimations")]
public string BloomFeature_PlayAnimations = "landscape;bloomReader";
[XmlAttribute("data-bfplaymusic")]
public string BloomFeature_PlayMusic = "landscape;bloomReader";
[XmlAttribute("data-bfplaynarration")]
public string BloomFeature_PlayNarration = "landscape;bloomReader";
[XmlAttribute("data-bffullscreenpicture")]
public string BloomFeature_FullScreenPicture = "landscape;bloomReader";
[XmlElement("div")]
public List<Div> Divs;
}
}
``` |
7b97892f-50fd-4284-a674-ef040eba2e4e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Rainbow.Model;
using Sitecore.Data;
namespace Rainbow.Formatting.FieldFormatters
{
public class MultilistFormatter : FieldTypeBasedFormatter
{
public override string[] SupportedFieldTypes
{
get
{
return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx" };
}
}
public override string Format(IItemFieldValue field)
{
var values = ID.ParseArray(field.Value);
if (values.Length == 0 && field.Value.Length > 0)
return field.Value;
return string.Join(Environment.NewLine, (IEnumerable<ID>)values);
}
public override string Unformat(string value)
{
if (value == null) return null;
return value.Trim().Replace(Environment.NewLine, "|");
}
}
}
```
Add deprecated 'tree list' type to formatter, because that's what __base templates still is :) | ```c#
using System;
using System.Collections.Generic;
using Rainbow.Model;
using Sitecore.Data;
namespace Rainbow.Formatting.FieldFormatters
{
public class MultilistFormatter : FieldTypeBasedFormatter
{
public override string[] SupportedFieldTypes
{
get
{
return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx", "tree list" };
}
}
public override string Format(IItemFieldValue field)
{
var values = ID.ParseArray(field.Value);
if (values.Length == 0 && field.Value.Length > 0)
return field.Value;
return string.Join(Environment.NewLine, (IEnumerable<ID>)values);
}
public override string Unformat(string value)
{
if (value == null) return null;
return value.Trim().Replace(Environment.NewLine, "|");
}
}
}
``` |
7fe42017-584f-4604-8178-d01be46ae09d | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8000/HelloIndigo/HelloIndigoService");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(), endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
```
Correct test client endpoint address. It worked! | ```c#
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8733/Design_Time_Addresses/Host/HelloIndigoService");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(), endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
``` |
7dd329fb-74e8-428f-82ae-7d3ec8145683 | {
"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.Game.Graphics.UserInterface;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value);
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
Text.Font = Text.Font.With(size: 14);
Chevron.Y = 3;
}
}
}
}
```
Remove underline from breadcrumb 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 osu.Game.Graphics.UserInterface;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value);
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
Text.Font = Text.Font.With(size: 14);
Chevron.Y = 3;
Bar.Height = 0;
}
}
}
}
``` |
fb3d0fe7-e625-4008-86b2-5d085f9f599c | {
"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.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Screens.Select.Options;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null);
overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, Color4.Pink, null);
overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
```
Fix button colors in beatmap options test | ```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.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Options;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
var colours = new OsuColour();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, null);
overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, null);
overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, colours.Yellow, null);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
``` |
e6116485-1e15-46e7-97c8-953b2c0daf00 | {
"language": "C#"
} | ```c#
namespace SqlStreamStore
{
using System.Threading;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Streams;
using Xunit;
public class MigrationTests
{
[Fact]
public async Task Can_migrate()
{
// Set up an old schema + data.
var schema = "baz";
var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false);
var v2Store = await v2Fixture.GetMsSqlStreamStore();
await v2Store.AppendToStream("stream-1",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.AppendToStream("stream-2",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20);
v2Store.Dispose();
v2Fixture.Dispose();
// Migrate with V3 schema.
var v3Fixture = new MsSqlStreamStoreV3Fixture(schema, databaseNameOverride: v2Fixture.DatabaseName);
var v3Store = await v3Fixture.GetMsSqlStreamStore();
var checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeFalse();
await v3Store.Migrate(CancellationToken.None);
checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeTrue();
v3Store.Dispose();
v3Fixture.Dispose();
}
}
}```
Fix migration test - use correct database from v2 fixture. | ```c#
namespace SqlStreamStore
{
using System.Threading;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Streams;
using Xunit;
public class MigrationTests
{
[Fact]
public async Task Can_migrate()
{
// Set up an old schema + data.
var schema = "baz";
var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false);
var v2Store = await v2Fixture.GetMsSqlStreamStore();
await v2Store.AppendToStream("stream-1",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.AppendToStream("stream-2",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20);
v2Store.Dispose();
v2Fixture.Dispose();
var settings = new MsSqlStreamStoreV3Settings(v2Fixture.ConnectionString)
{
Schema = schema,
};
var v3Store = new MsSqlStreamStoreV3(settings);
var checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeFalse();
await v3Store.Migrate(CancellationToken.None);
checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeTrue();
v3Store.Dispose();
}
}
}``` |
b57876a5-9d66-4a84-ab4d-2be1961575e1 | {
"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.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Overlays.Mods
{
public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction>
{
public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.SelectAll;
Action = modSelectOverlay.SelectAll;
}
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat || e.Action != PlatformAction.SelectAll)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
}
}
```
Disable "select all mods" button if all are selected | ```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.Linq;
using osu.Framework.Bindables;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Overlays.Mods
{
public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction>
{
private readonly Bindable<IReadOnlyList<Mod>> selectedMods = new Bindable<IReadOnlyList<Mod>>();
private readonly Bindable<Dictionary<ModType, IReadOnlyList<ModState>>> availableMods = new Bindable<Dictionary<ModType, IReadOnlyList<ModState>>>();
public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.SelectAll;
Action = modSelectOverlay.SelectAll;
selectedMods.BindTo(modSelectOverlay.SelectedMods);
availableMods.BindTo(modSelectOverlay.AvailableMods);
}
protected override void LoadComplete()
{
base.LoadComplete();
selectedMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState));
availableMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState));
updateEnabledState();
}
private void updateEnabledState()
{
Enabled.Value = availableMods.Value
.SelectMany(pair => pair.Value)
.Any(modState => !modState.Active.Value && !modState.Filtered.Value);
}
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat || e.Action != PlatformAction.SelectAll)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
}
}
``` |
abec684e-31bd-4536-8d35-8dd7fba4e988 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
public readonly partial struct DateTime
{
public static DateTime UtcNow
{
get
{
// For performance, use a private constructor that does not validate arguments.
return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + TicksTo1970)) | KindUtc);
}
}
}
}
```
Fix build error with mirroring | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
public readonly partial struct DateTime
{
public static DateTime UtcNow
{
get
{
// For performance, use a private constructor that does not validate arguments.
return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + DateTime.UnixEpochTicks)) | KindUtc);
}
}
}
}
``` |
e7aa58f9-2565-4c01-b0a0-fd373c6bde56 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CodeProject - EF Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AREBIS")]
[assembly: AssemblyProduct("CodeProject - EF")]
[assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: System.CLSCompliant(true)]```
Check voor CLS-compliante code verwijderd uit project CodeProject.Data | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CodeProject - EF Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AREBIS")]
[assembly: AssemblyProduct("CodeProject - EF")]
[assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// voorlopig geen CLS-compliante code.
// [assembly: System.CLSCompliant(true)]``` |
ec555afb-424d-48bd-888a-00838709dbb9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
ObservableCollection<TestClass> expected = new ObservableCollection<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
ObservableCollection<TestClass> result = sut.DeserializeCollection<TestClass>(testData);
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
[Fact]
public void ShouldReturnValue()
{
var sut = new JsonService();
string expected = "value";
string testData = "{ \"key\": \"value\" }";
string result = sut.GetValue<string>(testData, "key");
Assert.Equal(expected, result);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
```
Update Json tests to reflect change to IEnumerable | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
List<TestClass> expected = new List<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
List<TestClass> result = sut.DeserializeCollection<TestClass>(testData).ToList();
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
[Fact]
public void ShouldReturnValue()
{
var sut = new JsonService();
string expected = "value";
string testData = "{ \"key\": \"value\" }";
string result = sut.GetValue<string>(testData, "key");
Assert.Equal(expected, result);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
``` |
c12c879f-4767-4f5b-9d21-44d5a2fb0f2a | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w](?<functionName>\w*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
```
Extend character set of function names (including ".") | ```c#
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
``` |
912a1ba3-65bb-43b5-b3e7-930e4682aec2 | {
"language": "C#"
} | ```c#
namespace NuGet.Common
{
public class CommandLineRepositoryFactory : PackageRepositoryFactory
{
public static readonly string UserAgent = "NuGet Command Line";
private readonly IConsole _console;
public CommandLineRepositoryFactory(IConsole console)
{
_console = console;
}
public override IPackageRepository CreateRepository(string packageSource)
{
var repository = base.CreateRepository(packageSource);
var httpClientEvents = repository as IHttpClientEvents;
if (httpClientEvents != null)
{
httpClientEvents.SendingRequest += (sender, args) =>
{
if (_console.Verbosity == Verbosity.Detailed)
{
_console.WriteLine(
System.ConsoleColor.Green,
"{0} {1}", args.Request.Method, args.Request.RequestUri);
}
string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
HttpUtility.SetUserAgent(args.Request, userAgent);
};
}
return repository;
}
}
}```
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed. | ```c#
using System.Windows;
namespace NuGet.Common
{
public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener
{
public static readonly string UserAgent = "NuGet Command Line";
private readonly IConsole _console;
public CommandLineRepositoryFactory(IConsole console)
{
_console = console;
}
public override IPackageRepository CreateRepository(string packageSource)
{
var repository = base.CreateRepository(packageSource);
var httpClientEvents = repository as IHttpClientEvents;
if (httpClientEvents != null)
{
SendingRequestEventManager.AddListener(httpClientEvents, this);
}
return repository;
}
public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e)
{
if (managerType == typeof(SendingRequestEventManager))
{
var args = (WebRequestEventArgs)e;
if (_console.Verbosity == Verbosity.Detailed)
{
_console.WriteLine(
System.ConsoleColor.Green,
"{0} {1}", args.Request.Method, args.Request.RequestUri);
}
string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
HttpUtility.SetUserAgent(args.Request, userAgent);
return true;
}
else
{
return false;
}
}
}
}``` |
cdc48d46-342b-4a08-bc6c-17cc17fc1f30 | {
"language": "C#"
} | ```c#
using System;
using MonoMac.AppKit;
namespace macdoc
{
public class AppleDocWizardDelegate : NSApplicationDelegate
{
AppleDocWizardController wizard;
public override bool ApplicationShouldOpenUntitledFile (NSApplication sender)
{
return false;
}
public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification)
{
wizard = new AppleDocWizardController ();
wizard.Window.Center ();
NSApplication.SharedApplication.ArrangeInFront (this);
NSApplication.SharedApplication.RunModalForWindow (wizard.Window);
}
}
}
```
Make the application and its window come in front when launched | ```c#
using System;
using MonoMac.AppKit;
namespace macdoc
{
public class AppleDocWizardDelegate : NSApplicationDelegate
{
AppleDocWizardController wizard;
public override bool ApplicationShouldOpenUntitledFile (NSApplication sender)
{
return false;
}
public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification)
{
wizard = new AppleDocWizardController ();
NSApplication.SharedApplication.ActivateIgnoringOtherApps (true);
wizard.Window.MakeMainWindow ();
wizard.Window.MakeKeyWindow ();
wizard.Window.MakeKeyAndOrderFront (this);
wizard.Window.Center ();
wizard.VerifyFreshnessAndLaunchDocProcess ();
NSApplication.SharedApplication.RunModalForWindow (wizard.Window);
}
}
}
``` |
c4946854-4307-4729-be1d-4e8ccd8368b9 | {
"language": "C#"
} | ```c#
using Content.Client.GameObjects.Components.Construction;
using Robust.Client.Interfaces.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Content.Client.Construction
{
public class ConstructionButton : Button
{
private readonly IDisplayManager _displayManager;
public ConstructorComponent Owner
{
get => Menu.Owner;
set => Menu.Owner = value;
}
ConstructionMenu Menu;
public ConstructionButton(IDisplayManager displayManager)
{
_displayManager = displayManager;
PerformLayout();
}
protected override void Initialize()
{
base.Initialize();
AnchorLeft = 1.0f;
AnchorTop = 1.0f;
AnchorRight = 1.0f;
AnchorBottom = 1.0f;
MarginLeft = -110.0f;
MarginTop = -70.0f;
MarginRight = -50.0f;
MarginBottom = -50.0f;
Text = "Crafting";
OnPressed += IWasPressed;
}
private void PerformLayout()
{
Menu = new ConstructionMenu(_displayManager);
Menu.AddToScreen();
}
void IWasPressed(ButtonEventArgs args)
{
Menu.Open();
}
public void AddToScreen()
{
UserInterfaceManager.StateRoot.AddChild(this);
}
public void RemoveFromScreen()
{
if (Parent != null)
{
Parent.RemoveChild(this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Menu.Dispose();
}
base.Dispose(disposing);
}
}
}
```
Use SetAnchorPreset instead of manually setting each anchor | ```c#
using Content.Client.GameObjects.Components.Construction;
using Robust.Client.Interfaces.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Content.Client.Construction
{
public class ConstructionButton : Button
{
private readonly IDisplayManager _displayManager;
public ConstructorComponent Owner
{
get => Menu.Owner;
set => Menu.Owner = value;
}
ConstructionMenu Menu;
public ConstructionButton(IDisplayManager displayManager)
{
_displayManager = displayManager;
PerformLayout();
}
protected override void Initialize()
{
base.Initialize();
SetAnchorPreset(LayoutPreset.BottomRight);
MarginLeft = -110.0f;
MarginTop = -70.0f;
MarginRight = -50.0f;
MarginBottom = -50.0f;
Text = "Crafting";
OnPressed += IWasPressed;
}
private void PerformLayout()
{
Menu = new ConstructionMenu(_displayManager);
Menu.AddToScreen();
}
void IWasPressed(ButtonEventArgs args)
{
Menu.Open();
}
public void AddToScreen()
{
UserInterfaceManager.StateRoot.AddChild(this);
}
public void RemoveFromScreen()
{
if (Parent != null)
{
Parent.RemoveChild(this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Menu.Dispose();
}
base.Dispose(disposing);
}
}
}
``` |
c98314d6-12a5-43d3-ab30-d43199ff1552 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.PS3Model
{
[XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")]
public class PhotoStoryProject
{
[XmlAttribute("schemaVersion")]
public string SchemaVersion;
[XmlAttribute("appVersion")]
public string AppVersion;
[XmlAttribute("linkOnly")]
public bool LinkOnly;
[XmlAttribute("defaultImageDuration")]
public int DefaultImageDuration;
[XmlAttribute("visualUnitCount")]
public int VisualUnitCount;
[XmlAttribute("codecVersion")]
public string CodecVersion;
[XmlAttribute("sessionSeed")]
public int SessionSeed;
[XmlElement("VisualUnit")]
public VisualUnit[] VisualUnits;
public string GetProjectName()
{
var bookName = "";
foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null))
{
foreach (var edit in vunit.Image.Edits)
{
if (edit.TextOverlays.Length <= 0)
continue;
bookName = edit.TextOverlays[0].Text.Trim();
bookName = Regex.Replace(bookName, @"\s+", " ");
break;
}
if (bookName != "")
break;
}
return bookName;
}
}
}
```
Handle PS3 covers with no text | ```c#
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.PS3Model
{
[XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")]
public class PhotoStoryProject
{
[XmlAttribute("schemaVersion")]
public string SchemaVersion;
[XmlAttribute("appVersion")]
public string AppVersion;
[XmlAttribute("linkOnly")]
public bool LinkOnly;
[XmlAttribute("defaultImageDuration")]
public int DefaultImageDuration;
[XmlAttribute("visualUnitCount")]
public int VisualUnitCount;
[XmlAttribute("codecVersion")]
public string CodecVersion;
[XmlAttribute("sessionSeed")]
public int SessionSeed;
[XmlElement("VisualUnit")]
public VisualUnit[] VisualUnits;
public string GetProjectName()
{
var bookName = "";
foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null))
{
foreach (var edit in vunit.Image.Edits)
{
if (edit.TextOverlays == null || edit.TextOverlays.Length <= 0)
continue;
bookName = edit.TextOverlays[0].Text.Trim();
bookName = Regex.Replace(bookName, @"\s+", " ");
break;
}
if (bookName != "")
break;
}
return bookName;
}
}
}
``` |
e9c95cf3-054e-4f1f-afaf-2e91377dff39 | {
"language": "C#"
} | ```c#
using System.Linq;
using NUnit.Framework;
namespace Rant.Tests.Richard
{
[TestFixture]
public class Lists
{
private readonly RantEngine rant = new RantEngine();
[Test]
public void ListInitBare()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main);
}
[Test]
public void ListInitBrackets()
{
Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main);
}
[Test]
public void ListInitConcat()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main);
}
[Test]
public void ListAsBlock()
{
string[] possibleResults = new string[] { "1", "2", "3", "4" };
Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0);
}
[Test]
public void ListInitializer()
{
Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main);
}
}
}
```
Add test for returning empty list from script | ```c#
using System.Linq;
using NUnit.Framework;
namespace Rant.Tests.Richard
{
[TestFixture]
public class Lists
{
private readonly RantEngine rant = new RantEngine();
[Test]
public void ListInitBare()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main);
}
[Test]
public void ListInitBrackets()
{
Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main);
}
[Test]
public void ListInitConcat()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main);
}
[Test]
public void ListAsBlock()
{
string[] possibleResults = new string[] { "1", "2", "3", "4" };
Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0);
}
[Test]
public void ListInitializer()
{
Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main);
}
[Test]
public void ListEmptyAsBlock()
{
Assert.AreEqual("", rant.Do(@"[@ [] ]"));
}
}
}
``` |
81a8f180-c65a-4bf3-aa4c-6d892dcf3968 | {
"language": "C#"
} | ```c#
using System;
namespace TDDUnit {
class TestTestCase : TestCase {
public TestTestCase(string name) : base(name) {
}
public void TestTemplateMethod() {
WasRunObj test = new WasRunObj("TestMethod");
test.Run();
Assert.That(test.Log == "SetUp TestMethod TearDown ");
}
public void TestResult() {
WasRunObj test = new WasRunObj("TestMethod");
TestResult result = test.Run();
Assert.That("1 run, 0 failed" == result.Summary);
}
public void TestFailedResult() {
WasRunObj test = new WasRunObj("TestBrokenMethod");
TestResult result = test.Run();
Assert.That("1 run, 1 failed" == result.Summary);
}
public void TestFailedResultFormatting() {
TestResult result = new TestResult();
result.TestStarted();
result.TestFailed();
Assert.That("1 run, 1 failed" == result.Summary);
}
}
class Program {
static void Main() {
new TestTestCase("TestTemplateMethod").Run();
new TestTestCase("TestResult").Run();
new TestTestCase("TestFailedResult").Run();
new TestTestCase("TestFailedResultFormatting").Run();
}
}
}
```
Print results of running tests | ```c#
using System;
namespace TDDUnit {
class TestTestCase : TestCase {
public TestTestCase(string name) : base(name) {
}
public void TestTemplateMethod() {
WasRunObj test = new WasRunObj("TestMethod");
test.Run();
Assert.That(test.Log == "SetUp TestMethod TearDown ");
}
public void TestResult() {
WasRunObj test = new WasRunObj("TestMethod");
TestResult result = test.Run();
Assert.That("1 run, 0 failed" == result.Summary);
}
public void TestFailedResult() {
WasRunObj test = new WasRunObj("TestBrokenMethod");
TestResult result = test.Run();
Assert.That("1 run, 1 failed" == result.Summary);
}
public void TestFailedResultFormatting() {
TestResult result = new TestResult();
result.TestStarted();
result.TestFailed();
Assert.That("1 run, 1 failed" == result.Summary);
}
}
class Program {
static void Main() {
Console.WriteLine(new TestTestCase("TestTemplateMethod").Run().Summary);
Console.WriteLine(new TestTestCase("TestResult").Run().Summary);
Console.WriteLine(new TestTestCase("TestFailedResult").Run().Summary);
Console.WriteLine(new TestTestCase("TestFailedResultFormatting").Run().Summary);
}
}
}
``` |
7dd29870-166e-4935-bd44-57ee3fbeb3e7 | {
"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.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
```
Add a bracket that somehow did not get comitted | ```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.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
{
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
``` |
eae03c92-59ee-47c1-b2af-7f64bb615e2e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Stormpath.Configuration.Abstractions;
using Stormpath.Owin.Abstractions.Configuration;
namespace Stormpath.Owin.UnitTest
{
public static class ConfigurationHelper
{
public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config)
{
var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config);
var integrationConfig = new IntegrationConfiguration(
compiledConfig,
new TenantConfiguration("foo", false, false),
new KeyValuePair<string, ProviderConfiguration>[0]);
return integrationConfig;
}
}
}
```
Fix missing API key error on AppVeyor | ```c#
using System.Collections.Generic;
using Stormpath.Configuration.Abstractions;
using Stormpath.Owin.Abstractions.Configuration;
namespace Stormpath.Owin.UnitTest
{
public static class ConfigurationHelper
{
public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config)
{
if (config.Client?.ApiKey == null)
{
if (config.Client == null)
{
config.Client = new ClientConfiguration();
}
config.Client.ApiKey = new ClientApiKeyConfiguration()
{
Id = "foo",
Secret = "bar"
};
};
var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config);
var integrationConfig = new IntegrationConfiguration(
compiledConfig,
new TenantConfiguration("foo", false, false),
new KeyValuePair<string, ProviderConfiguration>[0]);
return integrationConfig;
}
}
}
``` |
091e0075-5f92-4ee1-91c7-81e1a49f369f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Oogstplanner.Common;
using Oogstplanner.Models;
using Oogstplanner.Services;
namespace Oogstplanner.Web.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
readonly ICalendarService calendarService;
public HomeController(ICalendarService calendarService)
{
if (calendarService == null)
{
throw new ArgumentNullException("calendarService");
}
this.calendarService = calendarService;
}
//
// GET: /welkom
public ActionResult Index()
{
return View();
}
}
}
```
Remove dependency of home controller since it is no longer needed | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Oogstplanner.Common;
using Oogstplanner.Models;
using Oogstplanner.Services;
namespace Oogstplanner.Web.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
readonly ICalendarService calendarService;
public HomeController()
{ }
//
// GET: /welkom
public ActionResult Index()
{
return View();
}
//
// GET: /veelgesteldevragen
public ActionResult Faq()
{
return View();
}
}
}
``` |
0df08d17-8b83-4eec-bb1c-445bb2279420 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity.Groups == null){
return false;
}
bool accessAllow = false, accessDeny = false;
foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){
switch(rule.AccessControlType){
case AccessControlType.Allow: accessAllow = true; break;
case AccessControlType.Deny: accessDeny = true; break;
}
}
return accessAllow && !accessDeny;
}
catch{
return false;
}
}
public static Process StartProcess(string file, string arguments, bool runElevated){
ProcessStartInfo processInfo = new ProcessStartInfo{
FileName = file,
Arguments = arguments
};
if (runElevated){
processInfo.Verb = "runas";
}
return Process.Start(processInfo);
}
}
}
```
Rewrite folder write permission check to hopefully make it more reliable | ```c#
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection collection = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(NTAccount));
foreach(FileSystemAccessRule rule in collection){
if ((rule.FileSystemRights & right) == right){
return true;
}
}
return false;
}
catch{
return false;
}
}
public static Process StartProcess(string file, string arguments, bool runElevated){
ProcessStartInfo processInfo = new ProcessStartInfo{
FileName = file,
Arguments = arguments
};
if (runElevated){
processInfo.Verb = "runas";
}
return Process.Start(processInfo);
}
}
}
``` |
a03be973-8718-4508-a687-42d029354ab4 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
}```
Make sure that the stream passed in ctor can be seeked and read | ```c#
using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
if (!fileStream.CanSeek) throw new ArgumentException("Stream must be seekable", "fileStream");
if (!fileStream.CanRead) throw new ArgumentException("Stream must be readable", "fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
}``` |
db38ef8e-32d4-4219-9b9e-eebe48d3af11 | {
"language": "C#"
} | ```c#
using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
}
}
```
Add ToString to help with debuggign... :-) | ```c#
using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
/// <summary>
/// TO help with debugging...
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "(" + Type.Name + ") " + RawValue;
}
}
}
``` |
18430c1a-ae92-4e8a-b50e-aba20713de6f | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Reflection;
namespace Serilog.Generator.Configuration
{
static class CurrentDirectoryAssemblyLoader
{
public static void Install()
{
AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
{
var assemblyPath = Path.Combine(Environment.CurrentDirectory, e.Name + ".dll");
return !File.Exists(assemblyPath) ? null : Assembly.LoadFrom(assemblyPath);
};
}
}
}```
Fix assembly loading name format | ```c#
using System;
using System.IO;
using System.Reflection;
namespace Serilog.Generator.Configuration
{
static class CurrentDirectoryAssemblyLoader
{
public static void Install()
{
AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
{
var assemblyPath = Path.Combine(Environment.CurrentDirectory, new AssemblyName(e.Name).Name + ".dll");
return !File.Exists(assemblyPath) ? null : Assembly.LoadFrom(assemblyPath);
};
}
}
}``` |
29bf16a3-80c8-4210-ae25-41241d5af264 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A set of parameters that control the way strings are localised.
/// </summary>
public class LocalisationParameters
{
/// <summary>
/// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.
/// </summary>
public readonly ILocalisationStore? Store;
/// <summary>
/// Whether to prefer the "original" script of <see cref="RomanisableString"/>s.
/// </summary>
public readonly bool PreferOriginalScript;
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param>
/// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param>
public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript)
{
Store = store;
PreferOriginalScript = preferOriginalScript;
}
}
}
```
Add protected copy constructor to avoid breaking changes | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A set of parameters that control the way strings are localised.
/// </summary>
public class LocalisationParameters
{
/// <summary>
/// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.
/// </summary>
public readonly ILocalisationStore? Store;
/// <summary>
/// Whether to prefer the "original" script of <see cref="RomanisableString"/>s.
/// </summary>
public readonly bool PreferOriginalScript;
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/> based off another <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="parameters">The <see cref="LocalisationParameters"/> to copy values from.</param>
protected LocalisationParameters(LocalisationParameters parameters)
: this(parameters.Store, parameters.PreferOriginalScript)
{
}
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param>
/// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param>
public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript)
{
Store = store;
PreferOriginalScript = preferOriginalScript;
}
}
}
``` |
8e3ba635-8210-4e2e-b257-87387bd2452d | {
"language": "C#"
} | ```c#
@model IEnumerable<BankingManagementClient.ProjectionStore.Projections.Client.ClientProjection>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientId)
</th>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientName)
</th>
<th></th>
</tr>
@foreach (var clientProjection in Model)
{
<tr>
<td>
@Html.ActionLink(clientProjection.ClientId.ToString(), "Details", new { id = clientProjection.ClientId })
</td>
<td>
@Html.DisplayFor(modelItem => clientProjection.ClientName)
</td>
</tr>
}
</table>```
Check if there are any Clients on the list page | ```c#
@model IEnumerable<BankingManagementClient.ProjectionStore.Projections.Client.ClientProjection>
@{
ViewBag.Title = "Index";
}
<h2>Clients</h2>
@if (Model.Any())
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientId)
</th>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientName)
</th>
<th></th>
</tr>
@foreach (var clientProjection in Model)
{
<tr>
<td>
@Html.ActionLink(clientProjection.ClientId.ToString(), "Details", new {id = clientProjection.ClientId})
</td>
<td>
@Html.DisplayFor(modelItem => clientProjection.ClientName)
</td>
</tr>
}
</table>
}
else
{
<p>No clients found.</p>
}``` |
89f95148-9ba1-47cf-8142-40dcf2387c64 | {
"language": "C#"
} | ```c#
using System.IO;
using ApiContractGenerator.AssemblyReferenceResolvers;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Source;
using Microsoft.Build.Framework;
namespace ApiContractGenerator.MSBuild
{
public sealed class GenerateApiContract : ITask
{
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
[Required]
public ITaskItem[] Assemblies { get; set; }
public string[] IgnoredNamespaces { get; set; }
public bool Execute()
{
if (Assemblies.Length == 0) return true;
var generator = new ApiContractGenerator();
generator.IgnoredNamespaces.UnionWith(IgnoredNamespaces);
foreach (var assembly in Assemblies)
{
var assemblyPath = assembly.GetMetadata("ResolvedAssemblyPath");
var outputPath = assembly.GetMetadata("ResolvedOutputPath");
var assemblyResolver = new CompositeAssemblyReferenceResolver(
new GacAssemblyReferenceResolver(),
new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(assemblyPath)));
using (var metadataReferenceResolver = new MetadataReaderReferenceResolver(() => File.OpenRead(assemblyPath), assemblyResolver))
using (var source = new MetadataReaderSource(File.OpenRead(assemblyPath), metadataReferenceResolver))
using (var outputFile = File.CreateText(outputPath))
generator.Generate(source, new CSharpTextFormatter(outputFile, metadataReferenceResolver));
}
return true;
}
}
}
```
Handle null arrays when MSBuild doesn't initialize task properties | ```c#
using System.IO;
using ApiContractGenerator.AssemblyReferenceResolvers;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Source;
using Microsoft.Build.Framework;
namespace ApiContractGenerator.MSBuild
{
public sealed class GenerateApiContract : ITask
{
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
[Required]
public ITaskItem[] Assemblies { get; set; }
public string[] IgnoredNamespaces { get; set; }
public bool Execute()
{
if (Assemblies == null || Assemblies.Length == 0) return true;
var generator = new ApiContractGenerator();
if (IgnoredNamespaces != null) generator.IgnoredNamespaces.UnionWith(IgnoredNamespaces);
foreach (var assembly in Assemblies)
{
var assemblyPath = assembly.GetMetadata("ResolvedAssemblyPath");
var outputPath = assembly.GetMetadata("ResolvedOutputPath");
var assemblyResolver = new CompositeAssemblyReferenceResolver(
new GacAssemblyReferenceResolver(),
new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(assemblyPath)));
using (var metadataReferenceResolver = new MetadataReaderReferenceResolver(() => File.OpenRead(assemblyPath), assemblyResolver))
using (var source = new MetadataReaderSource(File.OpenRead(assemblyPath), metadataReferenceResolver))
using (var outputFile = File.CreateText(outputPath))
generator.Generate(source, new CSharpTextFormatter(outputFile, metadataReferenceResolver));
}
return true;
}
}
}
``` |
4af53c91-48a9-472b-a320-4bf14ba198d7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public Settings()
{
DateTimeFormat = new List<string> {"{dd}d {hh}h {mm}m"};
}
[Category("End")]
[DisplayName("Date/Time")]
public DateTime EndDateTime { get; set; } = DateTime.Now;
[Browsable(false)]
[DisplayName("Last End Date/Time")]
public DateTime LastEndDateTime { get; set; } = DateTime.Now;
[Category("Style")]
[DisplayName("Continue Counting")]
public bool EndContinueCounting { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Year")]
public bool SyncYear { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Month")]
public bool SyncMonth { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Day")]
public bool SyncDay { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Hour")]
public bool SyncHour { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Minute")]
public bool SyncMinute { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Second")]
public bool SyncSecond { get; set; } = false;
}
}```
Change "Countdown" "End Sync" properties order | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public Settings()
{
DateTimeFormat = new List<string> {"{dd}d {hh}h {mm}m"};
}
[Category("End")]
[DisplayName("Date/Time")]
public DateTime EndDateTime { get; set; } = DateTime.Now;
[Browsable(false)]
[DisplayName("Last End Date/Time")]
public DateTime LastEndDateTime { get; set; } = DateTime.Now;
[Category("Style")]
[DisplayName("Continue Counting")]
public bool EndContinueCounting { get; set; } = false;
[PropertyOrder(0)]
[Category("End Sync")]
[DisplayName("Sync Next Year")]
public bool SyncYear { get; set; } = false;
[PropertyOrder(1)]
[Category("End Sync")]
[DisplayName("Sync Next Month")]
public bool SyncMonth { get; set; } = false;
[PropertyOrder(2)]
[Category("End Sync")]
[DisplayName("Sync Next Day")]
public bool SyncDay { get; set; } = false;
[PropertyOrder(3)]
[Category("End Sync")]
[DisplayName("Sync Next Hour")]
public bool SyncHour { get; set; } = false;
[PropertyOrder(4)]
[Category("End Sync")]
[DisplayName("Sync Next Minute")]
public bool SyncMinute { get; set; } = false;
[PropertyOrder(5)]
[Category("End Sync")]
[DisplayName("Sync Next Second")]
public bool SyncSecond { get; set; } = false;
}
}``` |
00f7ad34-476d-455e-8aec-14894a23ae30 | {
"language": "C#"
} | ```c#
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
/// <summary>
/// Base class to map classes derived from <see cref="AbpTenant{TTenant,TUser}"/>
/// </summary>
/// <typeparam name="TTenant">Tenant type</typeparam>
/// <typeparam name="TUser">User type</typeparam>
public abstract class AbpTenantMap<TTenant, TUser> : EntityMap<TTenant>
where TTenant : AbpTenant<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Constructor.
/// </summary>
protected AbpTenantMap()
: base("AbpTenants")
{
References(x => x.Edition).Column("EditionId").Nullable();
Map(x => x.TenancyName);
Map(x => x.Name);
Map(x => x.IsActive);
this.MapFullAudited();
Polymorphism.Explicit();
}
}
}```
Fix cref attribute in XML comment | ```c#
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
/// <summary>
/// Base class to map classes derived from <see cref="AbpTenant{TUser}"/>
/// </summary>
/// <typeparam name="TTenant">Tenant type</typeparam>
/// <typeparam name="TUser">User type</typeparam>
public abstract class AbpTenantMap<TTenant, TUser> : EntityMap<TTenant>
where TTenant : AbpTenant<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Constructor.
/// </summary>
protected AbpTenantMap()
: base("AbpTenants")
{
References(x => x.Edition).Column("EditionId").Nullable();
Map(x => x.TenancyName);
Map(x => x.Name);
Map(x => x.IsActive);
this.MapFullAudited();
Polymorphism.Explicit();
}
}
}``` |
5d711e2c-865a-404c-be10-6e641f23288f | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Octokit.Reactive;
using Xunit;
namespace Octokit.Tests.Integration
{
public class ObservableRepositoriesClientTests
{
public class TheGetMethod
{
[IntegrationTest]
public async Task ReturnsSpecifiedRepository()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var observable = client.Get("haacked", "seegit");
var repository = await observable;
var repository2 = await observable;
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository.CloneUrl);
Assert.False(repository.Private);
Assert.False(repository.Fork);
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository2.CloneUrl);
Assert.False(repository2.Private);
Assert.False(repository2.Fork);
}
}
public class TheGetAllPublicSinceMethod
{
[IntegrationTest]
public async Task ReturnsAllPublicReposSinceLastSeen()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var request = new PublicRepositoryRequest
{
Since = 32732250
};
var repositories = await client.GetAllPublic(request).ToArray();
Assert.NotNull(repositories);
Assert.True(repositories.Any());
Assert.Equal(32732252, repositories[0].Id);
Assert.False(repositories[0].Private);
Assert.Equal("zad19", repositories[0].Name);
}
}
}
}
```
Update Assert call and mute the test | ```c#
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Octokit.Reactive;
using Xunit;
namespace Octokit.Tests.Integration
{
public class ObservableRepositoriesClientTests
{
public class TheGetMethod
{
[IntegrationTest]
public async Task ReturnsSpecifiedRepository()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var observable = client.Get("haacked", "seegit");
var repository = await observable;
var repository2 = await observable;
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository.CloneUrl);
Assert.False(repository.Private);
Assert.False(repository.Fork);
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository2.CloneUrl);
Assert.False(repository2.Private);
Assert.False(repository2.Fork);
}
}
public class TheGetAllPublicSinceMethod
{
[IntegrationTest(Skip = "This will take a very long time to return, so will skip it for now.")]
public async Task ReturnsAllPublicReposSinceLastSeen()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var request = new PublicRepositoryRequest
{
Since = 32732250
};
var repositories = await client.GetAllPublic(request).ToArray();
Assert.NotEmpty(repositories);
Assert.Equal(32732252, repositories[0].Id);
Assert.False(repositories[0].Private);
Assert.Equal("zad19", repositories[0].Name);
}
}
}
}
``` |
eeb7a17c-abeb-4783-8369-05995b22bfba | {
"language": "C#"
} | ```c#
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tyrrrz.Extensions.Tests
{
[TestClass]
public class XmlTests
{
[TestMethod]
public void StripNamespacesTest()
{
var ns = XNamespace.Get("http://schemas.domain.com/orders");
var xml =
new XElement(ns + "order",
new XElement(ns + "customer", "Foo", new XAttribute(ns + "hello", "world")),
new XElement("purchases",
new XElement(ns + "purchase", "Unicycle", new XAttribute("price", "100.00")),
new XElement("purchase", "Bicycle"),
new XElement(ns + "purchase", "Tricycle",
new XAttribute("price", "300.00"),
new XAttribute(XNamespace.Xml.GetName("space"), "preserve")
)
)
);
var stripped = xml.StripNamespaces();
var xCustomer = stripped.Element("customer");
var xHello = xCustomer?.Attribute("hello");
Assert.IsNotNull(xCustomer);
Assert.IsNotNull(xHello);
Assert.AreEqual("world", xHello.Value);
}
}
}```
Add mutability test to StripNamespaces | ```c#
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tyrrrz.Extensions.Tests
{
[TestClass]
public class XmlTests
{
[TestMethod]
public void StripNamespacesTest()
{
var ns = XNamespace.Get("http://schemas.domain.com/orders");
var xml =
new XElement(ns + "order",
new XElement(ns + "customer", "Foo", new XAttribute(ns + "hello", "world")),
new XElement("purchases",
new XElement(ns + "purchase", "Unicycle", new XAttribute("price", "100.00")),
new XElement("purchase", "Bicycle"),
new XElement(ns + "purchase", "Tricycle",
new XAttribute("price", "300.00"),
new XAttribute(XNamespace.Xml.GetName("space"), "preserve")
)
)
);
var stripped = xml.StripNamespaces();
var xCustomer = stripped.Element("customer");
var xHello = xCustomer?.Attribute("hello");
Assert.AreNotSame(xml, stripped);
Assert.IsNotNull(xCustomer);
Assert.IsNotNull(xHello);
Assert.AreEqual("world", xHello.Value);
}
}
}``` |
70aa7bc6-045c-420b-8c78-7e5ae0faf225 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace LockSample
{
using System;
internal sealed class Program
{
private static void Main(string[] args)
{
}
}
}
```
Add basic integration test skeleton | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace LockSample
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
internal sealed class Program
{
private static void Main(string[] args)
{
Random random = new Random();
ExclusiveLock l = new ExclusiveLock();
List<int> list = new List<int>();
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Task task = LoopAsync(random, l, list, cts.Token);
Thread.Sleep(1000);
cts.Cancel();
task.Wait();
}
}
private static async Task LoopAsync(Random random, ExclusiveLock l, IList<int> list, CancellationToken token)
{
while (!token.IsCancellationRequested)
{
switch (random.Next(1))
{
case 0:
await EnumerateListAsync(l, list);
break;
}
}
}
private static async Task EnumerateListAsync(ExclusiveLock l, IList<int> list)
{
ExclusiveLock.Token token = await l.AcquireAsync();
await Task.Yield();
try
{
int lastItem = 0;
foreach (int item in list)
{
if (lastItem != (item - 1))
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"State corruption detected; expected {0} but saw {1} in next list entry.",
lastItem + 1,
item));
}
await Task.Yield();
}
}
finally
{
l.Release(token);
}
}
}
}
``` |
599b9222-7ffe-4d00-86f7-6f75666b06a1 | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CVaS.Web.Filters
{
/// <summary>
/// Exception filter that catch exception of known type
/// and transform them into specific HTTP status code with
/// error message
/// </summary>
public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
switch (context.Exception)
{
case ApiException apiException:
var apiError = new ApiError(apiException.Message);
context.ExceptionHandled = true;
context.HttpContext.Response.StatusCode = apiException.StatusCode;
context.Result = new ObjectResult(apiError);
break;
case NotImplementedException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
context.ExceptionHandled = true;
break;
case UnauthorizedAccessException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.ExceptionHandled = true;
break;
}
base.OnException(context);
}
}
}
```
Return 403 instead of 401 | ```c#
using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CVaS.Web.Filters
{
/// <summary>
/// Exception filter that catch exception of known type
/// and transform them into specific HTTP status code with
/// error message
/// </summary>
public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
switch (context.Exception)
{
case ApiException apiException:
var apiError = new ApiError(apiException.Message);
context.ExceptionHandled = true;
context.HttpContext.Response.StatusCode = apiException.StatusCode;
context.Result = new ObjectResult(apiError);
break;
case NotImplementedException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
context.ExceptionHandled = true;
break;
case UnauthorizedAccessException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.ExceptionHandled = true;
break;
}
base.OnException(context);
}
}
}
``` |
322b160e-24bc-4b72-9f94-4364d75a81d3 | {
"language": "C#"
} | ```c#
using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;
namespace Dragon.SecurityServer.Common
{
public class SecurityHelper
{
public static X509SigningCredentials CreateSignupCredentialsFromConfig()
{
return new X509SigningCredentials(new X509Certificate2(X509Certificate.CreateFromCertFile(
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]))));
}
}
}
```
Allow reading certificates from local files | ```c#
using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;
namespace Dragon.SecurityServer.Common
{
public class SecurityHelper
{
public static X509SigningCredentials CreateSignupCredentialsFromConfig()
{
var certificateFilePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]);
var data = File.ReadAllBytes(certificateFilePath);
var certificate = new X509Certificate2(data, string.Empty, X509KeyStorageFlags.MachineKeySet);
return new X509SigningCredentials(certificate);
}
}
}
``` |
0a5393f9-15ef-44ac-b647-1df7c1737f20 | {
"language": "C#"
} | ```c#
using compiler.middleend.ir;
using NUnit.Framework;
namespace NUnit.Tests.MiddleEnd
{
[TestFixture]
public class InstructionTests
{
[Test]
public void ToStringTest()
{
var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
new Operand(Operand.OpType.Identifier, 10));
var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
new Operand(inst1));
Assert.AreEqual( inst2.Num.ToString() + " Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());
}
}
}
```
Fix error in unit test from changing the ToString | ```c#
using compiler.middleend.ir;
using NUnit.Framework;
namespace NUnit.Tests.MiddleEnd
{
[TestFixture]
public class InstructionTests
{
[Test]
public void ToStringTest()
{
var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
new Operand(Operand.OpType.Identifier, 10));
var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
new Operand(inst1));
Assert.AreEqual( inst2.Num.ToString() + ": Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());
}
}
}
``` |
e1808f3d-410c-4ff6-9c0b-ce0e6a389664 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e5f59157-7a01-4616-86e3-c9a924d8a218")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Update copyright statement to 2014 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e5f59157-7a01-4616-86e3-c9a924d8a218")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
``` |
48b323c9-9b79-41a4-87c2-a5ada405ef24 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mef")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mef")]
``` |
b11804a7-1dc3-4f20-a940-36ee8989da4e | {
"language": "C#"
} | ```c#
using System;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;
public class ClientEntityFactory : IClientEntityFactory
{
private static ClientEntityFactory _default;
public static ClientEntityFactory Default
{
get { return _default ?? (_default = new ClientEntityFactory()); }
}
public Transform RootTransform { get; set; }
IClientEntity IClientEntityFactory.Create(Type protoTypeType)
{
var resource = Resources.Load("Client" + protoTypeType.Name.Substring(1));
var go = (GameObject)GameObject.Instantiate(resource);
if (RootTransform != null)
go.transform.SetParent(RootTransform, false);
return go.GetComponent<IClientEntity>();
}
void IClientEntityFactory.Delete(IClientEntity entity)
{
var enb = ((EntityNetworkBehaviour)entity);
GameObject.Destroy(enb.gameObject);
}
}
```
Fix a build error of UnityPackage | ```c#
using System;
using System.Collections.Concurrent;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;
public class ClientEntityFactory : IClientEntityFactory
{
private static ClientEntityFactory _default;
public static ClientEntityFactory Default
{
get { return _default ?? (_default = new ClientEntityFactory()); }
}
public Transform RootTransform { get; set; }
private readonly ConcurrentDictionary<Type, Type> _clientEntityToProtoTypeMap =
new ConcurrentDictionary<Type, Type>();
Type IClientEntityFactory.GetProtoType(Type entityType)
{
return _clientEntityToProtoTypeMap.GetOrAdd(entityType, t =>
{
var type = entityType;
while (type != null && type != typeof(object))
{
if (type.Name.EndsWith("ClientBase"))
{
var typePrefix = type.Namespace.Length > 0 ? type.Namespace + "." : "";
var protoType = type.Assembly.GetType(typePrefix + "I" +
type.Name.Substring(0, type.Name.Length - 10));
if (protoType != null && typeof(IEntityPrototype).IsAssignableFrom(protoType))
{
return protoType;
}
}
type = type.BaseType;
}
return null;
});
}
IClientEntity IClientEntityFactory.Create(Type protoType)
{
var resourceName = "Client" + protoType.Name.Substring(1);
var resource = Resources.Load(resourceName);
if (resource == null)
throw new InvalidOperationException("Failed to load resource(" + resourceName + ")");
var go = (GameObject)GameObject.Instantiate(resource);
if (go == null)
throw new InvalidOperationException("Failed to instantiate resource(" + resourceName + ")");
if (RootTransform != null)
go.transform.SetParent(RootTransform, false);
return go.GetComponent<IClientEntity>();
}
void IClientEntityFactory.Delete(IClientEntity entity)
{
var enb = ((EntityNetworkBehaviour)entity);
GameObject.Destroy(enb.gameObject);
}
}
``` |
28390471-4102-479f-a7d9-66bf6d7ad342 | {
"language": "C#"
} | ```c#
namespace Moq
{
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Sdk;
/// <summary>
/// Instantiates mocks for the specified types.
/// </summary>
[GeneratedCode("Moq", "5.0")]
[CompilerGenerated]
partial class Mock
{
/// <summary>
/// Creates the mock instance by using the specified types to
/// lookup the mock type in the assembly defining this class.
/// </summary>
private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
{
var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);
mocked.Initialize(behavior);
return (T)mocked;
}
}
}```
Unify namespace placement with the .Overloads partial class | ```c#
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Sdk;
namespace Moq
{
/// <summary>
/// Instantiates mocks for the specified types.
/// </summary>
[GeneratedCode("Moq", "5.0")]
[CompilerGenerated]
partial class Mock
{
/// <summary>
/// Creates the mock instance by using the specified types to
/// lookup the mock type in the assembly defining this class.
/// </summary>
private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
{
var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);
mocked.Initialize(behavior);
return (T)mocked;
}
}
}``` |
eb008ed0-38a0-4276-bccd-0cb45f415a04 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
```
Revert "Removing 'zzz' from method name" | ```c#
using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
``` |
395ed620-ce31-44b2-99fc-49d24e5592ee | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseLadderManager : OsuTestCase
{
[Cached]
private readonly LadderManager manager;
public TestCaseLadderManager()
{
var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
var ladder = JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) ?? new LadderInfo();
Child = manager = new LadderManager(ladder, teams);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info));
}
}
}
```
Reduce noise in json output and handle the case the file doesn't exist | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseLadderManager : OsuTestCase
{
[Cached]
private readonly LadderManager manager;
public TestCaseLadderManager()
{
var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
var ladder = File.Exists(@"bracket.json") ? JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) : new LadderInfo();
Child = manager = new LadderManager(ladder, teams);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
}));
}
}
}
``` |
edb7b3cb-06fe-4400-8ba8-c156947b2613 | {
"language": "C#"
} | ```c#
using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfMovieSystem.Views
{
/// <summary>
/// Interaction logic for InsertWindowView.xaml
/// </summary>
public partial class InsertWindowView : Window
{
public InsertWindowView()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
using (MoviesSystemDbContext context = new MoviesSystemDbContext())
{
var firstName = FirstNameTextBox.Text;
var lastName = LastNameTextBox.Text;
var movies = MoviesTextBox.Text.Split(',');
var newActor = new Actor
{
FirstName = firstName,
LastName = lastName,
Movies = new List<Movie>()
};
foreach (var movie in movies)
{
newActor.Movies.Add(new Movie { Title = movie });
}
context.Actors.Add(newActor);
context.SaveChanges();
}
FirstNameTextBox.Text = "";
LastNameTextBox.Text = "";
MoviesTextBox.Text = "";
}
}
}
```
Add restrictions when creating the movie collection | ```c#
using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfMovieSystem.Views
{
/// <summary>
/// Interaction logic for InsertWindowView.xaml
/// </summary>
public partial class InsertWindowView : Window
{
public InsertWindowView()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
using (MoviesSystemDbContext context = new MoviesSystemDbContext())
{
var firstName = FirstNameTextBox.Text;
var lastName = LastNameTextBox.Text;
var movies = MoviesTextBox.Text.Split(',');
var newActor = new Actor
{
FirstName = firstName,
LastName = lastName,
Movies = new List<Movie>()
};
foreach (var movie in movies)
{
newActor.Movies.Add(LoadOrCreateMovie(context, movie));
}
context.Actors.Add(newActor);
context.SaveChanges();
}
FirstNameTextBox.Text = "";
LastNameTextBox.Text = "";
MoviesTextBox.Text = "";
}
private static Movie LoadOrCreateMovie(MoviesSystemDbContext context, string movieTitle)
{
var movie = context.Movies
.FirstOrDefault(m => m.Title.ToLower() == movieTitle.ToLower());
if (movie == null)
{
movie = new Movie
{
Title = movieTitle
};
}
return movie;
}
}
}
``` |
01cb77d9-2c95-4249-b815-8aef77927126 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
public class TraktShowIds : TraktIds
{
}
}
```
Add documentation for show ids. | ```c#
namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
/// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt show.</summary>
public class TraktShowIds : TraktIds
{
}
}
``` |
b8d70ae0-6378-4c91-9827-7c4000ba4467 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace DiplomContentSystem.Requests
{
public class RequestService
{
public async Task<Stream> SendRequest(object data)
{
using (var client = new HttpClient())
{
try
{
var content = new StringContent(JsonConvert.SerializeObject(data)
);
client.BaseAddress = new Uri("http://localhost:1337");
var response = await client.PostAsync("api/docx", content);
response.EnsureSuccessStatusCode(); // Throw in not success
return await response.Content.ReadAsStreamAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
throw (e);
}
}
}
}
}
```
Update json.net to use new MIME, encoding and camelCase formatting | ```c#
using System;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace DiplomContentSystem.Requests
{
public class RequestService
{
public async Task<Stream> SendRequest(object data)
{
using (var client = new HttpClient())
{
try
{
var content = new StringContent(JsonConvert.SerializeObject(data,
new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}), System.Text.Encoding.UTF8, "application/json");
client.BaseAddress = new Uri("http://localhost:1337");
var response = await client.PostAsync("api/docx",content);
response.EnsureSuccessStatusCode(); // Throw in not success
return await response.Content.ReadAsStreamAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
throw (e);
}
}
}
}
}
``` |
d7db7825-e0f0-400f-9178-93474e487301 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Dapper.FluentMap.Utils
{
internal static class DictionaryExtensions
{
internal static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, IList<TValue>> dict, TKey key, TValue value)
{
if (dict.ContainsKey(key))
{
dict[key].Add(value);
}
else
{
dict.Add(key, new[] { value });
}
}
}
}
```
Use a list rather than a fixed-size array. | ```c#
using System.Collections.Generic;
namespace Dapper.FluentMap.Utils
{
internal static class DictionaryExtensions
{
internal static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, IList<TValue>> dict, TKey key, TValue value)
{
if (dict.ContainsKey(key))
{
dict[key].Add(value);
}
else
{
dict.Add(key, new List<TValue> { value });
}
}
}
}
``` |
ed71e3da-2e6b-4b8d-b7d4-cb4c379aa7b4 | {
"language": "C#"
} | ```c#
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
return RepeatImpl(element, count);
}
public static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
{
for (int i = 0; i < count; i++)
{
yield return element;
}
}
}
}
```
Make the implementation method private. | ```c#
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
return RepeatImpl(element, count);
}
private static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
{
for (int i = 0; i < count; i++)
{
yield return element;
}
}
}
}
``` |
0bbc63f3-299d-46c9-99a3-8548cda10466 | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;
namespace Mycroft.Tests
{
[TestClass]
public class TestCommandConnection
{
[TestMethod]
public async Task TestBodylessMessage(){
var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
var cmd = new CommandConnection(s);
var msg = await cmd.getCommandAsync();
Trace.WriteLine(msg);
if (msg != "APP_UP")
throw new Exception("Incorrect message!");
}
[TestMethod]
public async Task TestBodaciousMessage()
{
var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
var cmd = new CommandConnection(s);
var msg = await cmd.getCommandAsync();
Trace.WriteLine(msg);
Trace.WriteLine(input.Substring(3));
if (msg != input.Substring(3))
throw new Exception("Incorrect message!");
}
}
}
```
Fix CommandConnection methods in Test | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;
namespace Mycroft.Tests
{
[TestClass]
public class TestCommandConnection
{
[TestMethod]
public async Task TestBodylessMessage(){
var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
var cmd = new CommandConnection(s);
var msg = await cmd.GetCommandAsync();
Trace.WriteLine(msg);
if (msg != "APP_UP")
throw new Exception("Incorrect message!");
}
[TestMethod]
public async Task TestBodaciousMessage()
{
var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
var cmd = new CommandConnection(s);
var msg = await cmd.GetCommandAsync();
Trace.WriteLine(msg);
Trace.WriteLine(input.Substring(3));
if (msg != input.Substring(3))
throw new Exception("Incorrect message!");
}
}
}
``` |
7977db99-18f6-4604-8e04-b9a8b97c01bc | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public bool RegEx { get; set; }
}
}```
Fix deserialization of RegEx enabled properties | ```c#
using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public string RegEx { get; set; }
}
}``` |
f6a86407-beec-42cc-b44c-75c1b467ea88 | {
"language": "C#"
} | ```c#
namespace FunctionalTestUtils
{
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights.Channel;
public class BackTelemetryChannel : ITelemetryChannel
{
private IList<ITelemetry> buffer;
public BackTelemetryChannel()
{
this.buffer = new List<ITelemetry>();
}
public IList<ITelemetry> Buffer
{
get
{
return this.buffer;
}
}
public bool? DeveloperMode
{
get
{
return true;
}
set
{
}
}
public string EndpointAddress
{
get
{
return "https://dc.services.visualstudio.com/v2/track";
}
set
{
}
}
public void Dispose()
{
}
public void Flush()
{
throw new NotImplementedException();
}
public void Send(ITelemetry item)
{
this.buffer.Add(item);
}
}
}```
Add flush for mock channel | ```c#
namespace FunctionalTestUtils
{
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights.Channel;
public class BackTelemetryChannel : ITelemetryChannel
{
private IList<ITelemetry> buffer;
public BackTelemetryChannel()
{
this.buffer = new List<ITelemetry>();
}
public IList<ITelemetry> Buffer
{
get
{
return this.buffer;
}
}
public bool? DeveloperMode
{
get
{
return true;
}
set
{
}
}
public string EndpointAddress
{
get
{
return "https://dc.services.visualstudio.com/v2/track";
}
set
{
}
}
public void Dispose()
{
}
public void Flush()
{
}
public void Send(ITelemetry item)
{
this.buffer.Add(item);
}
}
}``` |
66b69911-c4b3-455c-b704-b42fa6c00d34 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]
// NOTE: When changing this version, also update Cassette.MSBuild\Cassette.targets to match.
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")]```
Set nuget package version to 2.0.0-beta1 | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]
[assembly: AssemblyInformationalVersion("2.0.0-beta1")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")]``` |
d40ea680-3c60-4c9c-8e72-8a22761f720c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace DotVVM.Framework.Diagnostics
{
public class DotvvmDiagnosticsConfiguration
{
public DotvvmDiagnosticsConfiguration()
{
LoadConfiguration();
}
private DiagnosticsServerConfiguration configuration;
public string DiagnosticsServerHostname
{
get
{
if (configuration == null)
LoadConfiguration();
return configuration.HostName;
}
}
public int? DiagnosticsServerPort
{
get
{
if (configuration == null)
LoadConfiguration();
return configuration?.Port;
}
}
private void LoadConfiguration()
{
try
{
var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
}
catch
{
// ignored
}
}
}
}
```
Remove redundant configuration loading of diagnostics configuration | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace DotVVM.Framework.Diagnostics
{
public class DotvvmDiagnosticsConfiguration
{
public DotvvmDiagnosticsConfiguration()
{
LoadConfiguration();
}
private DiagnosticsServerConfiguration configuration;
public string DiagnosticsServerHostname => configuration.HostName;
public int? DiagnosticsServerPort => configuration?.Port;
private void LoadConfiguration()
{
try
{
var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
}
catch
{
// ignored
}
}
}
}
``` |
bd952eca-b385-49ca-9e1c-0b595edf18fa | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp.Helpers
{
public static class LocationExtensions
{
public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = location.GetMappedLineSpan();
var path = lineSpan.Path;
var documents = workspace.GetDocuments(path);
var line = lineSpan.StartLinePosition.Line;
var text = location.SourceTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line,
Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
EndLine = lineSpan.EndLinePosition.Line,
EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
Projects = documents.Select(document => document.Project.Name).ToArray()
};
}
}
}
```
Exclude Cake files from line span mapping | ```c#
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp.Helpers
{
public static class LocationExtensions
{
public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = Path.GetExtension(location.SourceTree.FilePath).Equals(".cake", StringComparison.OrdinalIgnoreCase)
? location.GetLineSpan()
: location.GetMappedLineSpan();
var path = lineSpan.Path;
var documents = workspace.GetDocuments(path);
var line = lineSpan.StartLinePosition.Line;
var text = location.SourceTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line,
Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
EndLine = lineSpan.EndLinePosition.Line,
EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
Projects = documents.Select(document => document.Project.Name).ToArray()
};
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.