doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
0658d353-17c5-4f94-8768-68691af91d55 | {
"language": "C#"
} | ```c#
using System;
using UnityEngine;
public static class InputInterceptor
{
static InputInterceptor()
{
Type abstractControlsType = ReflectionHelper.FindType("AbstractControls");
_inputSystems = Resources.FindObjectsOfTypeAll(abstractControlsType);
}
public static void EnableInput()
{
foreach (UnityEngine.Object inputSystem in _inputSystems)
{
try
{
((MonoBehaviour)inputSystem).gameObject.SetActive(true);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
public static void DisableInput()
{
foreach (UnityEngine.Object inputSystem in _inputSystems)
{
try
{
((MonoBehaviour)inputSystem).gameObject.SetActive(false);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
private static UnityEngine.Object[] _inputSystems = null;
}
```
Stop mouse cursor disappearing when input is restored with Esc button | ```c#
using System;
using UnityEngine;
public static class InputInterceptor
{
static InputInterceptor()
{
Type abstractControlsType = ReflectionHelper.FindType("AbstractControls");
_inputSystems = Resources.FindObjectsOfTypeAll(abstractControlsType);
}
public static void EnableInput()
{
foreach (UnityEngine.Object inputSystem in _inputSystems)
{
try
{
((MonoBehaviour)inputSystem).gameObject.SetActive(true);
Cursor.visible = true;
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
public static void DisableInput()
{
foreach (UnityEngine.Object inputSystem in _inputSystems)
{
try
{
((MonoBehaviour)inputSystem).gameObject.SetActive(false);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
private static UnityEngine.Object[] _inputSystems = null;
}
``` |
93832606-906e-4871-b529-3733a3888cea | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using System.Reflection;
namespace CertiPay.Payroll.Common
{
public static class ExtensionMethods
{
/// <summary>
/// Returns the display name from the description attribute on the enumeration, if available.
/// Otherwise returns the ToString() value.
/// </summary>
public static string DisplayName(this Enum val)
{
FieldInfo fi = val.GetType().GetField(val.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
return val.ToString();
}
}
}```
Add method for rounding decimals. | ```c#
using System;
using System.ComponentModel;
using System.Reflection;
namespace CertiPay.Payroll.Common
{
public static class ExtensionMethods
{
/// <summary>
/// Round the decimal to the given number of decimal places using the given method of rounding.
/// By default, this is 2 decimal places to the nearest even for middle values
/// i.e. 1.455 -> 1.46
/// </summary>
public static Decimal Round(this Decimal val, int decimals = 2, MidpointRounding rounding = MidpointRounding.ToEven)
{
return Math.Round(val, decimals, rounding);
}
/// <summary>
/// Returns the display name from the description attribute on the enumeration, if available.
/// Otherwise returns the ToString() value.
/// </summary>
public static string DisplayName(this Enum val)
{
FieldInfo fi = val.GetType().GetField(val.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
return val.ToString();
}
}
}``` |
5d998286-677d-47a8-a27d-625102faf7ae | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap));
drawableRuleset.Playfield.AlwaysPresent = true;
drawableRuleset.Playfield.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.AlwaysPresent = true;
overlay.Hide();
}
public void ApplyToPlayer(Player player)
{
player.Background.EnableUserDim.Value = false;
player.DimmableVideo.IgnoreUserSettings.Value = true;
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
}
}
}
```
Hide HUD in a better way | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap));
drawableRuleset.Playfield.AlwaysPresent = true;
drawableRuleset.Playfield.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.ShowHud.Value = false;
overlay.ShowHud.Disabled = true;
}
public void ApplyToPlayer(Player player)
{
player.Background.EnableUserDim.Value = false;
player.DimmableVideo.IgnoreUserSettings.Value = true;
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
}
}
}
``` |
513a062e-715f-4add-8da0-d63e4e8bcc58 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Serilog;
using Serilog.Core;
namespace Titan.Logging
{
public class LogCreator
{
public static DirectoryInfo LogDirectory = new DirectoryInfo(Environment.CurrentDirectory +
Path.DirectorySeparatorChar + "logs");
public static Logger Create(string name)
{
return new LoggerConfiguration()
.WriteTo.LiterateConsole(outputTemplate:
"{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}")
.WriteTo.Async(a => a.RollingFile(Path.Combine(LogDirectory.ToString(),
name + "-{Date}.log"), outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u}] {Name} @ {ThreadId} - {Message}{NewLine}{Exception}"))
.MinimumLevel.Debug() // TODO: Change this to "INFO" on release.
.Enrich.WithProperty("Name", name)
.Enrich.WithProperty("Thread", Thread.CurrentThread.Name)
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.CreateLogger();
}
public static Logger Create()
{
var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;
return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)");
}
}
}```
Change field name to "_logDir" | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Serilog;
using Serilog.Core;
namespace Titan.Logging
{
public class LogCreator
{
private static DirectoryInfo _logDir = new DirectoryInfo(Environment.CurrentDirectory +
Path.DirectorySeparatorChar + "logs");
public static Logger Create(string name)
{
return new LoggerConfiguration()
.WriteTo.LiterateConsole(outputTemplate:
"{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}")
.WriteTo.Async(a => a.RollingFile(Path.Combine(_logDir.ToString(),
name + "-{Date}.log"), outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u}] {Name} @ {ThreadId} - {Message}{NewLine}{Exception}"))
.MinimumLevel.Debug() // TODO: Change this to "INFO" on release.
.Enrich.WithProperty("Name", name)
.Enrich.WithProperty("Thread", Thread.CurrentThread.Name)
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.CreateLogger();
}
public static Logger Create()
{
var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;
return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)");
}
}
}``` |
5db78554-1521-4c32-9ec1-70e04425e5f9 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.Bindings;
namespace osu.Framework.Input
{
internal class FrameworkActionContainer : KeyBindingContainer<FrameworkAction>
{
public override IEnumerable<KeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser),
new KeyBinding(new[] { InputKey.Control, InputKey.F2 }, FrameworkAction.ToggleGlobalStatistics),
new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics),
new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay),
new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen),
};
protected override bool Prioritised => true;
}
public enum FrameworkAction
{
CycleFrameStatistics,
ToggleDrawVisualiser,
ToggleGlobalStatistics,
ToggleLogOverlay,
ToggleFullscreen
}
}
```
Allow using F11 to toggle fullscreen | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.Bindings;
namespace osu.Framework.Input
{
internal class FrameworkActionContainer : KeyBindingContainer<FrameworkAction>
{
public override IEnumerable<KeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser),
new KeyBinding(new[] { InputKey.Control, InputKey.F2 }, FrameworkAction.ToggleGlobalStatistics),
new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics),
new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay),
new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen),
new KeyBinding(new[] { InputKey.F11 }, FrameworkAction.ToggleFullscreen)
};
protected override bool Prioritised => true;
}
public enum FrameworkAction
{
CycleFrameStatistics,
ToggleDrawVisualiser,
ToggleGlobalStatistics,
ToggleLogOverlay,
ToggleFullscreen
}
}
``` |
caec558f-c048-44ea-9120-eb838555a17a | {
"language": "C#"
} | ```c#
using System;
using System.Web;
using Cassette;
namespace Precompiled
{
/// <summary>
/// An example implementation of Cassette.IUrlModifier.
///
/// </summary>
public class CdnUrlModifier : IUrlModifier
{
public string Modify(string url)
{
// The url passed to modify will be a relative path.
// For example: "_cassette/scriptbundle/scripts/app_abc123"
// We can return a modified URL. For example, prefixing something like "http://mycdn.com/myapp/"
var prefix = GetCdnUrlPrefix();
return prefix + url;
}
static string GetCdnUrlPrefix()
{
// We don't have a CDN for this sample.
// So just build an absolute URL instead.
var host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
var prefix = host + HttpRuntime.AppDomainAppVirtualPath.TrimEnd('/') + "/";
return prefix;
}
}
}```
Update IUrlModifier to work on any thread by not using HttpContext.Current in the Modify method. | ```c#
using System;
using System.Web;
using Cassette;
namespace Precompiled
{
/// <summary>
/// An example implementation of Cassette.IUrlModifier.
/// </summary>
public class CdnUrlModifier : IUrlModifier
{
readonly string prefix;
public CdnUrlModifier(HttpContextBase httpContext)
{
// We don't have a CDN for this sample.
// So just build an absolute URL instead.
var host = httpContext.Request.Url.GetLeftPart(UriPartial.Authority);
prefix = host + httpContext.Request.ApplicationPath.TrimEnd('/') + "/";
}
public string Modify(string url)
{
// The url passed to modify will be a relative path.
// For example: "_cassette/scriptbundle/scripts/app_abc123"
// We can return a modified URL. For example, prefixing something like "http://mycdn.com/myapp/"
return prefix + url;
}
}
}``` |
74d688e7-3770-45d3-947c-1d12a3ddd804 | {
"language": "C#"
} | ```c#
@model Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination.PaginationInfo
<div class="esh-pager">
<div class="container">
<article class="esh-pager-wrapper row">
<nav>
<a class="esh-pager-item esh-pager-item--navigable @Model.Previous"
id="Previous"
href="@Url.Action("Index","Catalog", new { page = Model.ActualPage -1 })"
aria-label="Previous">
Previous
</a>
<span class="esh-pager-item">
Showing @Html.DisplayFor(modelItem => modelItem.ItemsPerPage) of @Html.DisplayFor(modelItem => modelItem.TotalItems) products - Page @(Model.ActualPage + 1) - @Html.DisplayFor(x => x.TotalPages)
</span>
<a class="esh-pager-item esh-pager-item--navigable @Model.Next"
id="Next"
href="@Url.Action("Index","Catalog", new { page = Model.ActualPage + 1 })"
aria-label="Next">
Next
</a>
</nav>
</article>
</div>
</div>
```
Refactor in pagination view to use tag helpers | ```c#
@model Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination.PaginationInfo
<div class="esh-pager">
<div class="container">
<article class="esh-pager-wrapper row">
<nav>
<a class="esh-pager-item esh-pager-item--navigable @Model.Previous"
id="Previous"
asp-controller="Catalog"
asp-action="Index"
asp-route-page="@(Model.ActualPage -1)"
aria-label="Previous">
Previous
</a>
<span class="esh-pager-item">
Showing @Model.ItemsPerPage of @Model.TotalItems products - Page @(Model.ActualPage + 1) - @Model.TotalPages
</span>
<a class="esh-pager-item esh-pager-item--navigable @Model.Next"
id="Next"
asp-controller="Catalog"
asp-action="Index"
asp-route-page="@(Model.ActualPage + 1)"
aria-label="Next">
Next
</a>
</nav>
</article>
</div>
</div>
``` |
4d24799c-56c4-464b-9bb2-1547debcf218 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Duplicati.Library.Main;
using NUnit.Framework;
namespace Duplicati.UnitTest
{
[TestFixture]
public class RepairHandlerTests : BasicSetupHelper
{
public override void SetUp()
{
base.SetUp();
File.WriteAllBytes(Path.Combine(this.DATAFOLDER, "emptyFile"), new byte[] {0});
}
[Test]
[Category("RepairHandler")]
[TestCase("true")]
[TestCase("false")]
public void RepairMissingIndexFiles(string noEncryption)
{
Dictionary<string, string> options = new Dictionary<string, string>(this.TestOptions) {["no-encryption"] = noEncryption};
using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null))
{
c.Backup(new[] {this.DATAFOLDER});
}
string[] dindexFiles = Directory.EnumerateFiles(this.TARGETFOLDER, "*dindex*").ToArray();
Assert.Greater(dindexFiles.Length, 0);
foreach (string f in dindexFiles)
{
File.Delete(f);
}
using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null))
{
c.Repair();
}
foreach (string file in dindexFiles)
{
Assert.IsTrue(File.Exists(Path.Combine(this.TARGETFOLDER, file)));
}
}
}
}```
Fix poorly named test file. | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Duplicati.Library.Main;
using NUnit.Framework;
namespace Duplicati.UnitTest
{
[TestFixture]
public class RepairHandlerTests : BasicSetupHelper
{
public override void SetUp()
{
base.SetUp();
File.WriteAllBytes(Path.Combine(this.DATAFOLDER, "file"), new byte[] {0});
}
[Test]
[Category("RepairHandler")]
[TestCase("true")]
[TestCase("false")]
public void RepairMissingIndexFiles(string noEncryption)
{
Dictionary<string, string> options = new Dictionary<string, string>(this.TestOptions) {["no-encryption"] = noEncryption};
using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null))
{
c.Backup(new[] {this.DATAFOLDER});
}
string[] dindexFiles = Directory.EnumerateFiles(this.TARGETFOLDER, "*dindex*").ToArray();
Assert.Greater(dindexFiles.Length, 0);
foreach (string f in dindexFiles)
{
File.Delete(f);
}
using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null))
{
c.Repair();
}
foreach (string file in dindexFiles)
{
Assert.IsTrue(File.Exists(Path.Combine(this.TARGETFOLDER, file)));
}
}
}
}``` |
99700bcb-769e-4ee6-8b97-ea3588a69104 | {
"language": "C#"
} | ```c#
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Avalonia.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
}
public Control GetControl(Type type)
{
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
else
{
throw new Exception($"Can not find factory method for type: {type}");
}
}
return control;
}
public void SetContent(object value)
{
Control control = null;
if (value != null)
{
control = GetControl(value.GetType());
}
this.Content = control;
}
}
}
```
Use CreateChild to override child creation | ```c#
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Avalonia.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => Content = value);
}
protected override IControl CreateChild()
{
var content = Content;
if (content != null)
{
Type type = content.GetType();
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
else
{
throw new Exception($"Can not find factory method for type: {type}");
}
}
return control;
}
return base.CreateChild();
}
}
}
``` |
1a8ee63c-11bf-4c6f-8f14-6454ff472348 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
}```
Add todo about shifting where messages are to be resolved | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
// TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
}``` |
69b11cf1-e9f9-4a44-81b2-f9a076539c5d | {
"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("SimpleZipCode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleZipCode")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("f5a869d6-0f69-4c26-bee2-917e3da08061")]
// 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.2")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
Change version number to auto-increment | ```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("SimpleZipCode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyProduct("SimpleZipCode")]
[assembly: AssemblyCopyright("Copyright © 2017")]
// 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("f5a869d6-0f69-4c26-bee2-917e3da08061")]
// 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.*")]
``` |
5cacb4fd-5572-4c70-96c2-5599b9a8c0d4 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using SFA.DAS.Reservations.Api.Types.Configuration;
namespace SFA.DAS.Reservations.Api.Types
{
public class ReservationHelper : IReservationHelper
{
private readonly ReservationsClientApiConfiguration _config;
public ReservationHelper(ReservationsClientApiConfiguration config)
{
_config = config;
}
public Task<ReservationValidationResult> ValidateReservation(ValidationReservationMessage request, Func<string, object, Task<ReservationValidationResult>> call)
{
var effectiveApiBaseUrl = _config.EffectiveApiBaseUrl.TrimEnd(new[] {'/'});
var url = $"{effectiveApiBaseUrl}/api/reservations/validate/{request.ReservationId}?courseCode={request.CourseCode}&startDate={request.StartDate}";
var data = new
{
StartDate = request.StartDate.ToString("yyyy-MM-dd"),
request.CourseCode
};
return call(url, data);
}
}
}```
Remove explicit parameters from the reservation query string | ```c#
using System;
using System.Threading.Tasks;
using SFA.DAS.Reservations.Api.Types.Configuration;
namespace SFA.DAS.Reservations.Api.Types
{
public class ReservationHelper : IReservationHelper
{
private readonly ReservationsClientApiConfiguration _config;
public ReservationHelper(ReservationsClientApiConfiguration config)
{
_config = config;
}
public Task<ReservationValidationResult> ValidateReservation(ValidationReservationMessage request, Func<string, object, Task<ReservationValidationResult>> call)
{
var effectiveApiBaseUrl = _config.EffectiveApiBaseUrl.TrimEnd(new[] {'/'});
var url = $"{effectiveApiBaseUrl}/api/reservations/validate/{request.ReservationId}";
var data = new
{
StartDate = request.StartDate.ToString("yyyy-MM-dd"),
request.CourseCode
};
return call(url, data);
}
}
}``` |
46264a2b-08c0-4125-b721-d96a4350a026 | {
"language": "C#"
} | ```c#
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Windows Azure Compute Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Windows Azure Virtual Machines and Hosted Services.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Windows Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
```
Change Assembly Version to 2.3.0.0 | ```c#
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Windows Azure Compute Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Windows Azure Virtual Machines and Hosted Services.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Windows Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
``` |
729e4867-4241-4b06-807e-93fcc9d94e2c | {
"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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
req.AddParameter(@"password", Password, RequestParameterType.Query);
return req;
}
protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
```
Fix inability to join a multiplayer room which has no password | ```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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
if (!string.IsNullOrEmpty(Password))
req.AddParameter(@"password", Password, RequestParameterType.Query);
return req;
}
protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
``` |
4f270ae3-88ca-4cbd-8367-0df37daeb738 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Vidly.Models;
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
public ActionResult Index()
{
var customers = GetCustomers();
return View(customers);
}
//[Route("Customers/Details/{id}")]
public ActionResult Details(int id)
{
var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
private IEnumerable<Customer> GetCustomers()
{
return new List<Customer>
{
new Customer() {Id = 1, Name = "John Smith"},
new Customer() {Id = 2, Name = "Mary Williams"}
};
}
}
}```
Load customers from the database. | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Vidly.Models;
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult Index()
{
var customers = _context.Customers.ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
}
}``` |
27b57c9d-8054-4e51-9f53-d5f89858e0da | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Welcome to the Utilities code base. This _README.cs file is your table of contents.
//
// You will notice that the code is littered with code: qualifiers. If you install the 'hyperAddin' for
// Visual Studio, these qualifiers turn into hyperlinks that allow easy cross references. The hyperAddin is
// available on http://www.codeplex.com/hyperAddin
//
// -------------------------------------------------------------------------------------
// Overview of files
//
// * file:GrowableArray.cs - holds a VERY LEAN implentation of a variable sized array (it is
// striped down, fast version of List<T>. There is never a reason to implement this logic by hand.
//
// * file:StreamUtilities.cs holds code:StreamUtilities which knows how to copy a stream.
//
// * file:FastSerialization.cs - holds defintions for code:FastSerialization.Serializer and
// code:FastSerialization.Deserializer which are general purpose, very fast and efficient ways of dumping
// an object graph to a stream (typically a file). It is used as a very convinient, versionable,
// efficient and extensible file format.
//
// * file:StreamReaderWriter.cs - holds concreate subclasses of
// code:FastSerialization.IStreamReader and code:FastSerialization.IStreamWriter, which allow you to
// write files a byte, chareter, int, or string at a time efficiently.```
Update Readme for FastSerialization to fix a typo | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Welcome to the Utilities code base. This _README.cs file is your table of contents.
//
// You will notice that the code is littered with code: qualifiers. If you install the 'hyperAddin' for
// Visual Studio, these qualifiers turn into hyperlinks that allow easy cross references. The hyperAddin is
// available on http://www.codeplex.com/hyperAddin
//
// -------------------------------------------------------------------------------------
// Overview of files
//
// * file:GrowableArray.cs - holds a VERY LEAN implentation of a variable sized array (it is
// striped down, fast version of List<T>. There is never a reason to implement this logic by hand.
//
// * file:StreamUtilities.cs holds code:StreamUtilities which knows how to copy a stream.
//
// * file:FastSerialization.cs - holds defintions for code:FastSerialization.Serializer and
// code:FastSerialization.Deserializer which are general purpose, very fast and efficient ways of dumping
// an object graph to a stream (typically a file). It is used as a very convenient, versionable,
// efficient and extensible file format.
//
// * file:StreamReaderWriter.cs - holds concreate subclasses of
// code:FastSerialization.IStreamReader and code:FastSerialization.IStreamWriter, which allow you to
// write files a byte, chareter, int, or string at a time efficiently.
``` |
2ad9c31b-c47b-4627-8a48-7b4077ecd0fe | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder());
}
protected override TimingControlPoint CreateTimingControlPoint()
=> new LegacyDifficultyCalculatorTimingControlPoint();
private class LegacyDifficultyCalculatorTimingControlPoint : TimingControlPoint
{
public LegacyDifficultyCalculatorTimingControlPoint()
{
BeatLengthBindable.MinValue = double.MinValue;
BeatLengthBindable.MaxValue = double.MaxValue;
}
}
}
}
```
Remove unlimited timing points in difficulty calculation | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder());
}
}
}
``` |
6a453ca5-7888-4686-96d3-e18eaf2f0d78 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using PythonScripting.Resources;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using IronPython.Compiler;
namespace PythonScripting
{
public class ScriptExecutor : Component, ICmpInitializable
{
public ContentRef<PythonScript> Script { get; set; }
public void OnInit(InitContext context)
{
if (context == InitContext.Activate)
{
}
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
```
Add placeholder support for OnUpdate | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Duality;
using PythonScripting.Resources;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace PythonScripting
{
public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable
{
public ContentRef<PythonScript> Script { get; set; }
public void OnInit(InitContext context)
{
if (context == InitContext.Activate)
{
}
}
public void OnUpdate()
{
}
public void OnShutdown(ShutdownContext context)
{
if (context == ShutdownContext.Deactivate)
{
GameObj.DisposeLater();
}
}
}
}
``` |
693c0abe-320d-42be-988c-23376397053a | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
Vector3 movement;
Rigidbody rb;
float cameraRayLength = 100;
int floorMask;
void Awake()
{
floorMask = LayerMask.GetMask ("Floor");
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxisRaw ("Horizontal");
float moveVertical = Input.GetAxisRaw ("Vertical");
Move (moveHorizontal, moveVertical);
Turning ();
}
void Move(float horizontal, float vertical)
{
movement.Set (horizontal, 0f, vertical);
movement = movement * speed * Time.deltaTime;
rb.MovePosition (transform.position + movement);
}
void Turning()
{
Ray cameraRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (cameraRay, out floorHit, cameraRayLength, floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
rb.MoveRotation (newRotation);
}
}
}
```
Change movement, player folow mouse | ```c#
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private CharacterController cc;
private float cameraRayLength = 100;
private int floorMask;
void Awake()
{
floorMask = LayerMask.GetMask ("Floor");
cc = GetComponent<CharacterController> ();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxisRaw ("Horizontal");
float moveVertical = Input.GetAxisRaw ("Vertical");
Move (moveHorizontal, moveVertical);
Turning ();
}
void Move(float horizontal, float vertical)
{
if (cc.isGrounded) {
moveDirection = new Vector3(horizontal, 0, vertical);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
cc.Move(moveDirection * Time.deltaTime);
}
void Turning()
{
Ray cameraRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (cameraRay, out floorHit, cameraRayLength, floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
transform.rotation = newRotation;
}
}
}
``` |
35479634-9089-4825-aecb-594d716a108a | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LegoSharp;
using System.Linq;
using System.Reflection;
using System.IO.MemoryMappedFiles;
namespace LegoSharpTest
{
[TestClass]
public class ReadmeTests
{
[TestMethod]
public async Task PickABrickExample()
{
LegoGraphClient graphClient = new LegoGraphClient();
await graphClient.authenticateAsync();
PickABrickQuery query = new PickABrickQuery();
query.addFilter(new BrickColorFilter()
.addValue(BrickColor.Black)
);
query.query = "wheel";
PickABrickQueryResult result = await graphClient.pickABrick(query);
foreach (Brick brick in result.elements)
{
// do something with each brick
}
}
[TestMethod]
public async Task ProductSearchExample()
{
LegoGraphClient graphClient = new LegoGraphClient();
await graphClient.authenticateAsync();
ProductSearchQuery query = new ProductSearchQuery();
query.addFilter(new ProductCategoryFilter()
.addValue(ProductCategory.Sets)
);
query.query = "train";
await graphClient.productSearch(query);
}
}
}
```
Fix bad casing for readme tests | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LegoSharp;
using System.Linq;
using System.Reflection;
using System.IO.MemoryMappedFiles;
namespace LegoSharpTest
{
[TestClass]
public class ReadmeTests
{
[TestMethod]
public async Task pickABrickExample()
{
LegoGraphClient graphClient = new LegoGraphClient();
await graphClient.authenticateAsync();
PickABrickQuery query = new PickABrickQuery();
query.addFilter(new BrickColorFilter()
.addValue(BrickColor.Black)
);
query.query = "wheel";
PickABrickQueryResult result = await graphClient.pickABrick(query);
foreach (Brick brick in result.elements)
{
// do something with each brick
}
}
[TestMethod]
public async Task productSearchExample()
{
LegoGraphClient graphClient = new LegoGraphClient();
await graphClient.authenticateAsync();
ProductSearchQuery query = new ProductSearchQuery();
query.addFilter(new ProductCategoryFilter()
.addValue(ProductCategory.Sets)
);
query.query = "train";
await graphClient.productSearch(query);
}
}
}
``` |
63fe5244-973c-4ed8-a89e-1b32a5f6eb1a | {
"language": "C#"
} | ```c#
using System;
namespace Terraria_Server.Messages
{
public class SummonSkeletronMessage : IMessage
{
public Packet GetPacket()
{
return Packet.SUMMON_SKELETRON;
}
public void Process(int start, int length, int num, int whoAmI, byte[] readBuffer, byte bufferData)
{
byte action = readBuffer[num];
if (action == 1)
{
NPC.SpawnSkeletron();
}
else if (action == 2)
{
NetMessage.SendData (51, -1, whoAmI, "", action, (float)readBuffer[num + 1], 0f, 0f, 0);
}
}
}
}
```
Fix Skeletron summoning message decoding. | ```c#
using System;
namespace Terraria_Server.Messages
{
public class SummonSkeletronMessage : IMessage
{
public Packet GetPacket()
{
return Packet.SUMMON_SKELETRON;
}
public void Process(int start, int length, int num, int whoAmI, byte[] readBuffer, byte bufferData)
{
int player = readBuffer[num++]; //TODO: maybe check for forgery
byte action = readBuffer[num];
if (action == 1)
{
NPC.SpawnSkeletron();
}
else if (action == 2)
{
NetMessage.SendData (51, -1, whoAmI, "", player, action, 0f, 0f, 0);
}
}
}
}
``` |
5a357c3a-5da9-4976-9068-4196211f7a82 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class KiaiFlash : BeatSyncedContainer
{
private const double fade_length = 80;
private const float flash_opacity = 0.25f;
public KiaiFlash()
{
EarlyActivationMilliseconds = 80;
Blending = BlendingParameters.Additive;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Alpha = 0f,
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
Child
.FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint)
.Then()
.FadeOut(Math.Max(0, timingPoint.BeatLength - fade_length), Easing.OutSine);
}
}
}
```
Use a minimum fade length for clamping rather than zero | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class KiaiFlash : BeatSyncedContainer
{
private const double fade_length = 80;
private const float flash_opacity = 0.25f;
public KiaiFlash()
{
EarlyActivationMilliseconds = 80;
Blending = BlendingParameters.Additive;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Alpha = 0f,
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
Child
.FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint)
.Then()
.FadeOut(Math.Max(fade_length, timingPoint.BeatLength - fade_length), Easing.OutSine);
}
}
}
``` |
3d815317-36e4-4a6c-b85a-10541e9121fc | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[PropertyOrder(0)]
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
[PropertyOrder(1)]
[DisplayName("Show Errors")]
public bool ShowErrors { get; set; } = false;
public void Execute()
{
DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
if (ShowErrors)
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
image: MessageBoxImage.Error);
}
});
}
protected virtual void ExecuteAction()
{
}
}
}```
Add action "Works If Muted", "Works If Foreground Is Fullscreen" options | ```c#
using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[PropertyOrder(0)]
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
[PropertyOrder(1)]
[DisplayName("Works If Foreground Is Fullscreen")]
public bool WorksIfForegroundIsFullscreen { get; set; }
[PropertyOrder(2)]
[DisplayName("Works If Muted")]
public bool WorksIfMuted { get; set; }
[PropertyOrder(3)]
[DisplayName("Show Errors")]
public bool ShowErrors { get; set; } = false;
public void Execute()
{
if (!WorksIfMuted && App.IsMuted ||
(!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp()))
return;
DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
if (ShowErrors)
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
image: MessageBoxImage.Error);
}
});
}
protected virtual void ExecuteAction()
{
}
}
}``` |
d392b09c-2579-41d5-9941-f5fdd0c289e0 | {
"language": "C#"
} | ```c#
using Xamarin.Forms;
namespace AppShell.Mobile.Views
{
[ContentProperty("ShellContent")]
public partial class ShellView : ContentView
{
public static readonly BindableProperty ShellContentProperty = BindableProperty.Create<ShellView, View>(d => d.ShellContent, null, propertyChanged: ShellContentPropertyChanged);
public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.Create<ShellView, bool>(x => x.HasNavigationBar, true, propertyChanged: OnHasNavigationBarChanged);
public View ShellContent { get { return (View)GetValue(ShellContentProperty); } set { SetValue(ShellContentProperty, value); } }
public bool HasNavigationBar { get { return (bool)GetValue(HasNavigationBarProperty); } set { SetValue(HasNavigationBarProperty, value); } }
public static void ShellContentPropertyChanged(BindableObject d, View oldValue, View newValue)
{
ShellView shellView = d as ShellView;
shellView.ShellContent = newValue;
}
private static void OnHasNavigationBarChanged(BindableObject d, bool oldValue, bool newValue)
{
ShellView shellView = d as ShellView;
NavigationPage.SetHasNavigationBar(shellView, newValue);
if (!newValue)
shellView.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
}
public ShellView()
{
InitializeComponent();
SetBinding(HasNavigationBarProperty, new Binding("HasNavigationBar"));
}
}
}
```
Revert "Fixed compile error in shell view" | ```c#
using Xamarin.Forms;
namespace AppShell.Mobile.Views
{
[ContentProperty("ShellContent")]
public partial class ShellView : ContentView
{
public static readonly BindableProperty ShellContentProperty = BindableProperty.Create<ShellView, View>(d => d.ShellContent, null, propertyChanged: ShellContentPropertyChanged);
public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.Create<ShellView, bool>(x => x.HasNavigationBar, true, propertyChanged: OnHasNavigationBarChanged);
public View ShellContent { get { return (View)GetValue(ShellContentProperty); } set { SetValue(ShellContentProperty, value); } }
public bool HasNavigationBar { get { return (bool)GetValue(HasNavigationBarProperty); } set { SetValue(HasNavigationBarProperty, value); } }
public static void ShellContentPropertyChanged(BindableObject d, View oldValue, View newValue)
{
ShellView shellView = d as ShellView;
shellView.ShellContentView.Content = newValue;
}
private static void OnHasNavigationBarChanged(BindableObject d, bool oldValue, bool newValue)
{
ShellView shellView = d as ShellView;
NavigationPage.SetHasNavigationBar(shellView, newValue);
if (!newValue)
shellView.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
}
public ShellView()
{
InitializeComponent();
SetBinding(HasNavigationBarProperty, new Binding("HasNavigationBar"));
}
}
}
``` |
8ac5bd42-1b40-401a-a592-c870a8863bcc | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace Meowtrix.osuAMT.Training.DataGenerator
{
class OszArchive : Archive, IDisposable
{
public ZipArchive archive;
private FileInfo fileinfo;
public OszArchive(FileInfo file)
{
fileinfo = file;
string name = file.Name;
Name = name.EndsWith(".osz") ? name.Substring(0, name.Length - 4) : name;
}
public override string Name { get; }
public void Dispose() => archive.Dispose();
private void EnsureArchiveOpened()
{
if (archive == null)
archive = new ZipArchive(fileinfo.OpenRead(), ZipArchiveMode.Read, false);
}
public override Stream OpenFile(string filename)
{
EnsureArchiveOpened();
return archive.GetEntry(filename).Open();
}
public override IEnumerable<Stream> OpenOsuFiles()
{
EnsureArchiveOpened();
return archive.Entries.Where(x => x.Name.EndsWith(".osu")).Select(e => e.Open());
}
}
}
```
Copy deflate stream to temporary memory stream. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace Meowtrix.osuAMT.Training.DataGenerator
{
class OszArchive : Archive, IDisposable
{
public ZipArchive archive;
private FileInfo fileinfo;
public OszArchive(FileInfo file)
{
fileinfo = file;
string name = file.Name;
Name = name.EndsWith(".osz") ? name.Substring(0, name.Length - 4) : name;
}
public override string Name { get; }
public void Dispose() => archive.Dispose();
private void EnsureArchiveOpened()
{
if (archive == null)
archive = new ZipArchive(fileinfo.OpenRead(), ZipArchiveMode.Read, false);
}
public override Stream OpenFile(string filename)
{
EnsureArchiveOpened();
var temp = new MemoryStream();
using (var deflate = archive.GetEntry(filename).Open())
{
deflate.CopyTo(temp);
temp.Seek(0, SeekOrigin.Begin);
return temp;
}
}
public override IEnumerable<Stream> OpenOsuFiles()
{
EnsureArchiveOpened();
return archive.Entries.Where(x => x.Name.EndsWith(".osu")).Select(e => e.Open());
}
}
}
``` |
534e29e7-51a5-4f64-a29e-b5e2e9c24cff | {
"language": "C#"
} | ```c#
using System.Net.Http.Formatting;
using System.Web.Http.ModelBinding;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.Trees;
using Umbraco.Web.WebApi.Filters;
namespace uSync8.BackOffice.Controllers.Trees
{
[Tree(Constants.Applications.Settings, uSync.Trees.uSync,
TreeGroup = uSync.Trees.Group,
TreeTitle = uSync.Name, SortOrder = 35)]
[PluginController(uSync.Name)]
public class uSyncTreeController : TreeController
{
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
root.RoutePath = $"{Constants.Applications.Settings}/{uSync.Trees.uSync}/dashboard";
root.Icon = "icon-infinity";
root.HasChildren = false;
root.MenuUrl = null;
return root;
}
protected override MenuItemCollection GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings)
{
return null;
}
protected override TreeNodeCollection GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings)
{
return new TreeNodeCollection();
}
}
}
```
Remove reference to settings section in routePath (so we can move the tree in theory) | ```c#
using System.Net.Http.Formatting;
using System.Web.Http.ModelBinding;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.Trees;
using Umbraco.Web.WebApi.Filters;
namespace uSync8.BackOffice.Controllers.Trees
{
[Tree(Constants.Applications.Settings, uSync.Trees.uSync,
TreeGroup = uSync.Trees.Group,
TreeTitle = uSync.Name, SortOrder = 35)]
[PluginController(uSync.Name)]
public class uSyncTreeController : TreeController
{
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
root.RoutePath = $"{this.SectionAlias}/{uSync.Trees.uSync}/dashboard";
root.Icon = "icon-infinity";
root.HasChildren = false;
root.MenuUrl = null;
return root;
}
protected override MenuItemCollection GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings)
{
return null;
}
protected override TreeNodeCollection GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings)
{
return new TreeNodeCollection();
}
}
}
``` |
272ee457-90cb-43e8-bbdd-6a83ec9ecf4a | {
"language": "C#"
} | ```c#
using RethinkDb.DatumConverters;
namespace RethinkDb.Newtonsoft.Configuration
{
public class NewtonSerializer : AggregateDatumConverterFactory
{
public NewtonSerializer() : base(
PrimitiveDatumConverterFactory.Instance,
TupleDatumConverterFactory.Instance,
AnonymousTypeDatumConverterFactory.Instance,
BoundEnumDatumConverterFactory.Instance,
NullableDatumConverterFactory.Instance,
NewtonsoftDatumConverterFactory.Instance
)
{
}
}
}
```
Add NamedValueDictionaryDatumConverterFactory to newtonsoft converter | ```c#
using RethinkDb.DatumConverters;
namespace RethinkDb.Newtonsoft.Configuration
{
public class NewtonSerializer : AggregateDatumConverterFactory
{
public NewtonSerializer() : base(
PrimitiveDatumConverterFactory.Instance,
TupleDatumConverterFactory.Instance,
AnonymousTypeDatumConverterFactory.Instance,
BoundEnumDatumConverterFactory.Instance,
NullableDatumConverterFactory.Instance,
NamedValueDictionaryDatumConverterFactory.Instance,
NewtonsoftDatumConverterFactory.Instance
)
{
}
}
}
``` |
4d7fbf78-912c-424e-b10a-44edfe6beaca | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ExRam.Gremlinq.Core.Projections;
using ExRam.Gremlinq.Core.Steps;
namespace ExRam.Gremlinq.Core
{
public static class EnumerableExtensions
{
public static Traversal ToTraversal(this IEnumerable<Step> steps) => new(
steps is Step[] array
? (Step[])array.Clone()
: steps.ToArray(),
Projection.Empty);
internal static bool InternalAny(this IEnumerable enumerable)
{
var enumerator = enumerable.GetEnumerator();
return enumerator.MoveNext();
}
internal static IAsyncEnumerable<TElement> ToNonNullAsyncEnumerable<TElement>(this IEnumerable enumerable)
{
return AsyncEnumerable.Create(Core);
async IAsyncEnumerator<TElement> Core(CancellationToken ct)
{
foreach (TElement element in enumerable)
{
ct.ThrowIfCancellationRequested();
if (element is not null)
yield return element;
}
}
}
}
}
```
Rework InternalAny to take IDisposables into account and short-cut on ICollections. | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ExRam.Gremlinq.Core.Projections;
using ExRam.Gremlinq.Core.Steps;
namespace ExRam.Gremlinq.Core
{
public static class EnumerableExtensions
{
public static Traversal ToTraversal(this IEnumerable<Step> steps) => new(
steps is Step[] array
? (Step[])array.Clone()
: steps.ToArray(),
Projection.Empty);
internal static bool InternalAny(this IEnumerable enumerable)
{
if (enumerable is ICollection collection)
return collection.Count > 0;
var enumerator = enumerable.GetEnumerator();
try
{
return enumerator.MoveNext();
}
finally
{
if (enumerator is IDisposable disposable)
disposable.Dispose();
}
}
internal static IAsyncEnumerable<TElement> ToNonNullAsyncEnumerable<TElement>(this IEnumerable enumerable)
{
return AsyncEnumerable.Create(Core);
async IAsyncEnumerator<TElement> Core(CancellationToken ct)
{
foreach (TElement element in enumerable)
{
ct.ThrowIfCancellationRequested();
if (element is not null)
yield return element;
}
}
}
}
}
``` |
108e5b47-2d5a-4054-a54d-6dcefc7195cf | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using HarryPotterUnity.Tween;
using UnityEngine;
namespace HarryPotterUnity.Utils
{
public static class GameManager {
public const int PreviewLayer = 9;
public const int CardLayer = 10;
public const int ValidChoiceLayer = 11;
public const int IgnoreRaycastLayer = 2;
public const int DeckLayer = 12;
public static byte NetworkIdCounter;
public static readonly List<GenericCard> AllCards = new List<GenericCard>();
public static Camera PreviewCamera;
public static readonly TweenQueue TweenQueue = new TweenQueue();
public static void DisableCards(List<GenericCard> cards)
{
cards.ForEach(card => card.Disable());
}
public static void EnableCards(List<GenericCard> cards)
{
cards.ForEach(card => card.Enable());
}
}
}
```
Rename some variables for consistency | ```c#
using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using HarryPotterUnity.Tween;
using UnityEngine;
namespace HarryPotterUnity.Utils
{
public static class GameManager {
public const int PREVIEW_LAYER = 9;
public const int CARD_LAYER = 10;
public const int VALID_CHOICE_LAYER = 11;
public const int IGNORE_RAYCAST_LAYER = 2;
public const int DECK_LAYER = 12;
public static byte _networkIdCounter;
public static readonly List<GenericCard> AllCards = new List<GenericCard>();
public static Camera _previewCamera;
public static readonly TweenQueue TweenQueue = new TweenQueue();
public static void DisableCards(List<GenericCard> cards)
{
cards.ForEach(card => card.Disable());
}
public static void EnableCards(List<GenericCard> cards)
{
cards.ForEach(card => card.Enable());
}
}
}
``` |
b3f6a20c-e0ee-4494-a98d-d01cfa47eca3 | {
"language": "C#"
} | ```c#
using System;
namespace Table {
public class Table {
public int Width;
public int Spacing;
public Table(int width, int spacing) {
Width = width;
Spacing = spacing;
}
}
}
```
Make the namespace uniform accross the project | ```c#
using System;
namespace Hangman {
public class Table {
public int Width;
public int Spacing;
public Table(int width, int spacing) {
Width = width;
Spacing = spacing;
}
}
}
``` |
64dd0a83-068b-4a39-b917-a9651738edec | {
"language": "C#"
} | ```c#
using System;
using Mono.VisualC.Interop;
using Mono.VisualC.Interop.ABI;
namespace Qt {
// Will be internal; public for testing
public static class Libs {
public static CppLibrary QtCore = null;
public static CppLibrary QtGui = null;
static Libs ()
{
string lib;
CppAbi abi;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{ // for Windows...
lib = "{0}d4.dll";
abi = new MsvcAbi ();
} else { // for Mac...
lib = "/Library/Frameworks/{0}.framework/Versions/Current/{0}";
abi = new ItaniumAbi ();
}
QtCore = new CppLibrary (string.Format(lib, "QtCore"), abi);
QtGui = new CppLibrary (string.Format(lib, "QtGui"), abi);
}
}
}
```
Use proper library/abi for qt on linux. | ```c#
using System;
using Mono.VisualC.Interop;
using Mono.VisualC.Interop.ABI;
namespace Qt {
// Will be internal; public for testing
public static class Libs {
public static CppLibrary QtCore = null;
public static CppLibrary QtGui = null;
static Libs ()
{
string lib;
CppAbi abi;
if (Environment.OSVersion.Platform == PlatformID.Unix) {
lib = "{0}.so";
abi = new ItaniumAbi ();
} else if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{ // for Windows...
lib = "{0}d4.dll";
abi = new MsvcAbi ();
} else { // for Mac...
lib = "/Library/Frameworks/{0}.framework/Versions/Current/{0}";
abi = new ItaniumAbi ();
}
QtCore = new CppLibrary (string.Format(lib, "QtCore"), abi);
QtGui = new CppLibrary (string.Format(lib, "QtGui"), abi);
}
}
}
``` |
aad3436e-f942-4f6e-ae82-7ec6decbbdef | {
"language": "C#"
} | ```c#
@using RightpointLabs.ConferenceRoom.Domain
@model IEnumerable<RightpointLabs.ConferenceRoom.Domain.Models.Entities.DeviceEntity>
@{
var buildings = (Dictionary<string, string>)ViewBag.Buildings;
var rooms = (Dictionary<string, string>)ViewBag.Rooms;
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.BuildingId)
</th>
<th>
@Html.DisplayNameFor(model => model.ControlledRoomIds)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@buildings.TryGetValue(item.Id)
</td>
<td>
@(null == item.BuildingId ? "" : buildings.TryGetValue(item.BuildingId))
</td>
<td>
@string.Join(", ", item.ControlledRoomIds.Select(_ => rooms.TryGetValue(_)))
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
```
Fix up some room display issues | ```c#
@using RightpointLabs.ConferenceRoom.Domain
@model IEnumerable<RightpointLabs.ConferenceRoom.Domain.Models.Entities.DeviceEntity>
@{
var buildings = (Dictionary<string, string>)ViewBag.Buildings;
var rooms = (Dictionary<string, string>)ViewBag.Rooms;
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.BuildingId)
</th>
<th>
@Html.DisplayNameFor(model => model.ControlledRoomIds)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@item.Id
</td>
<td>
@(null == item.BuildingId ? "" : buildings.TryGetValue(item.BuildingId))
</td>
<td>
@string.Join(", ", (item.ControlledRoomIds ?? new string[0]).Select(_ => rooms.TryGetValue(_)))
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
``` |
28d596d3-2e6e-4282-8db8-341d99598643 | {
"language": "C#"
} | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace CefSharp.Wpf.Rendering
{
public class InteropBitmapInfo : WpfBitmapInfo
{
private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32;
public InteropBitmap Bitmap { get; private set; }
public InteropBitmapInfo()
{
BytesPerPixel = PixelFormat.BitsPerPixel / 8;
}
public override bool CreateNewBitmap
{
get { return Bitmap == null; }
}
public override void ClearBitmap()
{
Bitmap = null;
}
public override void Invalidate()
{
if (Bitmap != null)
{
Bitmap.Invalidate();
}
}
public override BitmapSource CreateBitmap()
{
var stride = Width * BytesPerPixel;
if (FileMappingHandle == IntPtr.Zero)
{
ClearBitmap();
}
else
{
Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0);
}
return Bitmap;
}
}
}
```
Return null immediately if file handle is not valid | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace CefSharp.Wpf.Rendering
{
public class InteropBitmapInfo : WpfBitmapInfo
{
private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32;
public InteropBitmap Bitmap { get; private set; }
public InteropBitmapInfo()
{
BytesPerPixel = PixelFormat.BitsPerPixel / 8;
}
public override bool CreateNewBitmap
{
get { return Bitmap == null; }
}
public override void ClearBitmap()
{
Bitmap = null;
}
public override void Invalidate()
{
if (Bitmap != null)
{
Bitmap.Invalidate();
}
}
public override BitmapSource CreateBitmap()
{
var stride = Width * BytesPerPixel;
// Unable to create bitmap without valid File Handle (Most likely control is being disposed)
if (FileMappingHandle == IntPtr.Zero)
{
return null;
}
else
{
Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0);
}
return Bitmap;
}
}
}
``` |
62835331-5916-40fb-8475-72d2d10cc809 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
namespace AdoNetProfiler
{
/// <summary>
/// The factory to create the object of <see cref="IProfiler"/>.
/// </summary>
public class AdoNetProfilerFactory
{
// ConstructorInfo is faster than Func<IProfiler> when invoking.
private static ConstructorInfo _constructor;
/// <summary>
/// Initialize the setting for profiling of database accessing with ADO.NET.
/// </summary>
/// <param name="profilerType">The type to implement <see cref="IProfiler"/>.</param>
public static void Initialize(Type profilerType)
{
if (profilerType == null)
throw new ArgumentNullException(nameof(profilerType));
if (profilerType != typeof(IProfiler))
throw new ArgumentException($"The type must be {typeof(IProfiler).FullName}.", nameof(profilerType));
var constructor = profilerType.GetConstructor(Type.EmptyTypes);
if (constructor == null)
throw new InvalidOperationException("There is no default constructor. The profiler must have it.");
_constructor = constructor;
}
public static IProfiler GetProfiler()
{
return (IProfiler)_constructor.Invoke(null);
}
}
}```
Use the lock in the factory class. | ```c#
using System;
using System.Reflection;
using System.Threading;
namespace AdoNetProfiler
{
/// <summary>
/// The factory to create the object of <see cref="IProfiler"/>.
/// </summary>
public class AdoNetProfilerFactory
{
// ConstructorInfo is faster than Func<IProfiler> when invoking.
private static ConstructorInfo _constructor;
private static bool _initialized = false;
private static readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim();
/// <summary>
/// Initialize the setting for profiling of database accessing with ADO.NET.
/// </summary>
/// <param name="profilerType">The type to implement <see cref="IProfiler"/>.</param>
public static void Initialize(Type profilerType)
{
if (profilerType == null)
throw new ArgumentNullException(nameof(profilerType));
if (profilerType != typeof(IProfiler))
throw new ArgumentException($"The type must be {typeof(IProfiler).FullName}.", nameof(profilerType));
_readerWriterLockSlim.ExecuteWithReadLock(() =>
{
if (_initialized)
throw new InvalidOperationException("This factory class has already initialized.");
var constructor = profilerType.GetConstructor(Type.EmptyTypes);
if (constructor == null)
throw new InvalidOperationException("There is no default constructor. The profiler must have it.");
_constructor = constructor;
_initialized = true;
});
}
public static IProfiler GetProfiler()
{
return _readerWriterLockSlim.ExecuteWithWriteLock(() =>
{
if (!_initialized)
throw new InvalidOperationException("This factory class has not initialized yet.");
return (IProfiler)_constructor.Invoke(null);
});
}
}
}``` |
a79fb848-b83f-4f1e-8fa5-b01883aae5cf | {
"language": "C#"
} | ```c#
using KenticoInspector.Core.Models;
using System;
using System.Collections.Generic;
namespace KenticoInspector.Core
{
public abstract class AbstractReport : IReport
{
public string Codename => GetCodename(this.GetType());
public static string GetCodename(Type reportType) {
return GetDirectParentNamespace(reportType);
}
public abstract IList<Version> CompatibleVersions { get; }
public virtual IList<Version> IncompatibleVersions => new List<Version>();
public abstract IList<string> Tags { get; }
public abstract ReportResults GetResults();
private static string GetDirectParentNamespace(Type reportType)
{
var fullNameSpace = reportType.Namespace;
var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1;
return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod);
}
}
}
```
Add metadata support to abstract report | ```c#
using KenticoInspector.Core.Models;
using System;
using System.Collections.Generic;
namespace KenticoInspector.Core
{
public abstract class AbstractReport<T> : IReport, IWithMetadata<T> where T : new()
{
public string Codename => GetCodename(this.GetType());
public static string GetCodename(Type reportType) {
return GetDirectParentNamespace(reportType);
}
public abstract IList<Version> CompatibleVersions { get; }
public virtual IList<Version> IncompatibleVersions => new List<Version>();
public abstract IList<string> Tags { get; }
public abstract Metadata<T> Metadata { get; }
public abstract ReportResults GetResults();
private static string GetDirectParentNamespace(Type reportType)
{
var fullNameSpace = reportType.Namespace;
var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1;
return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod);
}
}
}
``` |
2280c9f2-775b-4cb0-8095-514ac0294fee | {
"language": "C#"
} | ```c#
using System;
using System.Web;
using System.Web.Routing;
namespace Cassette
{
public class ModuleRequestHandler<T> : IHttpHandler
where T : Module
{
public ModuleRequestHandler(IModuleContainer<T> moduleContainer, RequestContext requestContext)
{
this.moduleContainer = moduleContainer;
this.requestContext = requestContext;
}
readonly IModuleContainer<T> moduleContainer;
readonly RequestContext requestContext;
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext _)
{
var path = requestContext.RouteData.GetRequiredString("path");
var index = path.LastIndexOf('_');
if (index >= 0)
{
path = path.Substring(0, index);
}
var module = moduleContainer.FindModuleByPath(path);
var response = requestContext.HttpContext.Response;
if (module == null)
{
response.StatusCode = 404;
}
else
{
response.Cache.SetCacheability(HttpCacheability.Public);
response.Cache.SetMaxAge(TimeSpan.FromDays(365));
response.ContentType = module.ContentType;
using (var assetStream = module.Assets[0].OpenStream())
{
assetStream.CopyTo(response.OutputStream);
}
}
}
}
}
```
Move class into correct namespace. | ```c#
using System;
using System.Web;
using System.Web.Routing;
namespace Cassette.Web
{
public class ModuleRequestHandler<T> : IHttpHandler
where T : Module
{
public ModuleRequestHandler(IModuleContainer<T> moduleContainer, RequestContext requestContext)
{
this.moduleContainer = moduleContainer;
this.requestContext = requestContext;
}
readonly IModuleContainer<T> moduleContainer;
readonly RequestContext requestContext;
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext _)
{
var path = requestContext.RouteData.GetRequiredString("path");
var index = path.LastIndexOf('_');
if (index >= 0)
{
path = path.Substring(0, index);
}
var module = moduleContainer.FindModuleByPath(path);
var response = requestContext.HttpContext.Response;
if (module == null)
{
response.StatusCode = 404;
}
else
{
response.Cache.SetCacheability(HttpCacheability.Public);
response.Cache.SetMaxAge(TimeSpan.FromDays(365));
response.ContentType = module.ContentType;
using (var assetStream = module.Assets[0].OpenStream())
{
assetStream.CopyTo(response.OutputStream);
}
}
}
}
}
``` |
a4488031-b015-49c2-a512-d124e260267d | {
"language": "C#"
} | ```c#
// The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp : IDisposable
{
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_Finalize();
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
Tcl_Eval(interp, text);
var result = Tcl_GetStringResult(interp);
return Marshal.PtrToStringAnsi(result);
}
}
}
```
Load Tcl in a cross-platform way | ```c#
// The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp : IDisposable
{
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("tcl8.4")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_Finalize();
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
Tcl_Eval(interp, text);
var result = Tcl_GetStringResult(interp);
return Marshal.PtrToStringAnsi(result);
}
}
}
``` |
91cd15c8-ba30-407e-bb18-fc3a5a7b9333 | {
"language": "C#"
} | ```c#
using System;
using Engine.cgimin.material.simpletexture;
using Engine.cgimin.object3d;
using Engine.cgimin.texture;
using OpenTK;
namespace Mugo
{
class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel
{
private static readonly SimpleTextureMaterial material = new SimpleTextureMaterial();
public float Radius => radius;
public new Matrix4 Transformation {
get { return base.Transformation; }
set { base.Transformation = value; }
}
public void Draw ()
{
material.Draw(this, internalObject.TextureId);
}
}
internal class PizzaModelInternal : ObjLoaderObject3D
{
private const String objFilePath = "data/objects/Pizza.model";
private const String texturePath = "data/textures/Pizza.png";
public PizzaModelInternal () : base (objFilePath)
{
TextureId = TextureManager.LoadTexture (texturePath);
Transformation *= Matrix4.CreateScale (0.2f);
Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90));
Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90));
Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f);
DefaultTransformation = Transformation;
}
public int TextureId { get; private set; }
public Matrix4 DefaultTransformation { get; }
}
}
```
Move scale operation to base constructor. | ```c#
using System;
using Engine.cgimin.material.simpletexture;
using Engine.cgimin.object3d;
using Engine.cgimin.texture;
using OpenTK;
namespace Mugo
{
class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel
{
private static readonly SimpleTextureMaterial material = new SimpleTextureMaterial();
public float Radius => radius;
public new Matrix4 Transformation {
get { return base.Transformation; }
set { base.Transformation = value; }
}
public void Draw ()
{
material.Draw(this, internalObject.TextureId);
}
}
internal class PizzaModelInternal : ObjLoaderObject3D
{
private const String objFilePath = "data/objects/Pizza.model";
private const String texturePath = "data/textures/Pizza.png";
public PizzaModelInternal () : base (objFilePath, 0.2f)
{
TextureId = TextureManager.LoadTexture (texturePath);
Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90));
Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90));
Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f);
DefaultTransformation = Transformation;
}
public int TextureId { get; private set; }
public Matrix4 DefaultTransformation { get; }
}
}
``` |
783b9081-c37b-4185-9642-27ae5cd96997 | {
"language": "C#"
} | ```c#
/*Problem 9. Sum of n Numbers
Write a program that enters a number n and after that enters more n numbers and calculates and prints their sum.
Note: You may need to use a for-loop.
Examples:
numbers sum
3 90
20
60
10
5 6.5
2
-1
-0.5
4
2
1 1
1
*/
using System;
class SumOfNNumbers
{
static void Main()
{
Console.Title = "Sum of n Numbers"; //Changing the title of the console.
Console.Write("Please, enter an integer n: ");
int n = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 1; i <= n; i++)
{
sum += double.Parse(Console.ReadLine());
}
Console.WriteLine("\nsum = " + sum);
Console.ReadKey(); // Keeping the console opened.
}
}```
Update to Problem 9. Sum of n Numbers | ```c#
/*Problem 9. Sum of n Numbers
Write a program that enters a number n and after that enters more n numbers and calculates and prints their sum.
Note: You may need to use a for-loop.
Examples:
numbers sum
3 90
20
60
10
5 6.5
2
-1
-0.5
4
2
1 1
1
*/
using System;
class SumOfNNumbers
{
static void Main()
{
Console.Title = "Sum of n Numbers"; //Changing the title of the console.
Console.Write("Please, enter an integer n and n numbers after that.\nn: ");
int n = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 1; i <= n; i++)
{
Console.Write("number {0}: ", i);
sum += double.Parse(Console.ReadLine());
}
Console.WriteLine("\nsum = " + sum);
Console.ReadKey(); // Keeping the console opened.
}
}``` |
140cba8b-34fc-4169-b302-6d1faf39f1cf | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using AutoFixture.Xunit2;
using Shouldly;
using Xunit;
namespace Lloyd.AzureMailGateway.Models.Tests
{
public class EMailBuilderTests
{
//[Fact]
//public void BuilderShouldReturnNonNullEMailInstance()
//{
// // Arrange
// var builder = new EMailBuilder();
// // Act
// var email = new EMailBuilder().Build();
// // Assert
//}
[Fact]
public void BuildShouldThrowOnInvalidState()
{
// Arrange
var builder = new EMailBuilder();
// Act / Assert
Should.Throw<InvalidOperationException>(() => new EMailBuilder().Build());
}
[Theory, AutoData]
public void BuilderShouldSetToAndFromProperties(Address toAddress, Address fromAddress)
{
// Arrange
var builder = new EMailBuilder();
// Act
builder
.To(toAddress.EMail, toAddress.Name)
.From(fromAddress.EMail, fromAddress.Name);
var email = builder.Build();
// Assert
email.To.Addresses.First().EMail.ShouldBe(toAddress.EMail);
email.To.Addresses.First().Name.ShouldBe(toAddress.Name);
}
}
}```
Remove obsolete unit test (null check - can no longer be null) | ```c#
using System;
using System.Linq;
using AutoFixture.Xunit2;
using Shouldly;
using Xunit;
namespace Lloyd.AzureMailGateway.Models.Tests
{
public class EMailBuilderTests
{
[Fact]
public void BuildShouldThrowOnInvalidState()
{
// Arrange
var builder = new EMailBuilder();
// Act / Assert
Should.Throw<InvalidOperationException>(() => new EMailBuilder().Build());
}
[Theory, AutoData]
public void BuilderShouldSetToAndFromProperties(Address toAddress, Address fromAddress)
{
// Arrange
var builder = new EMailBuilder();
// Act
builder
.To(toAddress.EMail, toAddress.Name)
.From(fromAddress.EMail, fromAddress.Name);
var email = builder.Build();
// Assert
email.To.Addresses.First().EMail.ShouldBe(toAddress.EMail);
email.To.Addresses.First().Name.ShouldBe(toAddress.Name);
}
}
}``` |
5972e32f-4a28-4c4b-927f-ed2db5cfacd8 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RemiCover_UmbrellaBehaviour : MonoBehaviour {
public float verticalPosition;
// Use this for initialization
void Start () {
Cursor.visible = false;
}
// Update is called once per frame
void Update() {
Vector2 mousePosition = CameraHelper.getCursorPosition();
this.transform.position = new Vector2(mousePosition.x, verticalPosition);
}
}
```
Stop umbrella on player loss | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RemiCover_UmbrellaBehaviour : MonoBehaviour {
public float verticalPosition;
// Use this for initialization
void Start () {
Cursor.visible = false;
}
// Update is called once per frame
void Update() {
if (!MicrogameController.instance.getVictory())
return;
Vector2 mousePosition = CameraHelper.getCursorPosition();
this.transform.position = new Vector2(mousePosition.x, verticalPosition);
}
}
``` |
f470d1b1-548e-4f64-acd1-b82cd4520da7 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Mond.Compiler.Expressions;
namespace Mond.Compiler.Parselets
{
class ObjectParselet : IPrefixParselet
{
public Expression Parse(Parser parser, Token token)
{
var values = new List<KeyValuePair<string, Expression>>();
while (!parser.Match(TokenType.RightBrace))
{
var identifier = parser.Take(TokenType.Identifier);
parser.Take(TokenType.Colon);
var value = parser.ParseExpession();
values.Add(new KeyValuePair<string, Expression>(identifier.Contents, value));
if (!parser.Match(TokenType.Comma))
break;
parser.Take(TokenType.Comma);
}
parser.Take(TokenType.RightBrace);
return new ObjectExpression(token, values);
}
}
}
```
Add support for array-like object declarations | ```c#
using System.Collections.Generic;
using Mond.Compiler.Expressions;
namespace Mond.Compiler.Parselets
{
class ObjectParselet : IPrefixParselet
{
public Expression Parse(Parser parser, Token token)
{
var values = new List<KeyValuePair<string, Expression>>();
while (!parser.Match(TokenType.RightBrace))
{
var identifier = parser.Take(TokenType.Identifier);
Expression value;
if (parser.Match(TokenType.Comma) || parser.Match(TokenType.RightBrace))
{
value = new IdentifierExpression(identifier);
}
else
{
parser.Take(TokenType.Colon);
value = parser.ParseExpession();
}
values.Add(new KeyValuePair<string, Expression>(identifier.Contents, value));
if (!parser.Match(TokenType.Comma))
break;
parser.Take(TokenType.Comma);
}
parser.Take(TokenType.RightBrace);
return new ObjectExpression(token, values);
}
}
}
``` |
a7f5c8f9-e311-40ea-a283-b5614031c0bf | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
namespace YGOSharp.Network.Utils
{
public static class BinaryExtensions
{
public static void WriteUnicode(this BinaryWriter writer, string text, int len)
{
byte[] unicode = Encoding.Unicode.GetBytes(text);
byte[] result = new byte[len * 2];
int max = len * 2 - 2;
Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length);
writer.Write(result);
}
public static string ReadUnicode(this BinaryReader reader, int len)
{
byte[] unicode = reader.ReadBytes(len * 2);
string text = Encoding.Unicode.GetString(unicode);
text = text.Substring(0, text.IndexOf('\0'));
return text;
}
public static byte[] ReadToEnd(this BinaryReader reader)
{
return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
}
}
}
```
Fix a crash if we receive a too long unicode string | ```c#
using System;
using System.IO;
using System.Text;
namespace YGOSharp.Network.Utils
{
public static class BinaryExtensions
{
public static void WriteUnicode(this BinaryWriter writer, string text, int len)
{
byte[] unicode = Encoding.Unicode.GetBytes(text);
byte[] result = new byte[len * 2];
int max = len * 2 - 2;
Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length);
writer.Write(result);
}
public static string ReadUnicode(this BinaryReader reader, int len)
{
byte[] unicode = reader.ReadBytes(len * 2);
string text = Encoding.Unicode.GetString(unicode);
int index = text.IndexOf('\0');
if (index > 0) text = text.Substring(0, index);
return text;
}
public static byte[] ReadToEnd(this BinaryReader reader)
{
return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
}
}
}
``` |
9b66d03b-0e98-4de0-85d5-0829d8949fae | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.Api
{
public class ItemStartedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
}
public class ItemStartedEvent : Event
{
[JsonProperty("data")]
public ItemStartedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemStarted ID={0} Time={1} Item={2} Folder={3}>", this.Id, this.Time, this.Data.Item, this.Data.Folder);
}
}
}
```
Support details for ItemStarted event | ```c#
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.Api
{
public class ItemStartedEventDetails
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Flags")]
public int Flags { get; set; }
[JsonProperty("Modified")]
public long Modified { get; set; } // Is this supposed to be a DateTime?
[JsonProperty("Version")]
public int Version { get; set; }
[JsonProperty("LocalVersion")]
public int LocalVersion { get; set; }
[JsonProperty("NumBlocks")]
public int NumBlocks { get; set; }
}
public class ItemStartedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
[JsonProperty("details")]
public ItemStartedEventDetails Details { get; set; }
}
public class ItemStartedEvent : Event
{
[JsonProperty("data")]
public ItemStartedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemStarted ID={0} Time={1} Item={2} Folder={3} Name={4} Flags={5} Modified={6} Version={7} LocalVersion={8} NumBlocks={9}>",
this.Id, this.Time, this.Data.Item, this.Data.Folder, this.Data.Details.Name, this.Data.Details.Flags, this.Data.Details.Modified,
this.Data.Details.Version, this.Data.Details.LocalVersion, this.Data.Details.NumBlocks);
}
}
}
``` |
31da7a13-bd2e-4443-85bd-3a1bf63bdea1 | {
"language": "C#"
} | ```c#
using System;
namespace osu.Game.Online.RealtimeMultiplayer
{
public class NotJoinedRoomException : Exception
{
public NotJoinedRoomException()
: base("This user has not yet joined a multiplayer room.")
{
}
}
}```
Add missing final newline in file | ```c#
using System;
namespace osu.Game.Online.RealtimeMultiplayer
{
public class NotJoinedRoomException : Exception
{
public NotJoinedRoomException()
: base("This user has not yet joined a multiplayer room.")
{
}
}
}
``` |
320fc936-f658-4445-be1c-b64d8e8add92 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace MusicRandomizer
{
public partial class NewPlaylistForm : Form
{
public String name;
public NewPlaylistForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
name = txtName.Text;
// Check to make sure the user actually entered a name
if (name.Length == 0)
{
MessageBox.Show("Please enter in a name.");
return;
}
// Check for invalid characters in the filename
foreach (char c in Path.GetInvalidFileNameChars())
{
if (name.Contains(c))
{
MessageBox.Show("There are invalid characters in the playlist name.");
return;
}
}
// Check to make sure this name isn't already taken
String[] playlists = Directory.GetFiles("playlists");
foreach (String playlist in playlists)
{
if (playlist.Equals(name))
{
MessageBox.Show("This playlist already exists.");
return;
}
}
// Create the playlist
using (FileStream writer = File.OpenWrite("playlists\\" + name + ".xml"))
{
MainForm.serializer.Serialize(writer, new List<MusicFile>());
}
this.Close();
}
}
}
```
Fix a bug where you could create an already existing playlist | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace MusicRandomizer
{
public partial class NewPlaylistForm : Form
{
public String name;
public NewPlaylistForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
name = txtName.Text;
// Check to make sure the user actually entered a name
if (name.Length == 0)
{
MessageBox.Show("Please enter in a name.");
return;
}
// Check for invalid characters in the filename
foreach (char c in Path.GetInvalidFileNameChars())
{
if (name.Contains(c))
{
MessageBox.Show("There are invalid characters in the playlist name.");
return;
}
}
// Check to make sure this name isn't already taken
if (File.Exists("playlists\\" + name + ".xml"))
{
MessageBox.Show("That playlist already exists.");
return;
}
// Create the playlist
using (FileStream writer = File.OpenWrite("playlists\\" + name + ".xml"))
{
MainForm.serializer.Serialize(writer, new List<MusicFile>());
}
this.Close();
}
}
}
``` |
db850fa3-735f-417a-9e91-350d194cc68c | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.PictureSlideshow
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 384;
Height = 216;
}
[Category("General")]
[DisplayName("Root Folder")]
public string RootPath { get; set; }
[Category("General")]
[DisplayName("Allowed File Extensions")]
public string FileFilterExtension { get; set; } = ".jpg|.jpeg|.png|.bmp|.gif|.ico|.tiff|.wmp";
[Category("General")]
[DisplayName("Maximum File Size (bytes)")]
public double FileFilterSize { get; set; } = 1024000;
[Category("General")]
[DisplayName("Next Image Interval")]
public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15);
[Category("General")]
[DisplayName("Shuffle")]
public bool Shuffle { get; set; } = true;
[Category("General")]
[DisplayName("Recursive")]
public bool Recursive { get; set; } = false;
[Category("General")]
[DisplayName("Current Image Path")]
public string ImageUrl { get; set; }
[Category("General")]
[DisplayName("Allow Dropping Images")]
public bool AllowDropFiles { get; set; } = true;
[Category("General")]
[DisplayName("Freeze")]
public bool Freeze { get; set; }
}
}```
Change "Slideshow" "Root Folder" option name | ```c#
using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.PictureSlideshow
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Width = 384;
Height = 216;
}
[Category("General")]
[DisplayName("Image Folder Path")]
public string RootPath { get; set; }
[Category("General")]
[DisplayName("Allowed File Extensions")]
public string FileFilterExtension { get; set; } = ".jpg|.jpeg|.png|.bmp|.gif|.ico|.tiff|.wmp";
[Category("General")]
[DisplayName("Maximum File Size (bytes)")]
public double FileFilterSize { get; set; } = 1024000;
[Category("General")]
[DisplayName("Next Image Interval")]
public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15);
[Category("General")]
[DisplayName("Shuffle")]
public bool Shuffle { get; set; } = true;
[Category("General")]
[DisplayName("Recursive")]
public bool Recursive { get; set; } = false;
[Category("General")]
[DisplayName("Current Image Path")]
public string ImageUrl { get; set; }
[Category("General")]
[DisplayName("Allow Dropping Images")]
public bool AllowDropFiles { get; set; } = true;
[Category("General")]
[DisplayName("Freeze")]
public bool Freeze { get; set; }
}
}``` |
276a071d-a253-4223-8a2d-f5970f14697a | {
"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.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables
{
/// <summary>
/// A hit used specifically for drum rolls, where spawning flying hits is required.
/// </summary>
public class DrawableFlyingHit : DrawableHit
{
public DrawableFlyingHit(DrawableDrumRollTick drumRollTick)
: base(new IgnoreHit
{
StartTime = drumRollTick.HitObject.StartTime + drumRollTick.Result.TimeOffset,
IsStrong = drumRollTick.HitObject.IsStrong,
Type = drumRollTick.JudgementType
})
{
HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
}
protected override void LoadComplete()
{
base.LoadComplete();
ApplyResult(r => r.Type = r.Judgement.MaxResult);
}
}
}
```
Fix rim flying hits changing colour | ```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.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables
{
/// <summary>
/// A hit used specifically for drum rolls, where spawning flying hits is required.
/// </summary>
public class DrawableFlyingHit : DrawableHit
{
public DrawableFlyingHit(DrawableDrumRollTick drumRollTick)
: base(new IgnoreHit
{
StartTime = drumRollTick.HitObject.StartTime + drumRollTick.Result.TimeOffset,
IsStrong = drumRollTick.HitObject.IsStrong,
Type = drumRollTick.JudgementType
})
{
HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
}
protected override void LoadComplete()
{
base.LoadComplete();
ApplyResult(r => r.Type = r.Judgement.MaxResult);
}
protected override void LoadSamples()
{
// block base call - flying hits are not supposed to play samples
// the base call could overwrite the type of this hit
}
}
}
``` |
d0c5ae27-608e-4b38-8a12-a76bbc8de2ee | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Working_with_images
{
/// <summary>
/// The UIApplicationDelegate for the application. This class is responsible for launching the
/// User Interface of the application, as well as listening (and optionally responding) to
/// application events from iOS.
/// </summary>
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
/// <summary>
/// This method is invoked when the application has loaded and is ready to run. In this
/// method you should instantiate the window, load the UI into it and then make the window
/// visible.
/// </summary>
/// <remarks>
/// You have 5 seconds to return from this method, or iOS will terminate your application.
/// </remarks>
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
// make the window visible
window.MakeKeyAndVisible ();
return true;
}
}
}
```
Update Mike's Working with Images sample. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Working_with_images
{
/// <summary>
/// The UIApplicationDelegate for the application. This class is responsible for launching the
/// User Interface of the application, as well as listening (and optionally responding) to
/// application events from iOS.
/// </summary>
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
// Added contoller. As of MonoTouch 5.0.2, applications are expected to
// have a root view controller at the end of application launch
UIViewController controller;
UILabel label;
/// <summary>
/// This method is invoked when the application has loaded and is ready to run. In this
/// method you should instantiate the window, load the UI into it and then make the window
/// visible.
/// </summary>
/// <remarks>
/// You have 5 seconds to return from this method, or iOS will terminate your application.
/// </remarks>
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
controller = new UIViewController ();
controller.View.BackgroundColor = UIColor.White;
label = new UILabel();
label.Frame = new System.Drawing.RectangleF(10 ,10, UIScreen.MainScreen.Bounds.Width, 50);
label.Text = "Hello, Working with Images";
controller.View.AddSubview(label);
window.RootViewController = controller;
// make the window visible
window.MakeKeyAndVisible ();
return true;
}
}
}
``` |
fe2e08f7-1f7b-4dec-9dd9-a302390e9e32 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public sealed class HUD : MonoBehaviour {
private int frameCount = 0;
private float dt = 0.0F;
private float fps = 0.0F;
private float updateRate = 4.0F;
void Start () {
}
void Update () {
frameCount++;
dt += Time.deltaTime;
if (dt > 1.0F / updateRate) {
fps = frameCount / dt ;
frameCount = 0;
dt -= 1.0F / updateRate;
}
}
void OnGUI () {
GUI.Label(new Rect(10, 10, 150, 100), "Current FPS: " + ((int)fps).ToString());
GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 0, 0), "This is a crosshair");
}
}
```
Change some some syntax conventions. | ```c#
using UnityEngine;
using System.Collections;
public sealed class HUD : MonoBehaviour {
private int FrameCount = 0;
private float DeltaTime = 0.0F;
private float FPS = 0.0F;
private float UpdateRate = 5.0F;
void Start () {
}
void Update () {
FrameCount++;
DeltaTime += Time.deltaTime;
if (DeltaTime > 1.0F / UpdateRate) {
FPS = FrameCount / DeltaTime ;
FrameCount = 0;
DeltaTime -= 1.0F / UpdateRate;
}
}
void OnGUI () {
GUI.Label(new Rect(10, 10, 150, 100), "Current FPS: " + ((int)FPS).ToString());
GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 0, 0), "This is a crosshair");
}
}
``` |
7538430e-7de1-4cf1-af4d-4945166a294d | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader(true)]
private void load([CanBeNull] OverlayColourProvider overlayColourProvider, OsuColour colours)
{
BackgroundColour = overlayColourProvider?.Highlight1 ?? colours.Blue3;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
```
Fix rounded buttons not allowing custom colour specifications | ```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 JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osuTK.Graphics;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader(true)]
private void load([CanBeNull] OverlayColourProvider overlayColourProvider, OsuColour colours)
{
if (BackgroundColour == Color4.White)
BackgroundColour = overlayColourProvider?.Highlight1 ?? colours.Blue3;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
``` |
77fd7504-aa73-4f52-aed7-e3e63be20437 | {
"language": "C#"
} | ```c#
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
Console.WriteLine("{0} {1}{2}{3}",
context.Request.Method,
context.Request.PathBase,
context.Request.Path,
context.Request.QueryString);
if (context.IsWebSocketRequest)
{
var webSocket = await context.AcceptWebSocketAsync();
await EchoAsync(webSocket);
}
else
{
context.Response.ContentLength = 11;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello world");
}
});
}
public async Task EchoAsync(WebSocket webSocket)
{
var buffer = new ArraySegment<byte>(new byte[8192]);
for (; ;)
{
var result = await webSocket.ReceiveAsync(
buffer,
CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
else if (result.MessageType == WebSocketMessageType.Text)
{
Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count));
}
await webSocket.SendAsync(
new ArraySegment<byte>(buffer.Array, 0, result.Count),
result.MessageType,
result.EndOfMessage,
CancellationToken.None);
}
}
}
}```
Remove redundant websocket sample code. | ```c#
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
Console.WriteLine("{0} {1}{2}{3}",
context.Request.Method,
context.Request.PathBase,
context.Request.Path,
context.Request.QueryString);
context.Response.ContentLength = 11;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello world");
});
}
}
}``` |
0f4d3b78-d266-4484-9566-d3874b35bcc7 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Event;
using osu.Framework.Input.Handlers;
using osu.Framework.Platform;
using OpenTK;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
public UserInputManager()
{
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
if (inputStateChange is MousePositionChangeEvent mousePositionChange)
{
var mouse = mousePositionChange.InputState.Mouse;
// confine cursor
if (Host.Window != null && (Host.Window.CursorState & CursorState.Confined) > 0)
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
}
if (inputStateChange is MouseScrollChangeEvent)
{
if (Host.Window != null && !Host.Window.CursorInWindow) return;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
```
Use switch instead of ifs | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Event;
using osu.Framework.Input.Handlers;
using osu.Framework.Platform;
using OpenTK;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
public UserInputManager()
{
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
switch (inputStateChange)
{
case MousePositionChangeEvent mousePositionChange:
var mouse = mousePositionChange.InputState.Mouse;
// confine cursor
if (Host.Window != null && (Host.Window.CursorState & CursorState.Confined) > 0)
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
break;
case MouseScrollChangeEvent _:
if (Host.Window != null && !Host.Window.CursorInWindow)
return;
break;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
``` |
648e4f01-1056-45a5-bf2b-4ae683750ab3 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Autofac;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Zermelo.App.UWP.Schedule
{
public sealed partial class ScheduleView : Page
{
public ScheduleView()
{
this.InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Enabled;
}
ScheduleViewModel _viewModel;
public ScheduleViewModel ViewModel => _viewModel ?? (_viewModel = (ScheduleViewModel)DataContext);
private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
CalendarView.SelectedDates.Add(ViewModel.Date);
}
private void ScheduleListView_ItemClick(object sender, ItemClickEventArgs e)
{
ViewModel.SelectedAppointment = e.ClickedItem as Appointment;
Modal.IsModal = true;
}
private void CalendarView_SelectedDatesChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
if (args.AddedDates.Count > 0)
ViewModel.Date = args.AddedDates.FirstOrDefault();
else
CalendarView.SelectedDates.Add(ViewModel.Date);
}
private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
{
var day = args.Item.Date.DayOfWeek;
if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday)
args.Item.IsBlackout = true;
}
}
}
```
Fix crash when navigating back to ScheduleView | ```c#
using System;
using System.Linq;
using Autofac;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Zermelo.App.UWP.Schedule
{
public sealed partial class ScheduleView : Page
{
public ScheduleView()
{
this.InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Enabled;
}
ScheduleViewModel _viewModel;
public ScheduleViewModel ViewModel => _viewModel ?? (_viewModel = (ScheduleViewModel)DataContext);
private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (CalendarView.SelectedDates.Count < 1)
CalendarView.SelectedDates.Add(ViewModel.Date);
}
private void ScheduleListView_ItemClick(object sender, ItemClickEventArgs e)
{
ViewModel.SelectedAppointment = e.ClickedItem as Appointment;
Modal.IsModal = true;
}
private void CalendarView_SelectedDatesChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args)
{
if (args.AddedDates.Count > 0)
ViewModel.Date = args.AddedDates.FirstOrDefault();
else
CalendarView.SelectedDates.Add(ViewModel.Date);
}
private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args)
{
var day = args.Item.Date.DayOfWeek;
if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday)
args.Item.IsBlackout = true;
}
}
}
``` |
494ee753-b1f7-4ac1-a12d-797ef57b9c5c | {
"language": "C#"
} | ```c#
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System.Collections.Generic;
namespace Thinktecture.IdentityServer.WsFed.Models
{
public class RelyingParty
{
public string Name { get; set; }
public bool Enabled { get; set; }
public string Realm { get; set; }
public string ReplyUrl { get; set; }
public string TokenType { get; set; }
public int TokenLifeTime { get; set; }
public Dictionary<string, string> ClaimMappings { get; set; }
}
}```
Add encryption support to relying party model | ```c#
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Thinktecture.IdentityServer.WsFed.Models
{
public class RelyingParty
{
public string Name { get; set; }
public bool Enabled { get; set; }
public string Realm { get; set; }
public string ReplyUrl { get; set; }
public string TokenType { get; set; }
public int TokenLifeTime { get; set; }
public X509Certificate2 EncryptingCertificate { get; set; }
public Dictionary<string, string> ClaimMappings { get; set; }
}
}``` |
ddd2e896-bdd7-4a83-9af9-93521dceaee8 | {
"language": "C#"
} | ```c#
namespace Umbraco.Core.Models.Entities
{
/// <summary>
/// Represents the path of a tree entity.
/// </summary>
public class TreeEntityPath
{
/// <summary>
/// Gets or sets the identifier of the entity.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the path of the entity.
/// </summary>
public string Path { get; set; }
}
}
```
Fix issue where Id was not set when loading all entity paths | ```c#
namespace Umbraco.Core.Models.Entities
{
/// <summary>
/// Represents the path of a tree entity.
/// </summary>
public class TreeEntityPath
{
/// <summary>
/// Gets or sets the identifier of the entity.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the path of the entity.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Proxy of the Id
/// </summary>
public int NodeId
{
get => Id;
set => Id = value;
}
}
}
``` |
64af8040-4de9-4691-87f1-8fe54bead198 | {
"language": "C#"
} | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="CHAR_INFO_ENCODING"/> nested type.
/// </content>
public partial class Kernel32
{
/// <summary>
/// A union of the Unicode and Ascii encodings.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct CHAR_INFO_ENCODING
{
/// <summary>
/// Unicode character of a screen buffer character cell.
/// </summary>
[FieldOffset(0)]
public ushort UnicodeChar;
/// <summary>
/// ANSI character of a screen buffer character cell.
/// </summary>
[FieldOffset(0)]
public byte AsciiChar;
}
}
}
```
Use 'char' instead of 'ushort' for unicode character | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="CHAR_INFO_ENCODING"/> nested type.
/// </content>
public partial class Kernel32
{
/// <summary>
/// A union of the Unicode and Ascii encodings.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct CHAR_INFO_ENCODING
{
/// <summary>
/// Unicode character of a screen buffer character cell.
/// </summary>
[FieldOffset(0)]
public char UnicodeChar;
/// <summary>
/// ANSI character of a screen buffer character cell.
/// </summary>
[FieldOffset(0)]
public byte AsciiChar;
}
}
}
``` |
458aabb3-aa97-4760-a286-6657cd9eb229 | {
"language": "C#"
} | ```c#
@{
ViewData["Title"] = "List of Articles I've Written";
}
<h1 id="page_title">Articles I've written</h1>
<div class="centered_wrapper">
<input type="text" class="search" placeholder="Filter by title/tag">
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
<article>
<p class="date">Monday Aug 28</p>
<h2><a href="#">Change Kestrel default url on Asp Net Core</a></h2>
<div class="tags">
<a href="#">asp net core</a>
<a href="#">asp net core</a>
<a href="#">asp net core</a>
</div>
<hr>
</article>
</div>
<div class="pagination">
<span class="previous_page disabled">Previous</span>
<span class="current">1</span>
<a href="#" rel="next">2</a>
<a href="#" class="next_page">Next</a>
</div>```
Change static content to dynamic | ```c#
@model IEnumerable<ArticleModel>
@{
ViewData["Title"] = "List of Articles I've Written";
}
<h1 id="page_title">Articles I've written</h1>
<div class="centered_wrapper">
<input type="text" class="search" placeholder="Filter by title/tag">
@foreach (var article in Model)
{
<article>
<p class="date">@article.FormattedPublishedAt()</p>
<h2><a href="@article.Link" target="_blank">@article.Title</a></h2>
<div class="tags">
@foreach (var tag in article.Tags)
{
<a href="#">@tag</a>
}
</div>
<hr>
</article>
}
</div>
<!--<div class="pagination">
<span class="previous_page disabled">Previous</span>
<span class="current">1</span>
<a href="#" rel="next">2</a>
<a href="#" class="next_page">Next</a>
</div>-->``` |
9d023900-6b2b-4261-b2b5-b6d77dd7e41b | {
"language": "C#"
} | ```c#
using System;
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
{
private const int Speed = 10;
private const int MaxForward = 5;
private const int MinForward = -5;
private const int LegDistance = 15;
private const int LegHeight = -13;
private bool _movingForward;
private Vector3 _lastWrittenPosition = Vector3.Zero;
public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
{
Driver.Setup();
Driver.StandUpfromGround();
StartEngine();
}
protected override void EngineSpin()
{
var translate = Vector3.Zero;
if (_movingForward)
{
translate.Y += Speed * 0.001f * TimeSincelastTick;
}
else
{
translate.Y -= Speed * 0.001f * TimeSincelastTick;
}
_lastWrittenPosition += translate;
if (_movingForward && _lastWrittenPosition.Y > MaxForward)
{
_movingForward = false;
}
else if (!_movingForward && _lastWrittenPosition.Y < MinForward)
{
_movingForward = true;
}
Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
}
}
}
```
Add simple interpolated motion driver | ```c#
using System;
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public class BasicQuadrupedGaitEngine : QuadrupedGaitEngine
{
private const int Speed = 12;
private int _currentIndex;
private readonly Vector3[] _positions =
{
new Vector3(-5, 5, 3),
new Vector3(5, 5, -3),
new Vector3(5, -5, 3),
new Vector3(-5, -5, -3)
};
private const float LegHeight = -11f;
private const int LegDistance = 15;
private Vector3 _lastWrittenPosition = Vector3.Zero;
public BasicQuadrupedGaitEngine(QuadrupedIkDriver driver) : base(driver)
{
Driver.Setup();
Driver.StandUpfromGround();
StartEngine();
}
protected override void EngineSpin()
{
if (_lastWrittenPosition.Similar(_positions[_currentIndex], 0.25f))
{
_currentIndex++;
if (_currentIndex >= _positions.Length)
{
_currentIndex = 0;
}
}
_lastWrittenPosition =
_lastWrittenPosition.MoveTowards(_positions[_currentIndex], Speed * 0.001f * TimeSincelastTick);
Driver.MoveAbsoluteCenterMass(_lastWrittenPosition, LegDistance, LegHeight);
}
}
}
``` |
c7ab911b-17d7-4eeb-8445-9dbd061186dd | {
"language": "C#"
} | ```c#
namespace AnimalHope.Web
{
using System.Web;
using System.Web.Mvc;
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
```
Handle correctly the special HTML characters and tags | ```c#
namespace AnimalHope.Web
{
using System.Web;
using System.Web.Mvc;
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ValidateInputAttribute(false));
}
}
}
``` |
9ecc8fa6-35a6-44c0-9310-6ae7fc5d60bc | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using CommonBotLibrary.Interfaces.Models;
using RedditSharp.Things;
namespace CommonBotLibrary.Services.Models
{
[DebuggerDisplay("{Url, nq}")]
public class RedditResult : IWebpage
{
public RedditResult(Post post)
{
Title = post.Title;
Url = post.Url.OriginalString;
Post = post;
}
/// <summary>
/// The wrapped model returned by RedditSharp with more submission props.
/// </summary>
public Post Post { get; }
public string Url { get; set; }
public string Title { get; set; }
public static implicit operator Post(RedditResult redditResult)
=> redditResult.Post;
public enum PostCategory
{
New,
Controversial,
Rising,
Hot,
Top
}
}
}
```
Make Hot the default reddit post category | ```c#
using System.Diagnostics;
using CommonBotLibrary.Interfaces.Models;
using RedditSharp.Things;
namespace CommonBotLibrary.Services.Models
{
[DebuggerDisplay("{Url, nq}")]
public class RedditResult : IWebpage
{
public RedditResult(Post post)
{
Title = post.Title;
Url = post.Url.OriginalString;
Post = post;
}
/// <summary>
/// The wrapped model returned by RedditSharp with more submission props.
/// </summary>
public Post Post { get; }
public string Url { get; set; }
public string Title { get; set; }
public static implicit operator Post(RedditResult redditResult)
=> redditResult.Post;
public enum PostCategory
{
Hot,
New,
Controversial,
Rising,
Top
}
}
}
``` |
f84dc12f-2ea2-4a9d-816e-ea451b3cc91f | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
new FrameworkElement().Dispatcher.DoEvents();
}
public static void PumpingWait(this Task task)
{
PumpingWaitAll(new[] { task });
}
public static T PumpingWaitResult<T>(this Task<T> task)
{
PumpingWait(task);
return task.Result;
}
public static void PumpingWaitAll(this IEnumerable<Task> tasks)
{
var smallTimeout = TimeSpan.FromMilliseconds(10);
var taskArray = tasks.ToArray();
var done = false;
while (!done)
{
done = Task.WaitAll(taskArray, smallTimeout);
if (!done)
{
WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle);
}
}
foreach (var task in tasks)
{
if (task.Exception != null)
{
throw task.Exception;
}
}
}
}
}
```
Revert change to pump in the wrong spot. | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
Action action = delegate { };
new FrameworkElement().Dispatcher.Invoke(action, priority);
}
public static void PumpingWait(this Task task)
{
PumpingWaitAll(new[] { task });
}
public static T PumpingWaitResult<T>(this Task<T> task)
{
PumpingWait(task);
return task.Result;
}
public static void PumpingWaitAll(this IEnumerable<Task> tasks)
{
var smallTimeout = TimeSpan.FromMilliseconds(10);
var taskArray = tasks.ToArray();
var done = false;
while (!done)
{
done = Task.WaitAll(taskArray, smallTimeout);
if (!done)
{
WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle);
}
}
foreach (var task in tasks)
{
if (task.Exception != null)
{
throw task.Exception;
}
}
}
}
}
``` |
5228c057-a7f4-43fe-881a-f51fd6322aea | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
try
{
commandDispatcher.Dispatch(args);
}
catch (DispatchException exception)
{
Console.WriteLine();
Console.WriteLine("Error: {0}", exception.Message);
}
}
}
}
```
Use red color when outputting error message | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
try
{
commandDispatcher.Dispatch(args);
}
catch (DispatchException exception)
{
Console.WriteLine();
using (new ForegroundColor(ConsoleColor.Red))
{
Console.WriteLine("Error: {0}", exception.Message);
}
}
}
}
}
``` |
77a74f58-1c65-4356-a484-c9ff23bd4914 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class SettingsControl : UserControl
{
public SettingsControl()
{
InitializeComponent();
}
internal void DataBind(SettingsPresenter presenter)
{
if (presenter != null)
{
settingsName.DataSource = presenter.SettingsNames;
settingsName.DataBindings.Add("SelectedItem", presenter, "SettingsNameSelected", true, DataSourceUpdateMode.OnValidation);
settingsName.SelectedIndexChanged += (s, args) => settingsName.DataBindings["SelectedItem"].WriteValue();
settingsValue.DataBindings.Add("Text", presenter, "SettingsValue", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
public Button AddCommand
{
get {return addReference;}
}
public Button RemoveCommand
{
get { return removeReference; }
}
}
}
```
Fix issue that the changes to the connection strings were not registered before you're changing the focus to another connection string. | ```c#
using System;
using System.Linq;
using System.Windows.Forms;
using NBi.UI.Genbi.Presenter;
namespace NBi.UI.Genbi.View.TestSuiteGenerator
{
public partial class SettingsControl : UserControl
{
public SettingsControl()
{
InitializeComponent();
}
internal void DataBind(SettingsPresenter presenter)
{
if (presenter != null)
{
settingsName.DataSource = presenter.SettingsNames;
settingsName.DataBindings.Add("SelectedItem", presenter, "SettingsNameSelected", true, DataSourceUpdateMode.OnValidation);
settingsName.SelectedIndexChanged += (s, args) => settingsName.DataBindings["SelectedItem"].WriteValue();
settingsValue.TextChanged += (s, args) => presenter.UpdateValue((string)settingsName.SelectedValue, settingsValue.Text);
settingsValue.DataBindings.Add("Text", presenter, "SettingsValue", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
private void toto(object s, EventArgs args)
{
MessageBox.Show("Hello");
}
public Button AddCommand
{
get {return addReference;}
}
public Button RemoveCommand
{
get { return removeReference; }
}
}
}
``` |
4f9e1859-6881-4afa-a1b1-442ea59dc606 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
```
Fix the broken NuGet build. | ```c#
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
}``` |
57db1f0e-bfe0-4bcc-bdb5-a0d0e8308b7b | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
}
}```
Add Refund as paymentmethod so we can use it in SettlementPeriodRevenue. | ```c#
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
[EnumMember(Value = "refund")] Refund,
}
}``` |
31962425-8b09-4454-8b6a-6f41be1f4022 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
```
Add basics to load compiled client app | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc();
app.UseSpa(spa => {
spa.Options.SourcePath = "ClientApp";
//if (env.IsDevelopment()) {
// spa.UseProxyToSpaDevelopmentServer("http://localhost:1234");
//}
});
}
}
}
``` |
e082d2c8-3db6-49ec-96d3-89b2e1394eeb | {
"language": "C#"
} | ```c#
@{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "diagnostics%2Favailability%2Fanalysis";
}
else
{
detectorPath = "detectors%2FLinuxAppDown";
}
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ siteName
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
```
Fix detectors link to the slot | ```c#
@{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var hostName = Environment.GetEnvironmentVariable("HTTP_HOST") ?? "";
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "diagnostics%2Favailability%2Fanalysis";
}
else
{
detectorPath = "detectors%2FLinuxAppDown";
}
var hostNameIndex = hostName.IndexOf('.');
if (hostNameIndex >= 0)
{
hostName = hostName.Substring(0, hostNameIndex);
}
var runtimeSuffxIndex = siteName.IndexOf("__");
if (runtimeSuffxIndex >= 0)
{
siteName = siteName.Substring(0, runtimeSuffxIndex);
}
// Get the slot name
if (!hostName.Equals(siteName, StringComparison.CurrentCultureIgnoreCase))
{
var slotNameIndex = siteName.Length;
if (hostName.Length > slotNameIndex && hostName[slotNameIndex] == '-')
{
// Fix up hostName by replacing "-SLOTNAME" with "/slots/SLOTNAME"
var slotName = hostName.Substring(slotNameIndex + 1);
hostName = hostName.Substring(0, slotNameIndex) + "/slots/" + slotName;
}
}
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ hostName
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
``` |
20f60aa4-9f3b-4359-b499-6d571a0eef61 | {
"language": "C#"
} | ```c#
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
return Vector3.Normalize(vector);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
}
}
```
Add move towards method for vectors | ```c#
using System.Numerics;
namespace DynamixelServo.Quadruped
{
public static class Vector3Extensions
{
public static Vector3 Normal(this Vector3 vector)
{
return Vector3.Normalize(vector);
}
public static bool Similar(this Vector3 a, Vector3 b, float marginOfError = float.Epsilon)
{
return Vector3.Distance(a, b) <= marginOfError;
}
public static Vector3 MoveTowards(this Vector3 current, Vector3 target, float distance)
{
var transport = target - current;
var len = transport.Length();
if (len < distance)
{
return target;
}
return current + transport.Normal() * distance;
}
}
}
``` |
6b5257c3-3313-4c82-993b-7937fd5a2ff6 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
namespace Spiffy.Monitoring
{
public static class Behavior
{
static Action<Level, string> _loggingAction;
/// <summary>
/// Whether or not to remove newline characters from logged values.
/// </summary>
/// <returns>
/// <code>true</code> if newline characters will be removed from logged
/// values, <code>false</code> otherwise.
/// </returns>
public static bool RemoveNewlines { get; set; }
public static void UseBuiltInLogging(BuiltInLogging behavior)
{
switch (behavior)
{
case Monitoring.BuiltInLogging.Console:
_loggingAction = (level, message) => Console.WriteLine(message);
break;
case Monitoring.BuiltInLogging.Trace:
_loggingAction = (level, message) => Trace.WriteLine(message);
break;
default:
throw new NotSupportedException($"{behavior} is not supported");
}
}
public static void UseCustomLogging(Action<Level, string> loggingAction)
{
_loggingAction = loggingAction;
}
internal static Action<Level, string> GetLoggingAction()
{
return _loggingAction;
}
}
public enum BuiltInLogging
{
Trace,
Console
}
}```
Update default logging behaviors to use functions that correspond to log level | ```c#
using System;
using System.Diagnostics;
namespace Spiffy.Monitoring
{
public static class Behavior
{
static Action<Level, string> _loggingAction;
/// <summary>
/// Whether or not to remove newline characters from logged values.
/// </summary>
/// <returns>
/// <code>true</code> if newline characters will be removed from logged
/// values, <code>false</code> otherwise.
/// </returns>
public static bool RemoveNewlines { get; set; }
public static void UseBuiltInLogging(BuiltInLogging behavior)
{
switch (behavior)
{
case Monitoring.BuiltInLogging.Console:
_loggingAction = (level, message) =>
{
if (level == Level.Error)
{
Console.Error.WriteLine(message);
}
else
{
Console.WriteLine(message);
}
};
break;
case Monitoring.BuiltInLogging.Trace:
_loggingAction = (level, message) =>
{
switch (level)
{
case Level.Info:
Trace.TraceInformation(message);
break;
case Level.Warning:
Trace.TraceWarning(message);
break;
case Level.Error:
Trace.TraceError(message);
break;
default:
Trace.WriteLine(message);
break;
}
};
break;
default:
throw new NotSupportedException($"{behavior} is not supported");
}
}
public static void UseCustomLogging(Action<Level, string> loggingAction)
{
_loggingAction = loggingAction;
}
internal static Action<Level, string> GetLoggingAction()
{
return _loggingAction;
}
}
public enum BuiltInLogging
{
Trace,
Console
}
}
``` |
2f020d6c-12dd-4c13-97b6-9316ae5b8a7c | {
"language": "C#"
} | ```c#
//Copyright (c) 2016 Artem A. Mavrin and other contributors
using UnrealBuildTool;
public class DialogueSystem : ModuleRules
{
public DialogueSystem(TargetInfo Target)
{
PrivateIncludePaths.AddRange(
new string[] {"DialogueSystem/Private"});
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UMG",
"SlateCore",
"Slate",
"AIModule"
}
);
}
}
```
Fix build issues with 4.12 | ```c#
//Copyright (c) 2016 Artem A. Mavrin and other contributors
using UnrealBuildTool;
public class DialogueSystem : ModuleRules
{
public DialogueSystem(TargetInfo Target)
{
PrivateIncludePaths.AddRange(
new string[] {"DialogueSystem/Private"});
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UMG",
"SlateCore",
"Slate",
"AIModule",
"GameplayTasks"
}
);
}
}
``` |
52006a6d-7c65-45c1-b600-f7bdc2e88eb2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
public class DefaultSafeNamespaceValueFormModel : IValueForm
{
public DefaultSafeNamespaceValueFormModel()
{
}
public static readonly string FormName = "safe_namespace";
public virtual string Identifier => FormName;
public string Name => Identifier;
public IValueForm FromJObject(string name, JObject configuration)
{
throw new NotImplementedException();
}
public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
{
string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)(?=\d)|[^\w\.])", "_");
return workingValue;
}
}
}
```
Update expression to match dots following dots | ```c#
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms
{
public class DefaultSafeNamespaceValueFormModel : IValueForm
{
public DefaultSafeNamespaceValueFormModel()
{
}
public static readonly string FormName = "safe_namespace";
public virtual string Identifier => FormName;
public string Name => Identifier;
public IValueForm FromJObject(string name, JObject configuration)
{
throw new NotImplementedException();
}
public virtual string Process(IReadOnlyDictionary<string, IValueForm> forms, string value)
{
string workingValue = Regex.Replace(value, @"(^\s+|\s+$)", "");
workingValue = Regex.Replace(workingValue, @"(((?<=\.)|^)((?=\d)|\.)|[^\w\.])", "_");
return workingValue;
}
}
}
``` |
e1e34957-3e34-453c-ae16-8a3292af60dc | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration
{
public class EmployerApprenticeshipsServiceConfiguration
{
public CompaniesHouseConfiguration CompaniesHouse { get; set; }
public EmployerConfiguration Employer { get; set; }
public string ServiceBusConnectionString { get; set; }
public IdentityServerConfiguration Identity { get; set; }
public SmtpConfiguration SmtpServer { get; set; }
public string DashboardUrl { get; set; }
public HmrcConfiguration Hmrc { get; set; }
}
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
}
public class IdentityServerConfiguration
{
public bool UseFake { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string BaseAddress { get; set; }
}
public class EmployerConfiguration
{
public string DatabaseConnectionString { get; set; }
}
public class CompaniesHouseConfiguration
{
public string ApiKey { get; set; }
}
public class SmtpConfiguration
{
public string ServerName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Port { get; set; }
}
}```
Add new config value for testing scenarios related to duplicate PAYE schemes. This will be deleted | ```c#
using System.Collections.Generic;
namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration
{
public class EmployerApprenticeshipsServiceConfiguration
{
public CompaniesHouseConfiguration CompaniesHouse { get; set; }
public EmployerConfiguration Employer { get; set; }
public string ServiceBusConnectionString { get; set; }
public IdentityServerConfiguration Identity { get; set; }
public SmtpConfiguration SmtpServer { get; set; }
public string DashboardUrl { get; set; }
public HmrcConfiguration Hmrc { get; set; }
}
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
public bool DuplicatesCheck { get; set; }
}
public class IdentityServerConfiguration
{
public bool UseFake { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string BaseAddress { get; set; }
}
public class EmployerConfiguration
{
public string DatabaseConnectionString { get; set; }
}
public class CompaniesHouseConfiguration
{
public string ApiKey { get; set; }
}
public class SmtpConfiguration
{
public string ServerName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Port { get; set; }
}
}``` |
c9747cca-9c64-4ec9-91cd-9aba4081b851 | {
"language": "C#"
} | ```c#
namespace TestMoya.Runner.Runners
{
using System;
using System.Reflection;
using Moq;
using Moya.Attributes;
using Moya.Models;
using Moya.Runner.Runners;
using Xunit;
public class TimerDecoratorTests
{
private readonly Mock<ITestRunner> testRunnerMock;
private TimerDecorator timerDecorator;
public TimerDecoratorTests()
{
testRunnerMock = new Mock<ITestRunner>();
}
[Fact]
public void TimerDecoratorExecuteRunsMethod()
{
timerDecorator = new TimerDecorator(testRunnerMock.Object);
bool methodRun = false;
MethodInfo method = ((Action)(() => methodRun = true)).Method;
testRunnerMock
.Setup(x => x.Execute(method))
.Callback(() => methodRun = true)
.Returns(new TestResult());
timerDecorator.Execute(method);
Assert.True(methodRun);
}
[Fact]
public void TimerDecoratorExecuteAddsDurationToResult()
{
MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
timerDecorator = new TimerDecorator(new StressTestRunner());
var result = timerDecorator.Execute(method);
Assert.True(result.Duration > 0);
}
public class TestClass
{
[Stress]
public static void MethodWithMoyaAttribute()
{
}
}
}
}```
Make sure timerdecoratortest always succeeds | ```c#
using System.Threading;
namespace TestMoya.Runner.Runners
{
using System;
using System.Reflection;
using Moq;
using Moya.Attributes;
using Moya.Models;
using Moya.Runner.Runners;
using Xunit;
public class TimerDecoratorTests
{
private readonly Mock<ITestRunner> testRunnerMock;
private TimerDecorator timerDecorator;
public TimerDecoratorTests()
{
testRunnerMock = new Mock<ITestRunner>();
}
[Fact]
public void TimerDecoratorExecuteRunsMethod()
{
timerDecorator = new TimerDecorator(testRunnerMock.Object);
bool methodRun = false;
MethodInfo method = ((Action)(() => methodRun = true)).Method;
testRunnerMock
.Setup(x => x.Execute(method))
.Callback(() => methodRun = true)
.Returns(new TestResult());
timerDecorator.Execute(method);
Assert.True(methodRun);
}
[Fact]
public void TimerDecoratorExecuteAddsDurationToResult()
{
MethodInfo method = ((Action)TestClass.MethodWithMoyaAttribute).Method;
timerDecorator = new TimerDecorator(new StressTestRunner());
var result = timerDecorator.Execute(method);
Assert.True(result.Duration > 0);
}
public class TestClass
{
[Stress]
public static void MethodWithMoyaAttribute()
{
Thread.Sleep(1);
}
}
}
}``` |
5498b3b2-f11e-485e-abe4-a5eca482e49c | {
"language": "C#"
} | ```c#
@using CGO.Web.Models
@model IEnumerable<SideBarSection>
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
@foreach (var sideBarSection in Model)
{
<li class="nav-header">@sideBarSection.Title</li>
foreach (var link in sideBarSection.Links)
{
@SideBarLink(link)
}
}
</ul>
</div>
</div>
@helper SideBarLink(SideBarLink link)
{
if (link.IsActive)
{
<li class="active"><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
else
{
<li><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
}
```
Tidy up the display of the side bar. | ```c#
@using CGO.Web.Models
@model IEnumerable<SideBarSection>
<div class="col-lg-3">
<div class="well">
<ul class="nav nav-stacked">
@foreach (var sideBarSection in Model)
{
<li class="navbar-header">@sideBarSection.Title</li>
foreach (var link in sideBarSection.Links)
{
@SideBarLink(link)
}
}
</ul>
</div>
</div>
@helper SideBarLink(SideBarLink link)
{
if (link.IsActive)
{
<li class="active"><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
else
{
<li><a href="@link.Uri" title="@link.Title">@link.Title</a></li>
}
}
``` |
1a70820a-27ad-4607-a93b-450296b55be9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace Leeroy
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (args.FirstOrDefault() == "/test")
{
Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master");
overseer.Run(null);
}
else
{
ServiceBase.Run(new ServiceBase[] { new Service() });
}
}
}
}
```
Allow Leeroy to run until canceled in test mode. | ```c#
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
namespace Leeroy
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
if (args.FirstOrDefault() == "/test")
{
var tokenSource = new CancellationTokenSource();
Overseer overseer = new Overseer(tokenSource.Token, "BradleyGrainger", "Configuration", "master");
var task = Task.Factory.StartNew(overseer.Run, tokenSource, TaskCreationOptions.LongRunning);
MessageBox(IntPtr.Zero, "Leeroy is running. Click OK to stop.", "Leeroy", 0);
tokenSource.Cancel();
try
{
task.Wait();
}
catch (AggregateException)
{
// TODO: verify this contains a single OperationCanceledException
}
// shut down
task.Dispose();
tokenSource.Dispose();
}
else
{
ServiceBase.Run(new ServiceBase[] { new Service() });
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, int options);
}
}
``` |
a69e0add-61e9-4db8-b272-228ec966185d | {
"language": "C#"
} | ```c#
//
// DefaultDirectoryResolver.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using Couchbase.Lite.DI;
namespace Couchbase.Lite.Support
{
// NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
// It seems to usually be in the right place?
[CouchbaseDependency]
internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
{
#region IDefaultDirectoryResolver
public string DefaultDirectory()
{
var dllDirectory = Path.GetDirectoryName(typeof(DefaultDirectoryResolver).Assembly.Location);
return Path.Combine(dllDirectory, "CouchbaseLite");
}
#endregion
}
}
```
Revert change to .NET desktop default directory logic | ```c#
//
// DefaultDirectoryResolver.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using Couchbase.Lite.DI;
namespace Couchbase.Lite.Support
{
// NOTE: AppContext.BaseDirectory is not entirely reliable, but there is no other choice
// It seems to usually be in the right place?
[CouchbaseDependency]
internal sealed class DefaultDirectoryResolver : IDefaultDirectoryResolver
{
#region IDefaultDirectoryResolver
public string DefaultDirectory()
{
var baseDirectory = AppContext.BaseDirectory ??
throw new RuntimeException("BaseDirectory was null, cannot continue...");
return Path.Combine(baseDirectory, "CouchbaseLite");
}
#endregion
}
}
``` |
b463196f-9910-4ff3-b98e-e1c7fde45614 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Manos;
//
// This the default StaticContentModule that comes with all Manos apps
// if you do not wish to serve any static content with Manos you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : ManosModule {
public StaticContentModule ()
{
Get (".*", Content);
}
public static void Content (IManosContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
```
Make sure to End StaticContent. | ```c#
using System;
using System.IO;
using Manos;
//
// This the default StaticContentModule that comes with all Manos apps
// if you do not wish to serve any static content with Manos you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : ManosModule {
public StaticContentModule ()
{
Get (".*", Content);
}
public static void Content (IManosContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
ctx.Response.End ();
}
}
}
``` |
f3bd3a7e-d8ee-471f-8342-4281430764a7 | {
"language": "C#"
} | ```c#
using Grpc.Core;
using System;
namespace MagicOnion
{
public class ReturnStatusException : Exception
{
public StatusCode StatusCode { get; private set; }
public string Detail { get; private set; }
public ReturnStatusException(StatusCode statusCode, string detail)
{
this.StatusCode = statusCode;
this.Detail = detail;
}
public Status ToStatus()
{
return new Status(StatusCode, Detail ?? "");
}
}
}
```
Set an exception message for ReturnStatusMessage | ```c#
using Grpc.Core;
using System;
namespace MagicOnion
{
public class ReturnStatusException : Exception
{
public StatusCode StatusCode { get; private set; }
public string Detail { get; private set; }
public ReturnStatusException(StatusCode statusCode, string detail)
: base($"The method has returned the status code '{statusCode}'." + (string.IsNullOrWhiteSpace(detail) ? "" : $" (Detail={detail})"))
{
this.StatusCode = statusCode;
this.Detail = detail;
}
public Status ToStatus()
{
return new Status(StatusCode, Detail ?? "");
}
}
}
``` |
944f8142-5321-45f8-a546-2dce3bc3462d | {
"language": "C#"
} | ```c#
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented", Scope = "type", Target = "~T:Serilog.Exceptions.Test.Destructurers.ReflectionBasedDestructurerTest")]```
Enlarge the scope of SA1600 supression to whole test project | ```c#
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Test project classes do not need to be documented")]``` |
cdac58ee-7c22-46f4-8670-88ca082808c9 | {
"language": "C#"
} | ```c#
namespace Bumblebee.Interfaces
{
public interface ITextField : IElement, IHasText
{
TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
}
public interface ITextField<out TResult> : ITextField, IGenericElement<TResult> where TResult : IBlock
{
TResult EnterText(string text);
TResult AppendText(string text);
}
}```
Allow noop on text fields | ```c#
namespace Bumblebee.Interfaces
{
public interface ITextField : IElement, IHasText
{
TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock;
TCustomResult AppendText<TCustomResult>(string text) where TCustomResult : IBlock;
}
public interface ITextField<out TResult> : ITextField, IAllowsNoOp<TResult> where TResult : IBlock
{
TResult EnterText(string text);
TResult AppendText(string text);
}
}``` |
8a70d1c6-43bd-4817-ac7b-2ce0223ec4f8 | {
"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;
namespace osu.Game.Screens.Select.Filter
{
public enum SortMode
{
[Description("Artist")]
Artist,
[Description("Author")]
Author,
[Description("BPM")]
BPM,
[Description("Date Added")]
DateAdded,
[Description("Difficulty")]
Difficulty,
[Description("Length")]
Length,
[Description("Rank Achieved")]
RankAchieved,
[Description("Title")]
Title,
[Description("Source")]
Source,
}
}
```
Fix enum ordering after adding source | ```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;
namespace osu.Game.Screens.Select.Filter
{
public enum SortMode
{
[Description("Artist")]
Artist,
[Description("Author")]
Author,
[Description("BPM")]
BPM,
[Description("Date Added")]
DateAdded,
[Description("Difficulty")]
Difficulty,
[Description("Length")]
Length,
[Description("Rank Achieved")]
RankAchieved,
[Description("Source")]
Source,
[Description("Title")]
Title,
}
}
``` |
591dcd06-7ffc-4d6d-b4b8-1c933936c0a5 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("2.2.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.0.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
```
Change version number to 2.2.1 | ```c#
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("2.2.1")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("Version:2.2.1.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015/2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
``` |
8f4c0fb3-5e13-46ee-9214-4cb67dfb2a10 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Windows.Forms;
namespace GUI.Controls
{
internal class TreeViewFileSorter : IComparer
{
public int Compare(object x, object y)
{
var tx = x as TreeNode;
var ty = y as TreeNode;
var folderx = tx.ImageKey == @"_folder";
var foldery = ty.ImageKey == @"_folder";
if (folderx && !foldery)
{
return -1;
}
if (!folderx && foldery)
{
return 1;
}
return string.CompareOrdinal(tx.Text, ty.Text);
}
}
}
```
Check folders by its tag | ```c#
using System.Collections;
using System.Windows.Forms;
namespace GUI.Controls
{
internal class TreeViewFileSorter : IComparer
{
public int Compare(object x, object y)
{
var tx = x as TreeNode;
var ty = y as TreeNode;
var folderx = tx.Tag is TreeViewFolder;
var foldery = ty.Tag is TreeViewFolder;
if (folderx && !foldery)
{
return -1;
}
if (!folderx && foldery)
{
return 1;
}
return string.CompareOrdinal(tx.Text, ty.Text);
}
}
}
``` |
b25a0d2a-fb65-4ee2-b186-072a29475838 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;
namespace Ecom.Hal
{
public class HalClient
{
public HalClient(Uri endpoint)
{
Client = new HttpClient {BaseAddress = endpoint};
}
public T Parse<T>(string content)
{
return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
}
public Task<T> Get<T>(string path)
{
return Task<T>
.Factory
.StartNew(() =>
{
var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
return Parse<T>(body);
});
}
protected HttpClient Client { get; set; }
}
}
```
Add support for basic auth | ```c#
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Ecom.Hal.JSON;
using Newtonsoft.Json;
namespace Ecom.Hal
{
public class HalClient
{
public HalClient(Uri endpoint)
{
Client = new HttpClient {BaseAddress = endpoint};
}
public T Parse<T>(string content)
{
return JsonConvert.DeserializeObject<T>(content, new JsonConverter[] {new HalResourceConverter()});
}
public Task<T> Get<T>(string path)
{
return Task<T>
.Factory
.StartNew(() =>
{
var body = Client.GetStringAsync(new Uri(path, UriKind.Relative)).Result;
return Parse<T>(body);
});
}
public void SetCredentials(string username, string password)
{
Client
.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))));
}
protected HttpClient Client { get; set; }
}
}
``` |
f25e5701-90ec-4298-aa39-30f7577bf283 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
namespace SharpGraphEditor.Models
{
public class ZoomManager : PropertyChangedBase
{
public int MaxZoom { get; } = 2;
public double CurrentZoom { get; private set; }
public int CurrentZoomInPercents => (int)(CurrentZoom * 100);
public ZoomManager()
{
CurrentZoom = 1;
}
public void ChangeCurrentZoom(double value)
{
if (value >= (1 / MaxZoom) && value <= MaxZoom)
{
CurrentZoom = Math.Round(value, 2);
}
}
public void ChangeZoomByPercents(double percents)
{
CurrentZoom += percents / 100;
}
}
}
```
Fix bug with zoom when it didnt limit | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
namespace SharpGraphEditor.Models
{
public class ZoomManager : PropertyChangedBase
{
public double MaxZoom { get; } = 2;
public double CurrentZoom { get; private set; }
public int CurrentZoomInPercents => (int)(CurrentZoom * 100);
public ZoomManager()
{
CurrentZoom = 1.0;
}
public void ChangeCurrentZoom(double value)
{
var newZoom = CurrentZoom + value;
if (newZoom >= (1.0 / MaxZoom) && newZoom <= MaxZoom)
{
CurrentZoom = Math.Round(newZoom, 2);
}
}
public void ChangeZoomByPercents(double percents)
{
ChangeCurrentZoom(percents / 100);
}
}
}
``` |
01c98532-dc2e-4921-b5f6-686ff6e66226 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Services;
using FluentScheduler;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;
namespace BatteryCommander.Web.Jobs
{
public class SqliteBackupJob : IJob
{
private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable
private readonly IEmailService emailSvc;
public SqliteBackupJob(IEmailService emailSvc)
{
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var encoded = System.Convert.ToBase64String(data);
var message = new SendGridMessage
{
From = new EmailAddress("Battery-Commander@redlegdev.com"),
Subject = "Nightly Db Backup",
Contents = new List<Content>()
{
new Content
{
Type = "text/plain",
Value = "Please find the nightly database backup attached."
}
},
Attachments = new List<Attachment>()
{
new Attachment
{
Filename = "Data.db",
Type = "application/octet-stream",
Content = encoded
}
}
};
message.AddTo(Recipient);
emailSvc.Send(message).Wait();
}
}
}```
Use common from address for backup | ```c#
using BatteryCommander.Web.Services;
using FluentScheduler;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;
namespace BatteryCommander.Web.Jobs
{
public class SqliteBackupJob : IJob
{
private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable
private readonly IEmailService emailSvc;
public SqliteBackupJob(IEmailService emailSvc)
{
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var encoded = System.Convert.ToBase64String(data);
var message = new SendGridMessage
{
From = EmailService.FROM_ADDRESS,
Subject = "Nightly Db Backup",
Contents = new List<Content>()
{
new Content
{
Type = "text/plain",
Value = "Please find the nightly database backup attached."
}
},
Attachments = new List<Attachment>()
{
new Attachment
{
Filename = "Data.db",
Type = "application/octet-stream",
Content = encoded
}
}
};
message.AddTo(Recipient);
emailSvc.Send(message).Wait();
}
}
}``` |
c6d50ac3-1083-4296-9fce-62025945eefe | {
"language": "C#"
} | ```c#
using RestSharp;
namespace PivotalTrackerDotNet
{
public abstract class AAuthenticatedService
{
protected readonly string m_token;
protected RestClient RestClient;
protected AAuthenticatedService(string token)
{
m_token = token;
RestClient = new RestClient {BaseUrl = PivotalTrackerRestEndpoint.SSLENDPOINT};
}
protected RestRequest BuildGetRequest()
{
var request = new RestRequest(Method.GET);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPutRequest()
{
var request = new RestRequest(Method.PUT);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildDeleteRequest()
{
var request = new RestRequest(Method.DELETE);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPostRequest()
{
var request = new RestRequest(Method.POST);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
}
}```
Fix RestClient BaseUrl change to Uri | ```c#
using RestSharp;
namespace PivotalTrackerDotNet
{
using System;
public abstract class AAuthenticatedService
{
protected readonly string m_token;
protected RestClient RestClient;
protected AAuthenticatedService(string token)
{
m_token = token;
RestClient = new RestClient { BaseUrl = new Uri(PivotalTrackerRestEndpoint.SSLENDPOINT) };
}
protected RestRequest BuildGetRequest()
{
var request = new RestRequest(Method.GET);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPutRequest()
{
var request = new RestRequest(Method.PUT);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildDeleteRequest()
{
var request = new RestRequest(Method.DELETE);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
protected RestRequest BuildPostRequest()
{
var request = new RestRequest(Method.POST);
request.AddHeader("X-TrackerToken", m_token);
request.RequestFormat = DataFormat.Json;
return request;
}
}
}``` |
bb75d7e1-d63f-4c32-b75f-871ebefa398d | {
"language": "C#"
} | ```c#
#load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: false,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* ",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
```
Exclude Shouldly from code coverage | ```c#
#load nuget:?package=Cake.Recipe&version=1.0.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "TfsUrlParser",
repositoryOwner: "bbtsoftware",
repositoryName: "TfsUrlParser",
appVeyorAccountName: "BBTSoftwareAG",
shouldPublishMyGet: false,
shouldRunCodecov: false,
shouldDeployGraphDocumentation: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(
context: Context,
dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
``` |
1aa9aa3b-615f-4d06-97dc-808888b6cdf2 | {
"language": "C#"
} | ```c#
/*
* Programmed by Umut Celenli umut@celenli.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[256];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, 256);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true);
}
}
}```
Define a const for read buffer size | ```c#
/*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, maxBufferSize);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
}
}``` |
8daabd08-600c-43dd-bcb6-1f3defe8ca88 | {
"language": "C#"
} | ```c#
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif
namespace System.Threading
{
public class MonitorEx
{
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
public static void Enter(object obj, ref bool lockTaken)
{
#if LESSTHAN_NET40 || NETSTANDARD1_0
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (lockTaken)
{
throw new ArgumentException("Lock taken", nameof(lockTaken));
}
Monitor.Enter(obj);
Volatile.Write(ref lockTaken, true);
#else
Monitor.Enter(obj, ref lockTaken);
#endif
}
}
}
```
Use static class for static methods. | ```c#
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
using System.Runtime.CompilerServices;
#endif
namespace System.Threading
{
public static class MonitorEx
{
#if !(LESSTHAN_NET40 || NETSTANDARD1_0)
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
#endif
public static void Enter(object obj, ref bool lockTaken)
{
#if LESSTHAN_NET40 || NETSTANDARD1_0
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (lockTaken)
{
throw new ArgumentException("Lock taken", nameof(lockTaken));
}
Monitor.Enter(obj);
Volatile.Write(ref lockTaken, true);
#else
Monitor.Enter(obj, ref lockTaken);
#endif
}
}
}
``` |
4e428138-72ea-45ca-a44a-51b4f05a960e | {
"language": "C#"
} | ```c#
namespace Nancy
{
using System.Collections.Generic;
using System.IO;
public interface ISerializer
{
/// <summary>
/// Whether the serializer can serialize the content type
/// </summary>
/// <param name="contentType">Content type to serialize</param>
/// <returns>True if supported, false otherwise</returns>
bool CanSerialize(string contentType);
/// <summary>
/// Gets the list of extensions that the serializer can handle.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
IEnumerable<string> Extensions { get; }
/// <summary>
/// Serialize the given model with the given contentType
/// </summary>
/// <param name="contentType">Content type to serialize into</param>
/// <param name="model">Model to serialize</param>
/// <param name="outputStream">Output stream to serialize to</param>
/// <returns>Serialized object</returns>
void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
}
}```
Revert "Swapping Silly UK English ;)" | ```c#
namespace Nancy
{
using System.Collections.Generic;
using System.IO;
public interface ISerializer
{
/// <summary>
/// Whether the serializer can serialize the content type
/// </summary>
/// <param name="contentType">Content type to serialise</param>
/// <returns>True if supported, false otherwise</returns>
bool CanSerialize(string contentType);
/// <summary>
/// Gets the list of extensions that the serializer can handle.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value>
IEnumerable<string> Extensions { get; }
/// <summary>
/// Serialize the given model with the given contentType
/// </summary>
/// <param name="contentType">Content type to serialize into</param>
/// <param name="model">Model to serialize</param>
/// <param name="outputStream">Output stream to serialize to</param>
/// <returns>Serialised object</returns>
void Serialize<TModel>(string contentType, TModel model, Stream outputStream);
}
}``` |
8705d51d-2abe-4d17-91d7-6c4a6f017f78 | {
"language": "C#"
} | ```c#
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
return await _context.Orders.FindAsync(orderId);
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
```
Add OrderingDomainException when the order doesn't exist with id orderId | ```c#
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Exceptions;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
return await _context.Orders.FindAsync(orderId)
?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}");
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
``` |
75960f72-bf78-4913-bcfb-2d6e5af405d2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace XiboClient.Control
{
class WatchDogManager
{
public static void Start()
{
// Check to see if the WatchDog EXE exists where we expect it to be
// Uncomment to test local watchdog install.
//string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + Application.ProductName + "ClientWatchdog.exe";
string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";
// Start it
if (File.Exists(path))
{
try
{
Process process = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;
process.StartInfo = info;
process.Start();
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
}
}
}
}
}
```
Handle oddity in watchdog naming convention | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace XiboClient.Control
{
class WatchDogManager
{
public static void Start()
{
// Check to see if the WatchDog EXE exists where we expect it to be
// Uncomment to test local watchdog install.
//string path = @"C:\Program Files (x86)\Xibo Player\watchdog\x86\XiboClientWatchdog.exe";
string path = Path.GetDirectoryName(Application.ExecutablePath) + @"\watchdog\x86\" + ((Application.ProductName != "Xibo") ? Application.ProductName + "Watchdog.exe" : "XiboClientWatchdog.exe");
string args = "-p \"" + Application.ExecutablePath + "\" -l \"" + ApplicationSettings.Default.LibraryPath + "\"";
// Start it
if (File.Exists(path))
{
try
{
Process process = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.Arguments = "/c start \"watchdog\" \"" + path + "\" " + args;
process.StartInfo = info;
process.Start();
}
catch (Exception e)
{
Trace.WriteLine(new LogMessage("WatchDogManager - Start", "Unable to start: " + e.Message), LogType.Error.ToString());
}
}
}
}
}
``` |
bc7d6482-923d-4c91-8c28-21d20c96c9de | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
namespace Bloom.web.controllers
{
class KeybordingConfigApi
{
public void RegisterWithServer(EnhancedImageServer server)
{
server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
{
//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
var form = Application.OpenForms.Cast<Form>().Last();
request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)?"false":"true");
});
}
}
}
```
Fix BL-3614 Crash while checking for keyman | ```c#
using System;
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
namespace Bloom.web.controllers
{
class KeybordingConfigApi
{
public void RegisterWithServer(EnhancedImageServer server)
{
server.RegisterEndpointHandler("keyboarding/useLongPress", (ApiRequest request) =>
{
try
{
//detect if some keyboarding system is active, e.g. KeyMan. If it is, don't enable LongPress
var form = Application.OpenForms.Cast<Form>().Last();
request.ReplyWithText(SIL.Windows.Forms.Keyboarding.KeyboardController.IsFormUsingInputProcessor(form)
? "false"
: "true");
}
catch(Exception error)
{
request.ReplyWithText("true"); // This is arbitrary. I don't know if it's better to assume keyman, or not.
NonFatalProblem.Report(ModalIf.None, PassiveIf.All, "Error checking for keyman","", error);
}
}, handleOnUiThread:false);
}
}
}
``` |
7dd3f308-ef22-49f9-99d1-1eaeb7753bf2 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Noobot.Core.Configuration
{
public class ConfigReader : IConfigReader
{
private JObject _currentJObject;
private readonly string _configLocation;
private readonly object _lock = new object();
private const string DEFAULT_LOCATION = @"configuration\config.json";
private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";
public ConfigReader() : this(DEFAULT_LOCATION) { }
public ConfigReader(string configurationFile)
{
_configLocation = configurationFile;
}
public bool HelpEnabled { get; set; } = true;
public bool StatsEnabled { get; set; } = true;
public bool AboutEnabled { get; set; } = true;
public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);
public T GetConfigEntry<T>(string entryName)
{
return GetJObject().Value<T>(entryName);
}
private JObject GetJObject()
{
lock (_lock)
{
if (_currentJObject == null)
{
string assemblyLocation = AssemblyLocation();
string fileName = Path.Combine(assemblyLocation, _configLocation);
string json = File.ReadAllText(fileName);
_currentJObject = JObject.Parse(json);
}
}
return _currentJObject;
}
private string AssemblyLocation()
{
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var path = Path.GetDirectoryName(codebase.LocalPath);
return path;
}
}
}```
Allow config.json path to work on non-Windows OS | ```c#
using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Noobot.Core.Configuration
{
public class ConfigReader : IConfigReader
{
private JObject _currentJObject;
private readonly string _configLocation;
private readonly object _lock = new object();
private static readonly string DEFAULT_LOCATION = Path.Combine("configuration", "config.json");
private const string SLACKAPI_CONFIGVALUE = "slack:apiToken";
public ConfigReader() : this(DEFAULT_LOCATION) { }
public ConfigReader(string configurationFile)
{
_configLocation = configurationFile;
}
public bool HelpEnabled { get; set; } = true;
public bool StatsEnabled { get; set; } = true;
public bool AboutEnabled { get; set; } = true;
public string SlackApiKey => GetConfigEntry<string>(SLACKAPI_CONFIGVALUE);
public T GetConfigEntry<T>(string entryName)
{
return GetJObject().Value<T>(entryName);
}
private JObject GetJObject()
{
lock (_lock)
{
if (_currentJObject == null)
{
string assemblyLocation = AssemblyLocation();
string fileName = Path.Combine(assemblyLocation, _configLocation);
string json = File.ReadAllText(fileName);
_currentJObject = JObject.Parse(json);
}
}
return _currentJObject;
}
private string AssemblyLocation()
{
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var path = Path.GetDirectoryName(codebase.LocalPath);
return path;
}
}
}``` |
57e629f8-fd56-421d-a599-287607827c60 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileOpener2 : BaseCommand
{
public async void open(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
string aliasCurrentCommandCallbackId = args[2];
try
{
// Get the file.
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]);
// Launch the bug query file.
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), aliasCurrentCommandCallbackId);
}
catch (FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), aliasCurrentCommandCallbackId);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId);
}
}
}
}```
Add support for local folder | ```c#
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileOpener2 : BaseCommand
{
public async void open(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
this.openPath(args[0].Replace("/", "\\"), args[2]);
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
}
private async void openPath(string path, string cbid)
{
try
{
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
}
catch (FileNotFoundException)
{
this.openInLocalFolder(path, cbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
}
}
private async void openInLocalFolder(string path, string cbid)
{
try
{
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(
Path.Combine(
Windows.Storage.ApplicationData.Current.LocalFolder.Path,
path.TrimStart('\\')
)
);
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), cbid);
}
catch (FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), cbid);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), cbid);
}
}
}
}
``` |
c524a2f7-7450-4071-9514-5b02376429bc | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneAccountCreationOverlay : OsuTestScene
{
private readonly Container userPanelArea;
private IBindable<User> localUser;
public TestSceneAccountCreationOverlay()
{
AccountCreationOverlay accountCreation;
Children = new Drawable[]
{
accountCreation = new AccountCreationOverlay(),
userPanelArea = new Container
{
Padding = new MarginPadding(10),
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
AddStep("show", () => accountCreation.Show());
}
[BackgroundDependencyLoader]
private void load()
{
API.Logout();
localUser = API.LocalUser.GetBoundCopy();
localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);
AddStep("logout", API.Logout);
}
}
}
```
Rewrite test to cover failure case | ```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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneAccountCreationOverlay : OsuTestScene
{
private readonly Container userPanelArea;
private readonly AccountCreationOverlay accountCreation;
private IBindable<User> localUser;
public TestSceneAccountCreationOverlay()
{
Children = new Drawable[]
{
accountCreation = new AccountCreationOverlay(),
userPanelArea = new Container
{
Padding = new MarginPadding(10),
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
}
[BackgroundDependencyLoader]
private void load()
{
API.Logout();
localUser = API.LocalUser.GetBoundCopy();
localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true);
}
[Test]
public void TestOverlayVisibility()
{
AddStep("start hidden", () => accountCreation.Hide());
AddStep("log out", API.Logout);
AddStep("show manually", () => accountCreation.Show());
AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible);
AddStep("log back in", () => API.Login("dummy", "password"));
AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden);
}
}
}
``` |
4209c579-fb0f-45ab-a795-cfb7c1a18e5d | {
"language": "C#"
} | ```c#
using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.uri", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
}```
Add http.host and http.path annotations | ```c#
using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
using Microsoft.AspNetCore.Http.Extensions;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
trace.Record(Annotations.Tag("http.path", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
}``` |
80cb0c90-3ff1-4769-bf9d-d083c3744470 | {
"language": "C#"
} | ```c#
namespace Translatable.TranslationTest
{
public class MainWindowTranslation : ITranslatable
{
private IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();
public string Title { get; private set; } = "Main window title";
public string SampleText { get; private set; } = "This is my content\r\nwith multiple lines";
public string Messages { get; private set; } = "Messages";
[Context("Some context")]
public string Messages2 { get; private set; } = "Messages";
private string[] NewMessagesText { get; set; } = {"You have {0} new message", "You have {0} new messages"};
[TranslatorComment("This page is intentionally left blank")]
public string MissingTranslation { get; set; } = "This translation might be \"missing\"";
public EnumTranslation<TestEnum>[] TestEnumTranslation { get; private set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();
public string FormatMessageText(int messages)
{
var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
return string.Format(translation, messages);
}
}
}
```
Make translation work with inheritance | ```c#
namespace Translatable.TranslationTest
{
public class MainWindowTranslation : ITranslatable
{
protected IPluralBuilder PluralBuilder { get; set; } = new DefaultPluralBuilder();
public string Title { get; protected set; } = "Main window title";
public string SampleText { get; protected set; } = "This is my content\r\nwith multiple lines";
public string Messages { get; protected set; } = "Messages";
[Context("Some context")]
public string Messages2 { get; protected set; } = "Messages";
protected string[] NewMessagesText { get; set; } = { "You have {0} new message", "You have {0} new messages" };
[TranslatorComment("This page is intentionally left blank")]
public string MissingTranslation { get; set; } = "This translation might be \"missing\"";
public EnumTranslation<TestEnum>[] TestEnumTranslation { get; protected set; } = EnumTranslation<TestEnum>.CreateDefaultEnumTranslation();
public string FormatMessageText(int messages)
{
var translation = PluralBuilder.GetPlural(messages, NewMessagesText);
return string.Format(translation, messages);
}
}
public class TestTranslation : MainWindowTranslation
{
public string Text { get; private set; } = "Test";
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.