doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
7b773e7f-cefc-451c-bac5-202d5dc2582e | {
"language": "C#"
} | ```c#
using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Common.Models
{
public enum Rank
{
[Display(Name = "PVT")]
E1 = 1,
[Display(Name = "PV2")]
E2 = 2,
[Display(Name = "PFC")]
E3 = 3,
[Display(Name = "SPC")]
E4 = 4,
[Display(Name = "SGT")]
E5 = 5,
[Display(Name = "SSG")]
E6 = 6,
[Display(Name = "SFC")]
E7 = 7,
[Display(Name = "1SG")]
E8 = 8,
Cadet = 9,
[Display(Name = "2LT")]
O1 = 10,
[Display(Name = "1LT")]
O2 = 11,
[Display(Name = "CPT")]
O3 = 12,
[Display(Name = "MAJ")]
O4 = 13,
[Display(Name = "LTC")]
O5 = 14,
[Display(Name = "COL")]
O6 = 15
}
}```
Add a display property for cadet rank | ```c#
using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Common.Models
{
public enum Rank
{
[Display(Name = "PVT")]
E1 = 1,
[Display(Name = "PV2")]
E2 = 2,
[Display(Name = "PFC")]
E3 = 3,
[Display(Name = "SPC")]
E4 = 4,
[Display(Name = "SGT")]
E5 = 5,
[Display(Name = "SSG")]
E6 = 6,
[Display(Name = "SFC")]
E7 = 7,
[Display(Name = "1SG")]
E8 = 8,
[Display(Name = "CDT")]
Cadet = 9,
[Display(Name = "2LT")]
O1 = 10,
[Display(Name = "1LT")]
O2 = 11,
[Display(Name = "CPT")]
O3 = 12,
[Display(Name = "MAJ")]
O4 = 13,
[Display(Name = "LTC")]
O5 = 14,
[Display(Name = "COL")]
O6 = 15
}
}``` |
0567770c-8fb0-45be-bf62-0bf844a4f005 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.codeplex.com")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.codeplex.com/license")]
[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]
```
Update project and license URLs | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://github.com/terrajobst/nuproj")]
[assembly : AssemblyMetadata("LicenseUrl", "https://raw.githubusercontent.com/terrajobst/nuproj/master/LICENSE")]
[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]
``` |
a9db13df-d165-446a-90ed-31d370bd36bb | {
"language": "C#"
} | ```c#
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace AppHarbor
{
public class AppHarborInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(AllTypes.FromThisAssembly()
.BasedOn<ICommand>());
container.Register(Component
.For<IAccessTokenConfiguration>()
.ImplementedBy<AccessTokenConfiguration>());
container.Register(Component
.For<AppHarborClient>()
.UsingFactoryMethod(x =>
{
var accessTokenConfiguration = container.Resolve<AccessTokenConfiguration>();
return new AppHarborClient(accessTokenConfiguration.GetAccessToken());
}));
container.Register(Component
.For<CommandDispatcher>()
.UsingFactoryMethod(x =>
{
return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel);
}));
container.Register(Component
.For<IFileSystem>()
.ImplementedBy<PhysicalFileSystem>()
.LifeStyle.Transient);
}
}
}
```
Make sure to register interface rather than implementation | ```c#
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace AppHarbor
{
public class AppHarborInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(AllTypes.FromThisAssembly()
.BasedOn<ICommand>());
container.Register(Component
.For<IAccessTokenConfiguration>()
.ImplementedBy<AccessTokenConfiguration>());
container.Register(Component
.For<IAppHarborClient>()
.UsingFactoryMethod(x =>
{
return new AppHarborClient(accessTokenConfiguration.GetAccessToken());
}));
container.Register(Component
.For<CommandDispatcher>()
.UsingFactoryMethod(x =>
{
return new CommandDispatcher(Assembly.GetExecutingAssembly().GetExportedTypes(), container.Kernel);
}));
container.Register(Component
.For<IFileSystem>()
.ImplementedBy<PhysicalFileSystem>()
.LifeStyle.Transient);
}
}
}
``` |
73fdc460-6aaa-49af-89ad-08aa48cf6928 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Web.Trees
{
[CoreTree(TreeGroup =Constants.Trees.Groups.Settings)]
[UmbracoTreeAuthorize(Constants.Trees.MemberTypes)]
[Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)]
public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase
{
protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings)
{
return Services.MemberTypeService.GetAll()
.OrderBy(x => x.Name)
.Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false));
}
}
}
```
Fix for chekcing the children belonging to MemberType tree. | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using Umbraco.Core;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;
namespace Umbraco.Web.Trees
{
[CoreTree(TreeGroup = Constants.Trees.Groups.Settings)]
[UmbracoTreeAuthorize(Constants.Trees.MemberTypes)]
[Tree(Constants.Applications.Settings, Constants.Trees.MemberTypes, null, sortOrder: 2)]
public class MemberTypeTreeController : MemberTypeAndGroupTreeControllerBase
{
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
//check if there are any member types
root.HasChildren = Services.MemberTypeService.GetAll().Any();
return root;
}
protected override IEnumerable<TreeNode> GetTreeNodesFromService(string id, FormDataCollection queryStrings)
{
return Services.MemberTypeService.GetAll()
.OrderBy(x => x.Name)
.Select(dt => CreateTreeNode(dt, Constants.ObjectTypes.MemberType, id, queryStrings, "icon-item-arrangement", false));
}
}
}
``` |
12894359-bada-4e53-808f-22749c798399 | {
"language": "C#"
} | ```c#
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Permissions;
using CupCake.Players;
namespace CupCake.DefaultCommands.Commands.User
{
public sealed class KickCommand : UserCommandBase
{
[MinGroup(Group.Trusted)]
[Label("kick", "kickplayer")]
[CorrectUsage("[player] [reason]")]
protected override void Run(IInvokeSource source, ParsedCommand message)
{
this.RequireOwner();
Player player = this.GetPlayerOrSelf(source, message);
this.RequireSameRank(source, player);
this.Chatter.Kick(player.Username, message.GetTrail(1));
}
}
}```
Add default kick message, inform who the kicker was | ```c#
using System.Runtime.InteropServices;
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Permissions;
using CupCake.Players;
namespace CupCake.DefaultCommands.Commands.User
{
public sealed class KickCommand : UserCommandBase
{
[MinGroup(Group.Trusted)]
[Label("kick", "kickplayer")]
[CorrectUsage("[player] [reason]")]
protected override void Run(IInvokeSource source, ParsedCommand message)
{
this.RequireOwner();
Player player = this.GetPlayerOrSelf(source, message);
this.RequireSameRank(source, player);
this.Chatter.ChatService.Kick(source.Name, player.Username, (message.Count > 1 ? message.GetTrail(1) : "Tsk tsk tsk"));
}
}
}``` |
69ebe4a1-8eff-43ea-b0aa-911bfc77f476 | {
"language": "C#"
} | ```c#
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext
{
[Coalesce]
public class TestDbContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Case> Cases { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<CaseProduct> CaseProducts { get; set; }
public DbSet<ComplexModel> ComplexModels { get; set; }
public DbSet<Test> Tests { get; set; }
public TestDbContext() : this(Guid.NewGuid().ToString()) { }
public TestDbContext(string memoryDatabaseName)
: base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).Options)
{ }
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{ }
}
}
```
Fix tests - apparently CoreEventId.NavigationBaseIncludeIgnored now defaults to Error in EF Core 6. | ```c#
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Collections.Generic;
using System.Text;
namespace IntelliTect.Coalesce.Tests.TargetClasses.TestDbContext
{
[Coalesce]
public class TestDbContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Case> Cases { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<CaseProduct> CaseProducts { get; set; }
public DbSet<ComplexModel> ComplexModels { get; set; }
public DbSet<Test> Tests { get; set; }
public TestDbContext() : this(Guid.NewGuid().ToString()) { }
public TestDbContext(string memoryDatabaseName)
: base(new DbContextOptionsBuilder<TestDbContext>().UseInMemoryDatabase(memoryDatabaseName).ConfigureWarnings(w =>
{
#if NET5_0_OR_GREATER
w.Ignore(CoreEventId.NavigationBaseIncludeIgnored);
#endif
}).Options)
{ }
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{ }
}
}
``` |
10e88f6b-7721-473d-bfce-82545f09e880 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Packages.R;
namespace Microsoft.VisualStudio.R.Package.Options.R.Tools {
public sealed class SetupRemoteCommand : MenuCommand {
private const string _remoteSetupPage = "http://aka.ms/rtvs-remote";
public SetupRemoteCommand() :
base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) {
}
public static void OnCommand(object sender, EventArgs args) {
Process.Start(_remoteSetupPage);
}
}
}
```
Fix link to remote R setup | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Packages.R;
namespace Microsoft.VisualStudio.R.Package.Options.R.Tools {
public sealed class SetupRemoteCommand : MenuCommand {
private const string _remoteSetupPage = "https://aka.ms/rtvs-remote-setup-instructions";
public SetupRemoteCommand() :
base(OnCommand, new CommandID(RGuidList.RCmdSetGuid, RPackageCommandId.icmdSetupRemote)) {
}
public static void OnCommand(object sender, EventArgs args) {
Process.Start(_remoteSetupPage);
}
}
}
``` |
7dd883be-84d0-4278-9a39-34f7de83f64d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Pequot
{
[XmlRoot("settings")]
public class SerializableSettings
: Dictionary<string, string>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
string key = XmlConvert.DecodeName(reader.Name);
string value = reader.ReadString();
this.Add(key, value);
reader.Read();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
foreach (String key in this.Keys)
{
writer.WriteStartElement(XmlConvert.EncodeName(key));
writer.WriteString(this[key]);
writer.WriteEndElement();
}
}
#endregion
}
}
```
Make saved settings more readable | ```c#
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace Pequot
{
[XmlRoot("settings")]
public class SerializableSettings
: Dictionary<string, string>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != XmlNodeType.EndElement)
{
// Convert from human-readable element names (see below)
string key = XmlConvert.DecodeName(reader.Name.Replace("___", "_x0020_").Replace("__x005F__", "___"));
string value = reader.ReadString();
if(key!=null)
{
if(ContainsKey(key))
// update if already exists
this[key] = value;
else
Add(key, value);
}
reader.Read();
}
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
foreach (String key in Keys)
{
// Convert to human-readable element names by substituting three underscores for an encoded space (2nd Replace)
// and making sure existing triple-underscores will not cause confusion by substituting with partial encoding
string encoded = XmlConvert.EncodeName(key);
if (encoded == null) continue;
writer.WriteStartElement(encoded.Replace("___", "__x005F__").Replace("_x0020_", "___"));
writer.WriteString(this[key]);
writer.WriteEndElement();
}
}
#endregion
}
}
``` |
c05b3211-d076-445d-b7ce-67928d5b1652 | {
"language": "C#"
} | ```c#
namespace Nine.Application.WindowsStore.Test
{
using System;
using System.Reflection;
using Windows.UI.Xaml.Controls;
using Xunit;
using Xunit.Abstractions;
public sealed partial class MainPage : Page, IMessageSink
{
public MainPage()
{
InitializeComponent();
Loaded += async (a, b) =>
{
await new PortableTestExecutor().RunAll(this, typeof(AppUITest).GetTypeInfo().Assembly);
};
}
public bool OnMessage(IMessageSinkMessage message)
{
Output.Text = message.ToString();
return true;
}
}
}
```
Remove windows store test runner | ```c#
namespace Nine.Application.WindowsStore.Test
{
using System;
using System.Reflection;
using Windows.UI.Xaml.Controls;
using Xunit;
using Xunit.Abstractions;
public sealed partial class MainPage : Page, IMessageSink
{
public MainPage()
{
InitializeComponent();
}
public bool OnMessage(IMessageSinkMessage message)
{
Output.Text = message.ToString();
return true;
}
}
}
``` |
109f9e04-8b23-4d3f-a750-7f6300b2de0e | {
"language": "C#"
} | ```c#
using Xunit;
using System.Globalization;
using System.Threading;
namespace CronExpressionDescriptor.Test.Support
{
public abstract class BaseTestFormats
{
protected virtual string GetLocale()
{
return "en-US";
}
protected string GetDescription(string expression)
{
return GetDescription(expression, new Options());
}
protected string GetDescription(string expression, Options options)
{
options.Locale = this.GetLocale();
return ExpressionDescriptor.GetDescription(expression, options);
}
}
}```
Add verbose option for tests | ```c#
using Xunit;
using System.Globalization;
using System.Threading;
namespace CronExpressionDescriptor.Test.Support
{
public abstract class BaseTestFormats
{
protected virtual string GetLocale()
{
return "en-US";
}
protected string GetDescription(string expression, bool verbose = false)
{
return GetDescription(expression, new Options() { Verbose = verbose });
}
protected string GetDescription(string expression, Options options)
{
options.Locale = this.GetLocale();
return ExpressionDescriptor.GetDescription(expression, options);
}
}
}
``` |
ccecc674-20e9-4e0a-8d09-9dc8393605ed | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class Trampoline : MonoBehaviour {
public float velocityX;
public float velocityY;
public Input button;
void OnTriggerStay2D(Collider2D other) {
if (other.gameObject.tag == "Player") {
if(button){
other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY));
//other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY);
}
}
}
}
```
Revert "Tried to Figure Out Button: Failed" | ```c#
using UnityEngine;
using System.Collections;
public class Trampoline : MonoBehaviour {
public float velocityX;
public float velocityY;
void OnTriggerStay2D(Collider2D other) {
if (other.gameObject.tag == "Player") {
other.rigidbody2D.AddForce(new Vector2(velocityX,velocityY));
//other.rigidbody2D.velocity+=new Vector2(velocityX,velocityY);
}
}
}
``` |
9d5f1919-d486-4746-9063-210674cf25aa | {
"language": "C#"
} | ```c#
using System;
using Microsoft.SPOT;
using MicroTweet;
using System.Net;
using System.Threading;
namespace SampleApplication
{
public class Program
{
public static void Main()
{
// Wait for DHCP
while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any)
Thread.Sleep(50);
// Update the current time (since Twitter OAuth API requests require a valid timestamp)
DateTime utcTime = Sntp.GetCurrentUtcTime();
Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime);
// Set up application and user credentials
// Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens
var appCredentials = new OAuthApplicationCredentials()
{
ConsumerKey = "YOUR_CONSUMER_KEY_HERE",
ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE",
};
var userCredentials = new OAuthUserCredentials()
{
AccessToken = "YOUR_ACCESS_TOKEN",
AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET",
};
// Create new Twitter client with these credentials
var twitter = new TwitterClient(appCredentials, userCredentials);
// Send a tweet
twitter.SendTweet("Trying out MicroTweet!");
}
}
}
```
Modify sample application to show details about the posted tweet | ```c#
using System;
using Microsoft.SPOT;
using MicroTweet;
using System.Net;
using System.Threading;
namespace SampleApplication
{
public class Program
{
public static void Main()
{
// Wait for DHCP
while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any)
Thread.Sleep(50);
// Update the current time (since Twitter OAuth API requests require a valid timestamp)
DateTime utcTime = Sntp.GetCurrentUtcTime();
Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime);
// Set up application and user credentials
// Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens
var appCredentials = new OAuthApplicationCredentials()
{
ConsumerKey = "YOUR_CONSUMER_KEY_HERE",
ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE",
};
var userCredentials = new OAuthUserCredentials()
{
AccessToken = "YOUR_ACCESS_TOKEN",
AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET",
};
// Create new Twitter client with these credentials
var twitter = new TwitterClient(appCredentials, userCredentials);
// Send a tweet
var tweet = twitter.SendTweet("Trying out MicroTweet!");
if (tweet != null)
Debug.Print("Posted tweet with ID: " + tweet.ID);
else
Debug.Print("Could not send tweet.");
}
}
}
``` |
5edb851e-8a95-4948-959e-b0a328fbbeed | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using Ooui.Forms.Extensions;
using Xamarin.Forms;
namespace Ooui.Forms.Renderers
{
public class ScrollViewRenderer : ViewRenderer<ScrollView, Div>
{
protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e)
{
base.OnElementChanged (e);
this.Style.Overflow = "scroll";
}
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
}
}
}
```
Add ScrollTo support to ScrollView | ```c#
using System;
using System.ComponentModel;
using Ooui.Forms.Extensions;
using Xamarin.Forms;
namespace Ooui.Forms.Renderers
{
public class ScrollViewRenderer : VisualElementRenderer<ScrollView>
{
bool disposed = false;
protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e)
{
if (e.OldElement != null) {
e.OldElement.ScrollToRequested -= Element_ScrollToRequested;
}
if (e.NewElement != null) {
Style.Overflow = "scroll";
e.NewElement.ScrollToRequested += Element_ScrollToRequested;
}
base.OnElementChanged (e);
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (disposing && !disposed) {
if (Element != null) {
Element.ScrollToRequested -= Element_ScrollToRequested;
}
disposed = true;
}
}
void Element_ScrollToRequested (object sender, ScrollToRequestedEventArgs e)
{
var oe = (ITemplatedItemsListScrollToRequestedEventArgs)e;
var item = oe.Item;
var group = oe.Group;
if (e.Mode == ScrollToMode.Position) {
Send (Ooui.Message.Set (Id, "scrollTop", e.ScrollY));
Send (Ooui.Message.Set (Id, "scrollLeft", e.ScrollX));
}
else {
switch (e.Position) {
case ScrollToPosition.Start:
Send (Ooui.Message.Set (Id, "scrollTop", 0));
break;
case ScrollToPosition.End:
Send (Ooui.Message.Set (Id, "scrollTop", new Ooui.Message.PropertyReference { TargetId = Id, Key = "scrollHeight" }));
break;
}
}
}
}
}
``` |
ff1c9c59-242e-43d6-a3e9-346f251ac2b5 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: AssemblyDescription("Autofac multitenancy support library.")]
[assembly: ComVisible(false)]```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: ComVisible(false)]``` |
1f578dca-0ab8-4a15-8686-03334f88fbab | {
"language": "C#"
} | ```c#
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.API.ModelBindings.Providers;
namespace WebAPI.API
{
public class ModelBindingConfig
{
public static void RegisterModelBindings(ServicesContainer services)
{
services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider());
}
}
}```
Add model binder to binding config | ```c#
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.API.ModelBindings.Providers;
namespace WebAPI.API
{
public class ModelBindingConfig
{
public static void RegisterModelBindings(ServicesContainer services)
{
services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new ArcGisOnlineOptionsModelBindingProvide());
services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider());
services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider());
}
}
}``` |
ef387ef6-da31-4b29-bd1c-c2cd68328de0 | {
"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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Utilities
{
internal static class IVsEditorAdaptersFactoryServiceExtensions
{
public static IOleUndoManager TryGetUndoManager(
this IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
Workspace workspace,
DocumentId contextDocumentId,
CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(contextDocumentId);
var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
var textBuffer = textSnapshot?.TextBuffer;
return editorAdaptersFactoryService.TryGetUndoManager(textBuffer);
}
public static IOleUndoManager TryGetUndoManager(
this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer)
{
if (subjectBuffer != null)
{
var adapter = editorAdaptersFactoryService.GetBufferAdapter(subjectBuffer);
if (adapter != null)
{
if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager)))
{
return manager;
}
}
}
return null;
}
}
}```
Address null ref when we can't get an Undo manager. | ```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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Utilities
{
internal static class IVsEditorAdaptersFactoryServiceExtensions
{
public static IOleUndoManager TryGetUndoManager(
this IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
Workspace workspace,
DocumentId contextDocumentId,
CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(contextDocumentId);
var text = document?.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
var textBuffer = textSnapshot?.TextBuffer;
return editorAdaptersFactoryService.TryGetUndoManager(textBuffer);
}
public static IOleUndoManager TryGetUndoManager(
this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer)
{
if (subjectBuffer != null)
{
var adapter = editorAdaptersFactoryService?.GetBufferAdapter(subjectBuffer);
if (adapter != null)
{
if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager)))
{
return manager;
}
}
}
return null;
}
}
}``` |
f2cf49cf-747f-4ca3-aca7-5ba3ad0ee28e | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Mania.Skinning.Default;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.Skinning.Argon
{
public class ArgonHitTarget : CompositeDrawable
{
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
Height = DefaultNotePiece.NOTE_HEIGHT;
InternalChildren = new[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.3f,
Blending = BlendingParameters.Additive,
Colour = Color4.White
},
};
}
}
}
```
Fix argon hit target area not being aligned correctly | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Mania.Skinning.Default;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.Skinning.Argon
{
public class ArgonHitTarget : CompositeDrawable
{
private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();
[BackgroundDependencyLoader]
private void load(IScrollingInfo scrollingInfo)
{
RelativeSizeAxes = Axes.X;
Height = DefaultNotePiece.NOTE_HEIGHT;
InternalChildren = new[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.3f,
Blending = BlendingParameters.Additive,
Colour = Color4.White
},
};
direction.BindTo(scrollingInfo.Direction);
direction.BindValueChanged(onDirectionChanged, true);
}
private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
{
Anchor = Origin = direction.NewValue == ScrollingDirection.Up ? Anchor.TopLeft : Anchor.BottomLeft;
}
}
}
``` |
269ad338-0a37-41e4-a1d4-2ad85b2557cb | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Fixie
{
public class ClassExecution
{
public ClassExecution(ExecutionPlan executionPlan, Type testClass, CaseExecution[] caseExecutions)
{
ExecutionPlan = executionPlan;
TestClass = testClass;
CaseExecutions = caseExecutions;
}
public ExecutionPlan ExecutionPlan { get; private set; }
public Type TestClass { get; private set; }
public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; }
public void FailCases(Exception exception)
{
foreach (var caseExecution in CaseExecutions)
caseExecution.Fail(exception);
}
}
}```
Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable. | ```c#
using System;
using System.Collections.Generic;
namespace Fixie
{
public class ClassExecution
{
public ClassExecution(ExecutionPlan executionPlan, Type testClass, IReadOnlyList<CaseExecution> caseExecutions)
{
ExecutionPlan = executionPlan;
TestClass = testClass;
CaseExecutions = caseExecutions;
}
public ExecutionPlan ExecutionPlan { get; private set; }
public Type TestClass { get; private set; }
public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; }
public void FailCases(Exception exception)
{
foreach (var caseExecution in CaseExecutions)
caseExecution.Fail(exception);
}
}
}``` |
9430bd8f-59c0-4dcb-beb5-d6d0d143e4f4 | {
"language": "C#"
} | ```c#
using System;
using RSB;
using RSB.Diagnostics;
using RSB.Transports.RabbitMQ;
namespace SampleDiscoverableModule
{
class Program
{
static void Main(string[] args)
{
var bus = new Bus(RabbitMqTransport.FromConfigurationFile());
var diagnostics = new BusDiagnostics(bus,"SampleDiscoverableModule");
diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => true);
Console.ReadLine();
}
}
}```
Refactor to use UseBusDiagnostics extension | ```c#
using System;
using System.Threading;
using RSB;
using RSB.Diagnostics;
using RSB.Transports.RabbitMQ;
namespace SampleDiscoverableModule
{
class Program
{
static void Main(string[] args)
{
var bus = new Bus(RabbitMqTransport.FromConfigurationFile());
bus.UseBusDiagnostics("SampleDiscoverableModule", diagnostics =>
{
diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () =>
{
Thread.Sleep(6000);
return true;
});
});
Console.ReadLine();
}
}
}``` |
164d0d1c-b7ad-48e2-95d8-4a42ece396fe | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
using Newtonsoft.Json;
namespace AudioSharp.Config
{
public class ConfigHandler
{
public static void SaveConfig(Configuration config)
{
string json = JsonConvert.SerializeObject(config);
File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
}
public static Configuration ReadConfig()
{
string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
if (File.Exists(path))
{
string json = File.ReadAllText(path);
return JsonConvert.DeserializeObject<Configuration>(json);
}
return new Configuration()
{
RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
RecordingPrefix = "Recording",
NextRecordingNumber = 1,
AutoIncrementRecordingNumber = true,
OutputFormat = "wav",
ShowTrayIcon = true,
GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(),
RecordingSettingsPanelVisible = true,
RecordingOutputPanelVisible = true
};
}
}
}
```
Include the recording number in the default format | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
using Newtonsoft.Json;
namespace AudioSharp.Config
{
public class ConfigHandler
{
public static void SaveConfig(Configuration config)
{
string json = JsonConvert.SerializeObject(config);
File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
}
public static Configuration ReadConfig()
{
string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
if (File.Exists(path))
{
string json = File.ReadAllText(path);
return JsonConvert.DeserializeObject<Configuration>(json);
}
return new Configuration()
{
RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
RecordingPrefix = "Recording{n}",
NextRecordingNumber = 1,
AutoIncrementRecordingNumber = true,
OutputFormat = "wav",
ShowTrayIcon = true,
GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(),
RecordingSettingsPanelVisible = true,
RecordingOutputPanelVisible = true
};
}
}
}
``` |
4d038892-798b-4896-b586-e18dbe27c96c | {
"language": "C#"
} | ```c#
using JoinRpg.Domain;
using JoinRpg.Services.Interfaces;
using JoinRpg.TestHelpers;
using JoinRpg.Web.Models;
using Xunit;
namespace JoinRpg.Web.Test
{
public class EnumTests
{
[Fact]
public void ProblemEnum()
{
EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>();
EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>();
EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>();
EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>();
}
}
}
```
Split enum test to 4 separate | ```c#
using JoinRpg.Domain;
using JoinRpg.Services.Interfaces;
using JoinRpg.TestHelpers;
using JoinRpg.Web.Models;
using Xunit;
namespace JoinRpg.Web.Test
{
public class EnumTests
{
[Fact]
public void AccessReason() => EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>();
[Fact]
public void ProjectFieldType() => EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>();
[Fact]
public void ClaimStatus() => EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>();
[Fact]
public void FinanceOperation() => EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>();
}
}
``` |
47cdff25-8da1-414f-b82f-2b3d2ed7750c | {
"language": "C#"
} | ```c#
using System;
using System.Net;
namespace BmpListener.Bgp
{
public class IPAddrPrefix
{
public IPAddrPrefix(byte[] data, int offset, AddressFamily afi = AddressFamily.IP)
{
DecodeFromBytes(data, offset, afi);
}
internal int ByteLength { get { return 1 + (Length + 7) / 8; } }
public int Length { get; private set; }
public IPAddress Prefix { get; private set; }
public override string ToString()
{
return ($"{Prefix}/{Length}");
}
public void DecodeFromBytes(byte[] data, int offset, AddressFamily afi = AddressFamily.IP)
{
Length = data[offset];
var byteLength = (Length + 7) / 8;
var ipBytes = afi == AddressFamily.IP
? new byte[4]
: new byte[16];
Array.Copy(data, offset + 1, ipBytes, 0, byteLength);
Prefix = new IPAddress(ipBytes);
}
}
}
```
Return prefix and byte length | ```c#
using System;
using System.Linq;
using System.Net;
namespace BmpListener.Bgp
{
public class IPAddrPrefix
{
// RFC 4721 4.3
// The Type field indicates the length in bits of the IP address prefix.
public int Length { get; private set; }
public IPAddress Prefix { get; private set; }
public override string ToString()
{
return ($"{Prefix}/{Length}");
}
public static (IPAddrPrefix prefix, int byteLength) Decode(byte[] data, int offset, AddressFamily afi)
{
var bitLength = data[offset];
var byteLength = (bitLength + 7) / 8;
var ipBytes = afi == AddressFamily.IP
? new byte[4]
: new byte[16];
Array.Copy(data, offset + 1, ipBytes, 0, byteLength);
var prefix = new IPAddress(ipBytes);
var ipAddrPrefix = new IPAddrPrefix { Length = bitLength, Prefix = prefix };
return (ipAddrPrefix, byteLength + 1);
}
public static (IPAddrPrefix prefix, int byteLength) Decode(ArraySegment<byte> data, int offset, AddressFamily afi)
{
byte bitLength = data.First();
var ipBytes = afi == AddressFamily.IP
? new byte[4]
: new byte[16];
offset += data.Offset;
return Decode(data.Array, data.Offset, afi);
}
}
}
``` |
f7800527-9cc8-4eb8-bc20-4cceddc192ec | {
"language": "C#"
} | ```c#
@{
ViewData["Title"] = "Data sources";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
```
Add FutureEmployment to data sources. | ```c#
@{
ViewData["Title"] = "Data sources";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
http://www.oxfordmartin.ox.ac.uk/downloads/academic/The_Future_of_Employment.pdf
``` |
02fd0dc6-7c08-4742-8b3f-692823eac81f | {
"language": "C#"
} | ```c#
@{
Layout = null;
@using ISWebTest.ExtensionMethods;
@using ISWebTest.Controllers;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
<a href="@{Url.Action<HomeController>(nameof(HomeController.Analyze))}">TEST</a>
</div>
</body>
</html>
```
Clean up syntax of index page | ```c#
@using ISWebTest.ExtensionMethods;
@using ISWebTest.Controllers;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
<a href="@(Url.Action<HomeController>(nameof(HomeController.Analyze)))">TEST</a>
</div>
</body>
</html>
``` |
bf9bd5ba-3683-4204-9357-d00531770d92 | {
"language": "C#"
} | ```c#
using IFVM.Core;
namespace IFVM.Execution
{
public partial class Interpreter
{
public static uint Execute(Function function)
{
return 0;
}
}
}
```
Add interpreter with skeleton game loop | ```c#
using System;
using IFVM.Ast;
using IFVM.Collections;
using IFVM.Core;
using IFVM.FlowAnalysis;
namespace IFVM.Execution
{
public partial class Interpreter
{
public static uint Execute(Function function, Machine machine)
{
var cfg = ControlFlowGraph.Compute(function.Body);
var block = cfg.GetBlock(cfg.EntryBlock.Successors[0]);
var result = 0u;
while (!block.IsExit)
{
var nextBlockId = block.ID.GetNext();
foreach (var statement in block.Statements)
{
var jump = false;
void HandleReturnStatement(AstReturnStatement returnStatement)
{
result = Execute(returnStatement.Expression, machine);
nextBlockId = BlockId.Exit;
jump = true;
}
void HandleJumpStatement(AstJumpStatement jumpStatement)
{
nextBlockId = new BlockId(jumpStatement.Label.Index);
jump = true;
}
// Handle control flow
switch (statement.Kind)
{
case AstNodeKind.ReturnStatement:
HandleReturnStatement((AstReturnStatement)statement);
break;
case AstNodeKind.JumpStatement:
HandleJumpStatement((AstJumpStatement)statement);
break;
case AstNodeKind.BranchStatement:
{
var branchStatement = (AstBranchStatement)statement;
var condition = Execute(branchStatement.Condition, machine);
if (condition == 1)
{
switch (branchStatement.Statement.Kind)
{
case AstNodeKind.ReturnStatement:
HandleReturnStatement((AstReturnStatement)branchStatement.Statement);
break;
case AstNodeKind.JumpStatement:
HandleJumpStatement((AstJumpStatement)branchStatement.Statement);
break;
default:
throw new InvalidOperationException($"Invalid statement kind for branch: {branchStatement.Statement.Kind}");
}
}
continue;
}
}
if (jump)
{
break;
}
Execute(statement, machine);
}
block = cfg.GetBlock(nextBlockId);
}
return result;
}
private static uint Execute(AstExpression expression, Machine machine)
{
switch (expression.Kind)
{
default:
throw new InvalidOperationException($"Invalid expression kind: {expression.Kind}");
}
}
private static void Execute(AstStatement statement, Machine machine)
{
switch (statement.Kind)
{
case AstNodeKind.LabelStatement:
break;
default:
throw new InvalidOperationException($"Invalid statement kind: {statement.Kind}");
}
}
}
}
``` |
4db8ab36-637d-4a98-8ba4-a419a78c708b | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Xunit;
namespace Microsoft.AspNet.Routing.Tests
{
public class RouteOptionsTests
{
[Fact]
public void ConstraintMap_SettingNullValue_Throws()
{
// Arrange
var options = new RouteOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentNullException>(() => options.ConstraintMap = null);
Assert.Equal("The 'ConstraintMap' property of 'Microsoft.AspNet.Routing.RouteOptions' must not be null." +
Environment.NewLine + "Parameter name: value", ex.Message);
}
[Fact]
public void ConfigureRouting_ConfiguresOptionsProperly()
{
// Arrange
var services = new ServiceCollection().AddOptions();
// Act
services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint)));
var serviceProvider = services.BuildServiceProvider();
// Assert
var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name);
}
private class TestRouteConstraint : IRouteConstraint
{
public TestRouteConstraint(string pattern)
{
Pattern = pattern;
}
public string Pattern { get; private set; }
public bool Match(HttpContext httpContext,
IRouter route,
string routeKey,
IDictionary<string, object> values,
RouteDirection routeDirection)
{
throw new NotImplementedException();
}
}
}
}
```
Remove test the `[NotNull]` move makes irrelevant | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Xunit;
namespace Microsoft.AspNet.Routing.Tests
{
public class RouteOptionsTests
{
[Fact]
public void ConfigureRouting_ConfiguresOptionsProperly()
{
// Arrange
var services = new ServiceCollection().AddOptions();
// Act
services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint)));
var serviceProvider = services.BuildServiceProvider();
// Assert
var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name);
}
private class TestRouteConstraint : IRouteConstraint
{
public TestRouteConstraint(string pattern)
{
Pattern = pattern;
}
public string Pattern { get; private set; }
public bool Match(HttpContext httpContext,
IRouter route,
string routeKey,
IDictionary<string, object> values,
RouteDirection routeDirection)
{
throw new NotImplementedException();
}
}
}
}
``` |
2d041e3a-9e2c-41f8-9121-eb9e6d06bf34 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dbot.Utility {
public static class Settings {
public const int MessageLogSize = 200; // aka context size
public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10);
public const int SelfSpamSimilarity = 75;
public const int LongSpamSimilarity = 75;
public const int SelfSpamContextLength = 15;
public const int LongSpamContextLength = 26;
public const int LongSpamMinimumLength = 40;
public const int LongSpamLongerBanMultiplier = 3;
public const double NukeStringDelta = 0.7;
public const int NukeLoopWait = 2000;
public const int AegisLoopWait = 250;
public const int NukeDefaultDuration = 30;
public static bool IsMono;
public static string Timezone;
}
}
```
Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dbot.Utility {
public static class Settings {
public const int MessageLogSize = 200; // aka context size
public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10);
public const int SelfSpamSimilarity = 75;
public const int LongSpamSimilarity = 75;
public const int SelfSpamContextLength = 15;
public const int LongSpamContextLength = 26;
public const int LongSpamMinimumLength = 40;
public const int LongSpamLongerBanMultiplier = 3;
public const double NukeStringDelta = 0.7;
public const int NukeLoopWait = 0;
public const int AegisLoopWait = 0;
public const int NukeDefaultDuration = 30;
public static bool IsMono;
public static string Timezone;
}
}
``` |
f76d04a4-d48a-413d-90a3-a0112bd3c2b1 | {
"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.Screens;
using osu.Game.Overlays.FirstRunSetup;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene
{
public TestSceneFirstRunScreenUIScale()
{
AddStep("load screen", () =>
{
Child = new ScreenStack(new ScreenUIScale());
});
}
}
}
```
Add missing `OverlayColourProvider` in test scene | ```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.Screens;
using osu.Game.Overlays;
using osu.Game.Overlays.FirstRunSetup;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene
{
[Cached]
private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
public TestSceneFirstRunScreenUIScale()
{
AddStep("load screen", () =>
{
Child = new ScreenStack(new ScreenUIScale());
});
}
}
}
``` |
6488edf8-ae59-4a2a-b893-de3b38f95817 | {
"language": "C#"
} | ```c#
using Xunit;
namespace Farity.Tests
{
public class AlwaysTests
{
[Fact]
public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways()
{
var answerToLifeUniverseAndEverything = F.Always(42);
var answer = answerToLifeUniverseAndEverything();
Assert.Equal(answer, answerToLifeUniverseAndEverything());
Assert.Equal(answer, answerToLifeUniverseAndEverything(1));
Assert.Equal(answer, answerToLifeUniverseAndEverything("string", null));
Assert.Equal(answer, answerToLifeUniverseAndEverything(null, "str", 3));
Assert.Equal(answer, answerToLifeUniverseAndEverything(null, null, null, null));
}
}
}```
Use expected in tests for F.Always | ```c#
using Xunit;
namespace Farity.Tests
{
public class AlwaysTests
{
[Fact]
public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways()
{
const int expected = 42;
var answerToLifeUniverseAndEverything = F.Always(expected);
Assert.Equal(expected, answerToLifeUniverseAndEverything());
Assert.Equal(expected, answerToLifeUniverseAndEverything(1));
Assert.Equal(expected, answerToLifeUniverseAndEverything("string", null));
Assert.Equal(expected, answerToLifeUniverseAndEverything(null, "str", 3));
Assert.Equal(expected, answerToLifeUniverseAndEverything(null, null, null, null));
}
}
}``` |
d22b5797-0e4c-40e9-869d-fc0994f9d407 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseBeatmapPanel : OsuTestCase
{
[Resolved]
private APIAccess api { get; set; } = null;
[Resolved]
private RulesetStore rulesets { get; set; } = null;
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 });
req.Success += success;
api.Queue(req);
}
private void success(APIBeatmap apiBeatmap)
{
var beatmap = apiBeatmap.ToBeatmap(rulesets);
Add(new TournamentBeatmapPanel(beatmap)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
}
}
```
Allow dynamic recompilation of beatmap panel testcase | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseBeatmapPanel : OsuTestCase
{
[Resolved]
private APIAccess api { get; set; } = null;
[Resolved]
private RulesetStore rulesets { get; set; } = null;
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(TournamentBeatmapPanel),
};
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 });
req.Success += success;
api.Queue(req);
}
private void success(APIBeatmap apiBeatmap)
{
var beatmap = apiBeatmap.ToBeatmap(rulesets);
Add(new TournamentBeatmapPanel(beatmap)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
}
}
``` |
7b1b15ee-e2a5-4bfb-a443-ab96cdd59fda | {
"language": "C#"
} | ```c#
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
using System.IO;
using Lokad.Cqrs.Core.Outbox;
namespace Lokad.Cqrs.Feature.FilePartition
{
public sealed class FileQueueWriter : IQueueWriter
{
readonly DirectoryInfo _folder;
readonly IEnvelopeStreamer _streamer;
public string Name { get; private set; }
public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer)
{
_folder = folder;
_streamer = streamer;
Name = name;
}
public void PutMessage(ImmutableEnvelope envelope)
{
var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss-ffff}-{1}", envelope.CreatedOnUtc, Guid.NewGuid());
var full = Path.Combine(_folder.FullName, fileName);
var data = _streamer.SaveEnvelopeData(envelope);
File.WriteAllBytes(full, data);
}
}
}```
Fix order of high-frequency messages on file queues | ```c#
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
using System.IO;
using System.Threading;
using Lokad.Cqrs.Core.Outbox;
namespace Lokad.Cqrs.Feature.FilePartition
{
public sealed class FileQueueWriter : IQueueWriter
{
readonly DirectoryInfo _folder;
readonly IEnvelopeStreamer _streamer;
public string Name { get; private set; }
public readonly string Suffix ;
public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer)
{
_folder = folder;
_streamer = streamer;
Name = name;
Suffix = Guid.NewGuid().ToString().Substring(0, 4);
}
static long UniversalCounter;
public void PutMessage(ImmutableEnvelope envelope)
{
var id = Interlocked.Increment(ref UniversalCounter);
var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}-{1:00000000}-{2}", envelope.CreatedOnUtc, id, Suffix);
var full = Path.Combine(_folder.FullName, fileName);
var data = _streamer.SaveEnvelopeData(envelope);
File.WriteAllBytes(full, data);
}
}
}``` |
9f4c0b71-2aa3-4e91-985e-b11f9f5c28f3 | {
"language": "C#"
} | ```c#
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable
{
private readonly HttpClient _httpClient;
private readonly HttpClientHandler _httpHandler;
public RemoteHttpMessagePublisher()
{
_httpHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpHandler);
}
public void PublishMessage(IMessage message)
{
var content = new StringContent("Hello");
// TODO: Try shifting to async and await
// TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync
_httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message)
.ContinueWith(requestTask =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue and write out top facts for each country
var result = response.Content.ReadAsStringAsync().Result;
});
}
public void Dispose()
{
_httpClient.Dispose();
_httpHandler.Dispose();
}
}
}```
Remove not used using statements | ```c#
using System;
using System.Net.Http;
namespace Glimpse.Agent
{
public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable
{
private readonly HttpClient _httpClient;
private readonly HttpClientHandler _httpHandler;
public RemoteHttpMessagePublisher()
{
_httpHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpHandler);
}
public void PublishMessage(IMessage message)
{
var content = new StringContent("Hello");
// TODO: Try shifting to async and await
// TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync
_httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message)
.ContinueWith(requestTask =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue and write out top facts for each country
var result = response.Content.ReadAsStringAsync().Result;
});
}
public void Dispose()
{
_httpClient.Dispose();
_httpHandler.Dispose();
}
}
}``` |
7e81928a-7d51-4284-9cf5-f9e40bb1ebde | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.IO;
namespace AntlrGrammarEditor
{
public class Grammar
{
public const string AntlrDotExt = ".g4";
public const string ProjectDotExt = ".age";
public const string LexerPostfix = "Lexer";
public const string ParserPostfix = "Parser";
public string Name { get; set; }
public string Root { get; set; }
public string FileExtension { get; set; } = "txt";
public HashSet<Runtime> Runtimes = new HashSet<Runtime>();
public bool SeparatedLexerAndParser { get; set; }
public bool CaseInsensitive { get; set; }
public bool Preprocessor { get; set; }
public bool PreprocessorCaseInsensitive { get; set; }
public string PreprocessorRoot { get; set; }
public bool PreprocessorSeparatedLexerAndParser { get; set; }
public List<string> Files { get; set; } = new List<string>();
public List<string> TextFiles { get; set; } = new List<string>();
public string Directory { get; set; } = "";
}
}```
Add CaseInsensitiveType (None, lower, UPPER) | ```c#
using System.Collections.Generic;
namespace AntlrGrammarEditor
{
public enum CaseInsensitiveType
{
None,
lower,
UPPER
}
public class Grammar
{
public const string AntlrDotExt = ".g4";
public const string LexerPostfix = "Lexer";
public const string ParserPostfix = "Parser";
public string Name { get; set; }
public string Root { get; set; }
public string FileExtension { get; set; } = "txt";
public HashSet<Runtime> Runtimes = new HashSet<Runtime>();
public bool SeparatedLexerAndParser { get; set; }
public CaseInsensitiveType CaseInsensitiveType { get; set; }
public bool Preprocessor { get; set; }
public bool PreprocessorCaseInsensitive { get; set; }
public string PreprocessorRoot { get; set; }
public bool PreprocessorSeparatedLexerAndParser { get; set; }
public List<string> Files { get; set; } = new List<string>();
public List<string> TextFiles { get; set; } = new List<string>();
public string Directory { get; set; } = "";
}
}``` |
0ce1d37b-b118-4d8b-8a1f-0d98d890009d | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution
{
/// <summary>
/// A scary low-level reader-writer lock implementation.
/// <para>
/// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing
/// so, it avoids the cost of synchronisation and is much faster than a blocking lock.
/// </para>
/// </summary>
public class InterlockedReaderWriterLock : IReaderWriterLock
{
private const int OneWriter = 1 << 16;
private int counts;
public void EnterReadLock()
{
while (true)
{
int cur = Interlocked.Increment(ref counts);
if ((cur & 0xFFFF0000) == 0)
{
return;
}
Interlocked.Decrement(ref counts);
Thread.Yield();
}
}
public void ExitReadLock()
{
Interlocked.Decrement(ref counts);
}
public void EnterWriteLock()
{
while (true)
{
int cur = Interlocked.Add(ref counts, OneWriter);
if (cur == OneWriter)
{
return;
}
Interlocked.Add(ref counts, -OneWriter);
Thread.Yield();
}
}
public void ExitWriteLock()
{
Interlocked.Add(ref counts, -OneWriter);
}
}
}
```
Allow more of the word for the reader count, as the writer count will always be v small | ```c#
using System.Threading;
namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution
{
/// <summary>
/// A scary low-level reader-writer lock implementation.
/// <para>
/// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing
/// so, it avoids the cost of synchronisation and is much faster than a blocking lock.
/// </para>
/// </summary>
public class InterlockedReaderWriterLock : IReaderWriterLock
{
private const int OneWriter = 1 << 28;
private int counts;
public void EnterReadLock()
{
while (true)
{
int cur = Interlocked.Increment(ref counts);
if ((cur & 0xF0000000) == 0)
{
return;
}
Interlocked.Decrement(ref counts);
Thread.Yield();
}
}
public void ExitReadLock()
{
Interlocked.Decrement(ref counts);
}
public void EnterWriteLock()
{
while (true)
{
int cur = Interlocked.Add(ref counts, OneWriter);
if (cur == OneWriter)
{
return;
}
Interlocked.Add(ref counts, -OneWriter);
Thread.Yield();
}
}
public void ExitWriteLock()
{
Interlocked.Add(ref counts, -OneWriter);
}
}
}
``` |
d976eb7b-b5f3-4362-9825-b5aa82ce0eed | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(GridLayoutGroup))]
public class TabletUI : MonoBehaviour, ITablet
{
public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } }
public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } }
public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } }
public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } }
private TabletCellUI topLeft;
private TabletCellUI topRight;
private TabletCellUI bottomLeft;
private TabletCellUI bottomRight;
void Start() {
GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft;
GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal;
TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>();
if (cells.Length != 4)
throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length);
topLeft = cells[0];
topRight = cells[1];
bottomLeft = cells[2];
bottomRight = cells[3];
topLeft.parent = this;
topRight.parent = this;
bottomLeft.parent = this;
bottomRight.parent = this;
}
}
```
Make input tablet start states be set right | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(GridLayoutGroup))]
public class TabletUI : MonoBehaviour, ITablet
{
public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } }
public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } }
public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } }
public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } }
private TabletCellUI topLeft;
private TabletCellUI topRight;
private TabletCellUI bottomLeft;
private TabletCellUI bottomRight;
void Start() {
GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft;
GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal;
TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>();
if (cells.Length != 4)
throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length);
topLeft = cells[0];
topRight = cells[1];
bottomLeft = cells[2];
bottomRight = cells[3];
topLeft.parent = this;
topRight.parent = this;
bottomLeft.parent = this;
bottomRight.parent = this;
this.SetState(GlobalInput.InputTablet);
}
}
``` |
30491f2d-5438-4951-9014-5969f428354b | {
"language": "C#"
} | ```c#
using System;
namespace Atata
{
public static class JsonConfigMapper
{
public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder)
where TConfig : JsonConfig<TConfig>
{
if (config.BaseUrl != null)
builder.UseBaseUrl(config.BaseUrl);
if (config.RetryTimeout != null)
builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value));
if (config.RetryInterval != null)
builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value));
if (config.AssertionExceptionTypeName != null)
builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName));
if (config.UseNUnitTestName)
builder.UseNUnitTestName();
if (config.LogNUnitError)
builder.LogNUnitError();
if (config.TakeScreenshotOnNUnitError)
{
if (config.TakeScreenshotOnNUnitErrorTitle != null)
builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle);
else
builder.TakeScreenshotOnNUnitError();
}
return builder;
}
}
}
```
Add basic mapping functionality of log consumers | ```c#
using System;
namespace Atata
{
public static class JsonConfigMapper
{
public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder)
where TConfig : JsonConfig<TConfig>
{
if (config.BaseUrl != null)
builder.UseBaseUrl(config.BaseUrl);
if (config.RetryTimeout != null)
builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value));
if (config.RetryInterval != null)
builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value));
if (config.AssertionExceptionTypeName != null)
builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName));
if (config.UseNUnitTestName)
builder.UseNUnitTestName();
if (config.LogNUnitError)
builder.LogNUnitError();
if (config.TakeScreenshotOnNUnitError)
{
if (config.TakeScreenshotOnNUnitErrorTitle != null)
builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle);
else
builder.TakeScreenshotOnNUnitError();
}
if (config.LogConsumers != null)
{
foreach (var item in config.LogConsumers)
MapLogConsumer(item, builder);
}
return builder;
}
private static void MapLogConsumer(LogConsumerJsonSection logConsumerSection, AtataContextBuilder builder)
{
Type type = ResolveLogConsumerType(logConsumerSection.TypeName);
ILogConsumer logConsumer = (ILogConsumer)Activator.CreateInstance(type);
if (logConsumerSection.MinLevel != null)
;
if (logConsumerSection.SectionFinish == false)
;
}
private static Type ResolveLogConsumerType(string typeName)
{
//// Check log consumer aliases.
return Type.GetType(typeName);
}
}
}
``` |
14b9b738-681f-4bf1-bf2c-0b99b6451613 | {
"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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.UI;
namespace osu.Game.Rulesets.Taiko.Tests
{
[TestFixture]
public class TestSceneDrumTouchInputArea : DrawableTaikoRulesetTestScene
{
protected const double NUM_HIT_OBJECTS = 10;
protected const double HIT_OBJECT_TIME_SPACING_MS = 1000;
[BackgroundDependencyLoader]
private void load()
{
var drumTouchInputArea = new DrumTouchInputArea();
DrawableRuleset.KeyBindingInputManager.Add(drumTouchInputArea);
drumTouchInputArea.ShowTouchControls();
}
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
{
List<TaikoHitObject> hitObjects = new List<TaikoHitObject>();
for (int i = 0; i < NUM_HIT_OBJECTS; i++)
{
hitObjects.Add(new Hit
{
StartTime = Time.Current + i * HIT_OBJECT_TIME_SPACING_MS,
IsStrong = isOdd(i),
Type = isOdd(i / 2) ? HitType.Centre : HitType.Rim
});
}
var beatmap = new Beatmap<TaikoHitObject>
{
BeatmapInfo = { Ruleset = ruleset },
HitObjects = hitObjects
};
return beatmap;
}
private bool isOdd(int number)
{
return number % 2 == 0;
}
}
}
```
Make test actually test drum behaviours | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Taiko.UI;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Taiko.Tests
{
[TestFixture]
public class TestSceneDrumTouchInputArea : OsuTestScene
{
[Cached]
private TaikoInputManager taikoInputManager = new TaikoInputManager(new TaikoRuleset().RulesetInfo);
private DrumTouchInputArea drumTouchInputArea = null!;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create drum", () =>
{
Children = new Drawable[]
{
new InputDrum
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Height = 0.5f,
},
drumTouchInputArea = new DrumTouchInputArea
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Height = 0.5f,
},
};
});
}
[Test]
public void TestDrum()
{
AddStep("show drum", () => drumTouchInputArea.Show());
}
}
}
``` |
c2ac4b56-c732-4a70-82be-1a03d7d3e01d | {
"language": "C#"
} | ```c#
using Common;
using Exporter;
using System.Linq;
namespace Crayon
{
// cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext)
class RunCbxFlagBuilderWorker : AbstractCrayonWorker
{
public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args)
{
ExportCommand command = (ExportCommand)args[0].Value;
string finalCbxPath = (string)args[1].Value;
string cbxFile = FileUtil.GetPlatformPath(finalCbxPath);
int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s)));
string flags = cbxFile + " vmpid:" + processId;
if (runtimeArgs.Length > 0)
{
flags += " runtimeargs:" + runtimeArgs;
}
return new CrayonWorkerResult() { Value = flags };
}
}
}
```
Fix bug where running a project without export in a directory with a space was confusing the command line arg generator. | ```c#
using Common;
using Exporter;
using System.Linq;
namespace Crayon
{
// cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext)
class RunCbxFlagBuilderWorker : AbstractCrayonWorker
{
public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args)
{
ExportCommand command = (ExportCommand)args[0].Value;
string finalCbxPath = (string)args[1].Value;
string cbxFile = FileUtil.GetPlatformPath(finalCbxPath);
int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s)));
string flags = "\"" + cbxFile + "\" vmpid:" + processId;
if (runtimeArgs.Length > 0)
{
flags += " runtimeargs:" + runtimeArgs;
}
return new CrayonWorkerResult() { Value = flags };
}
}
}
``` |
5d68f986-5cc7-41f2-8256-3d377e101e1f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Rs317.Sharp
{
public static class Program
{
public static async Task Main(string[] args)
{
try
{
Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader");
await StartClient(0, 0, true);
}
catch(Exception exception)
{
throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}");
}
}
private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld)
{
Application.SetCompatibleTextRenderingDefault(false);
Task clientRunningAwaitable = signlink.startpriv("127.0.0.1");
ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld);
RsWinForm windowsFormApplication = new RsWinForm(765, 503);
RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics(), new DefaultWebSocketClientFactory());
windowsFormApplication.RegisterInputSubscriber(client1);
client1.createClientFrame(765, 503);
Application.Run(windowsFormApplication);
await clientRunningAwaitable
.ConfigureAwait(false);
}
}
}
```
Remove test websocket code from WF implementation | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Rs317.Sharp
{
public static class Program
{
public static async Task Main(string[] args)
{
try
{
Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader");
await StartClient(0, 0, true);
}
catch(Exception exception)
{
throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}");
}
}
private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld)
{
Application.SetCompatibleTextRenderingDefault(false);
Task clientRunningAwaitable = signlink.startpriv("127.0.0.1");
ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld);
RsWinForm windowsFormApplication = new RsWinForm(765, 503);
RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics());
windowsFormApplication.RegisterInputSubscriber(client1);
client1.createClientFrame(765, 503);
Application.Run(windowsFormApplication);
await clientRunningAwaitable
.ConfigureAwait(false);
}
}
}
``` |
9874985c-47f0-4186-91f1-a55cf6176849 | {
"language": "C#"
} | ```c#
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// 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 Cube.Log;
using NUnit.Framework;
using System.Reflection;
namespace Cube.FileSystem.Tests
{
/* --------------------------------------------------------------------- */
///
/// GlobalSetup
///
/// <summary>
/// NUnit で最初に実行する処理を記述するテストです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[SetUpFixture]
public class GlobalSetup
{
/* ----------------------------------------------------------------- */
///
/// OneTimeSetup
///
/// <summary>
/// 一度だけ実行される初期化処理です。
/// </summary>
///
/* ----------------------------------------------------------------- */
[OneTimeSetUp]
public void OneTimeSetup()
{
Logger.Configure();
Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
}
}
}
```
Fix to apply for the library updates. | ```c#
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// 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 NUnit.Framework;
using System.Reflection;
namespace Cube.FileSystem.Tests
{
/* --------------------------------------------------------------------- */
///
/// GlobalSetup
///
/// <summary>
/// NUnit で最初に実行する処理を記述するテストです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[SetUpFixture]
public class GlobalSetup
{
/* ----------------------------------------------------------------- */
///
/// OneTimeSetup
///
/// <summary>
/// 一度だけ実行される初期化処理です。
/// </summary>
///
/* ----------------------------------------------------------------- */
[OneTimeSetUp]
public void OneTimeSetup()
{
Logger.Configure();
Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
}
}
}
``` |
41c020c6-bcd3-4fc9-927c-07f4741b4dd2 | {
"language": "C#"
} | ```c#
using Flood.Tools.RPCGen;
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
namespace RPCGen.Tests
{
[TestFixture]
class RPCGenTests
{
[Test]
public void MainTest()
{
string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
Directory.CreateDirectory(genDirectory);
var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb");
var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb");
System.IO.File.Copy(sourceDllPath, destDllPath, true);
if (File.Exists(sourcePdbPath))
System.IO.File.Copy(sourcePdbPath, destPdbPath, true);
var args = new string[]
{
String.Format("-o={0}", genDirectory),
destDllPath
};
var ret = Flood.Tools.RPCGen.Program.Main(args);
Assert.AreEqual(0, ret);
}
[Test]
public void GenAPI()
{
string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests.API");
Directory.CreateDirectory(genDirectory);
var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
var rpcCompiler = new Compiler(sourceDllPath, genDirectory);
rpcCompiler.Process();
rpcCompiler.CompileApi(destDllPath);
}
}
}
```
Remove test of no longer existing method CompileApi. | ```c#
using Flood.Tools.RPCGen;
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
namespace RPCGen.Tests
{
[TestFixture]
class RPCGenTests
{
[Test]
public void MainTest()
{
string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
Directory.CreateDirectory(genDirectory);
var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb");
var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb");
System.IO.File.Copy(sourceDllPath, destDllPath, true);
if (File.Exists(sourcePdbPath))
System.IO.File.Copy(sourcePdbPath, destPdbPath, true);
var args = new string[]
{
String.Format("-o={0}", genDirectory),
destDllPath
};
var ret = Flood.Tools.RPCGen.Program.Main(args);
Assert.AreEqual(0, ret);
}
}
}
``` |
3dd7d2b6-2197-4297-b8a0-ff7829dcaffc | {
"language": "C#"
} | ```c#
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WordHunt.Data.Connection;
namespace WordHunt.Games.Create.Repository
{
public interface IGameRepository
{
void SaveGame(string name);
}
public class GameRepository : IGameRepository
{
private readonly IDbConnectionProvider connectionProvider;
public GameRepository(IDbConnectionProvider connectionProvider)
{
this.connectionProvider = connectionProvider;
}
public void SaveGame(string name)
{
var connection = connectionProvider.GetConnection();
connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)",
new { LanguageId = 1, Value = name });
}
}
}
```
Change usage of connection provider for connection factory. | ```c#
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WordHunt.Data.Connection;
namespace WordHunt.Games.Create.Repository
{
public interface IGameRepository
{
void SaveGame(string name);
}
public class GameRepository : IGameRepository
{
private readonly IDbConnectionFactory connectionFactory;
public GameRepository(IDbConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
}
public void SaveGame(string name)
{
using (var connection = connectionFactory.CreateConnection())
{
connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)",
new { LanguageId = 1, Value = name });
}
}
}
}
``` |
ad5d2f36-c5cb-428a-acc7-06e7ffa92238 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal static class ErrorCauseExtensions
{
public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict)
{
if (dict == null) return;
if (dict.TryGetValue("reason", out var reason)) rootCause.Reason = Convert.ToString(reason);
if (dict.TryGetValue("type", out var type)) rootCause.Type = Convert.ToString(type);
if (dict.TryGetValue("stack_trace", out var stackTrace)) rootCause.StackTrace = Convert.ToString(stackTrace);
// if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index);
// if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId);
// if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType);
}
}
}
```
Convert ErrorCause properties only when not null | ```c#
using System;
using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal static class ErrorCauseExtensions
{
public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict)
{
if (dict == null) return;
if (dict.TryGetValue("reason", out var reason) && reason != null) rootCause.Reason = Convert.ToString(reason);
if (dict.TryGetValue("type", out var type) && type != null) rootCause.Type = Convert.ToString(type);
if (dict.TryGetValue("stack_trace", out var stackTrace) && stackTrace != null) rootCause.StackTrace = Convert.ToString(stackTrace);
// if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index);
// if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId);
// if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType);
}
}
}
``` |
c138b284-c7f3-4ecf-9592-fb954c142196 | {
"language": "C#"
} | ```c#
using System.Collections.Concurrent;
namespace CircuitBreaker
{
public class CircuitBreakerStateStoreFactory
{
private static ConcurrentDictionary<string, ICircuitBreakerStateStore> _stateStores =
new ConcurrentDictionary<string, ICircuitBreakerStateStore>();
internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit)
{
// There is only one type of ICircuitBreakerStateStore to return...
// The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads)
// For example, a store for a db connection, web service client, and NAS storage could exist
if (!_stateStores.ContainsKey(circuit.GetType().Name))
{
_stateStores.TryAdd(circuit.GetType().Name, new CircuitBreakerStateStore(circuit));
}
return _stateStores[circuit.GetType().Name];
}
// TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary?
}
}```
Use Type as a key...instead of a string. | ```c#
using System;
using System.Collections.Concurrent;
namespace CircuitBreaker
{
public class CircuitBreakerStateStoreFactory
{
private static ConcurrentDictionary<Type, ICircuitBreakerStateStore> _stateStores =
new ConcurrentDictionary<Type, ICircuitBreakerStateStore>();
internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit)
{
// There is only one type of ICircuitBreakerStateStore to return...
// The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads)
// For example, a store for a db connection, web service client, and NAS storage could exist
if (!_stateStores.ContainsKey(circuit.GetType()))
{
_stateStores.TryAdd(circuit.GetType(), new CircuitBreakerStateStore(circuit));
}
return _stateStores[circuit.GetType()];
}
// TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary?
}
}``` |
549d4af7-9cc1-452f-a2a3-56c7eb8428ce | {
"language": "C#"
} | ```c#
using System;
using Mono.Terminal;
namespace School.REPL
{
public class REPL
{
public REPL()
{
}
public void Run()
{
Evaluator evaluator = new Evaluator();
LineEditor editor = new LineEditor("School");
Console.WriteLine("School REPL:");
string line;
while ((line = editor.Edit("> ", "")) != null)
{
if (!String.IsNullOrWhiteSpace(line))
{
try {
Value value = evaluator.Evaluate(line);
Console.WriteLine(value);
} catch (Exception e) {
Console.WriteLine(e);
}
}
}
}
}
}
```
Use continue to reduce one indentation level. | ```c#
using System;
using Mono.Terminal;
namespace School.REPL
{
public class REPL
{
public REPL()
{
}
public void Run()
{
Evaluator evaluator = new Evaluator();
LineEditor editor = new LineEditor("School");
Console.WriteLine("School REPL:");
string line;
while ((line = editor.Edit("> ", "")) != null)
{
if (String.IsNullOrWhiteSpace(line))
continue;
try {
Value value = evaluator.Evaluate(line);
Console.WriteLine(value);
} catch (Exception e) {
Console.WriteLine(e);
}
}
}
}
}
``` |
553b26be-5306-4123-a988-a2703375af24 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Company.Application1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
```
Use top level program for the Worker template | ```c#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Company.Application1;
using IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
``` |
2f5197fc-7b08-4d37-afac-d9a7f0feb83b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy.Memory.Mappers
{
class RomOnly : Cartridge
{
public RomOnly(CartridgeHeader header, byte[] romData)
: base(header, romData)
{
}
public override byte ReadByte(ushort address)
{
return _romData[address];
}
public override void WriteByte(ushort address, byte value)
{
return;
}
}
}
```
Return a value for reads from expansion RAM even though not present | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy.Memory.Mappers
{
class RomOnly : Cartridge
{
public RomOnly(CartridgeHeader header, byte[] romData)
: base(header, romData)
{
}
public override byte ReadByte(ushort address)
{
if (address < 0x8000)
{
return _romData[address];
}
else
return 0x00;
}
public override void WriteByte(ushort address, byte value)
{
return;
}
}
}
``` |
b0cf3a58-80fa-46f0-9fbc-188d18f86471 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
/// <summary>
/// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency.
/// </summary>
public class ColumnTestContainer : Container
{
protected override Container<Drawable> Content => content;
private readonly Container content;
[Cached]
private readonly Column column;
public ColumnTestContainer(int column, ManiaAction action)
{
this.column = new Column(column)
{
Action = { Value = action },
AccentColour = Color4.Orange
};
InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4)
{
RelativeSizeAxes = Axes.Both
};
}
}
}
```
Add odd/even type to test scenes | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
/// <summary>
/// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency.
/// </summary>
public class ColumnTestContainer : Container
{
protected override Container<Drawable> Content => content;
private readonly Container content;
[Cached]
private readonly Column column;
public ColumnTestContainer(int column, ManiaAction action)
{
this.column = new Column(column)
{
Action = { Value = action },
AccentColour = Color4.Orange,
ColumnType = column % 2 == 0 ? ColumnType.Even : ColumnType.Odd
};
InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4)
{
RelativeSizeAxes = Axes.Both
};
}
}
}
``` |
b5ab7ef1-2c56-44ad-8979-f8355057977f | {
"language": "C#"
} | ```c#
using Machine.Specifications;
namespace Quarks.Tests
{
[Subject(typeof(Inflector))]
public class When_using_pluralize_for_count
{
It should_pluralize_when_count_is_greater_than_two = () =>
"item".PluralizeForCount(2).ShouldEqual("items");
It should_pluralize_when_count_is_zero = () =>
"item".PluralizeForCount(0).ShouldEqual("items");
It should_not_pluralize_when_count_is_one = () =>
"item".PluralizeForCount(1).ShouldEqual("item");
}
}
```
Remove "public" access modifier from test class | ```c#
using Machine.Specifications;
namespace Quarks.Tests
{
[Subject(typeof(Inflector))]
class When_using_pluralize_for_count
{
It should_pluralize_when_count_is_greater_than_two = () =>
"item".PluralizeForCount(2).ShouldEqual("items");
It should_pluralize_when_count_is_zero = () =>
"item".PluralizeForCount(0).ShouldEqual("items");
It should_not_pluralize_when_count_is_one = () =>
"item".PluralizeForCount(1).ShouldEqual("item");
}
}
``` |
6001d683-ed39-42d8-b221-9bc0f2c47660 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Foundatio.Messaging {
public interface IMessage {
string Type { get; }
Type ClrType { get; }
byte[] Data { get; }
object GetBody();
IReadOnlyDictionary<string, string> Properties { get; }
}
public class Message : IMessage {
private Lazy<object> _getBody;
public Message(Func<object> getBody) {
if (getBody == null)
throw new ArgumentNullException("getBody");
_getBody = new Lazy<object>(getBody);
}
public string Type { get; set; }
public Type ClrType { get; set; }
public byte[] Data { get; set; }
public object GetBody() => _getBody.Value;
public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
}
}```
Add message debugger display to show the message type | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Foundatio.Messaging {
public interface IMessage {
string Type { get; }
Type ClrType { get; }
byte[] Data { get; }
object GetBody();
IReadOnlyDictionary<string, string> Properties { get; }
}
[DebuggerDisplay("Type: {Type}")]
public class Message : IMessage {
private Lazy<object> _getBody;
public Message(Func<object> getBody) {
if (getBody == null)
throw new ArgumentNullException("getBody");
_getBody = new Lazy<object>(getBody);
}
public string Type { get; set; }
public Type ClrType { get; set; }
public byte[] Data { get; set; }
public object GetBody() => _getBody.Value;
public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
}
}``` |
38ee63c7-dd94-4da1-b179-6e894c5c1c83 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
T[] objects = Resources.FindObjectsOfTypeAll<T>();
if (objects.Length != 1)
{
Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
}
else
{
_Instance = objects[0];
}
}
return _Instance;
}
}
/// <summary>
/// Called by Unity when destroying a MonoBehaviour. Scripts that extend
/// SingleInstance should be sure to call base.OnDestroy() to ensure the
/// underlying static _Instance reference is properly cleaned up.
/// </summary>
protected virtual void OnDestroy()
{
_Instance = null;
}
}
}```
Revert "Instance isn't found if class is on a disabled GameObject." | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
T[] objects = FindObjectsOfType<T>();
if (objects.Length != 1)
{
Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
}
else
{
_Instance = objects[0];
}
}
return _Instance;
}
}
/// <summary>
/// Called by Unity when destroying a MonoBehaviour. Scripts that extend
/// SingleInstance should be sure to call base.OnDestroy() to ensure the
/// underlying static _Instance reference is properly cleaned up.
/// </summary>
protected virtual void OnDestroy()
{
_Instance = null;
}
}
}``` |
12c7fa37-667a-4411-b520-85b06deb0137 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Razor;
namespace Microsoft.VisualStudio.Editor.Razor
{
[System.Composition.Shared]
[ExportWorkspaceService(typeof(ProjectPathProvider), ServiceLayer.Default)]
internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory
{
private readonly TextBufferProjectService _projectService;
[ImportingConstructor]
public DefaultProjectPathProviderFactory(TextBufferProjectService projectService)
{
if (projectService == null)
{
throw new ArgumentNullException(nameof(projectService));
}
_projectService = projectService;
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
if (workspaceServices == null)
{
throw new ArgumentNullException(nameof(workspaceServices));
}
return new DefaultProjectPathProvider(_projectService);
}
}
}
```
Fix mef attributes project path provider | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.Editor.Razor
{
[Shared]
[ExportWorkspaceServiceFactory(typeof(ProjectPathProvider), ServiceLayer.Default)]
internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory
{
private readonly TextBufferProjectService _projectService;
[ImportingConstructor]
public DefaultProjectPathProviderFactory(TextBufferProjectService projectService)
{
if (projectService == null)
{
throw new ArgumentNullException(nameof(projectService));
}
_projectService = projectService;
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
if (workspaceServices == null)
{
throw new ArgumentNullException(nameof(workspaceServices));
}
return new DefaultProjectPathProvider(_projectService);
}
}
}
``` |
53a97b39-da7f-4ae8-bffa-ad61a7e5caec | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNetOpen.PrerenderModule
{
public static class Constants
{
#region Const
public const string PrerenderIOServiceUrl = "http://service.prerender.io/";
public const int DefaultPort = 80;
public const string CrawlerUserAgentPattern = "(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)";
public const string EscapedFragment = "_escaped_fragment_";
public const string HttpProtocol = "http://";
public const string HttpsProtocol = "https://";
public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto";
public const string HttpHeader_XPrerenderToken = "X-Prerender-Token";
public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule";
#endregion
}
}
```
Add googlebot and bingbot to list of crawler user agents | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNetOpen.PrerenderModule
{
public static class Constants
{
#region Const
public const string PrerenderIOServiceUrl = "http://service.prerender.io/";
public const int DefaultPort = 80;
public const string CrawlerUserAgentPattern = "(bingbot)|(googlebot)|(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)";
public const string EscapedFragment = "_escaped_fragment_";
public const string HttpProtocol = "http://";
public const string HttpsProtocol = "https://";
public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto";
public const string HttpHeader_XPrerenderToken = "X-Prerender-Token";
public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule";
#endregion
}
}
``` |
65381f7a-728f-44b6-9599-5a44d4d54562 | {
"language": "C#"
} | ```c#
using System;
namespace Mitternacht.Modules.Verification.Exceptions {
public class UserAlreadyVerifyingException : Exception {}
public class UserAlreadyVerifiedException : Exception {}
public class UserCannotVerifyException : Exception { }
//public class Exception : Exception { }
}
```
Remove unnecessary comment and format file. | ```c#
using System;
namespace Mitternacht.Modules.Verification.Exceptions {
public class UserAlreadyVerifyingException : Exception { }
public class UserAlreadyVerifiedException : Exception { }
public class UserCannotVerifyException : Exception { }
}
``` |
ac0df414-fc6a-4fc3-8b14-727b02bea53d | {
"language": "C#"
} | ```c#
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/bootstrap.min.css")
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("Scripts", false)
</body>
</html>
```
Add styles and scripts to admin Layout. | ```c#
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/bootstrap.min.css")
@Styles.Render("~/Content/bootstrap-responsive.min.css")
@Styles.Render("~/bundles/font-awesome")
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/knockout")
<script type="text/javascript">
Modernizr.load({
test: Modernizr.input.placeholder,
nope: '/scripts/placeholder.js'
});
Modernizr.load({
test: Modernizr.inputtypes.date,
nope: '/scripts/datepicker.js'
});
</script>
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("Scripts", false)
</body>
</html>
``` |
67299e58-eecc-421a-a678-99b475c133a5 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Yin-Chun Wang")]
[assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")]
[assembly: AssemblyVersion(_ModernWPFVersionString.Release)]
[assembly: AssemblyFileVersion(_ModernWPFVersionString.Build)]
[assembly: AssemblyInformationalVersion(_ModernWPFVersionString.Build)]
static class _ModernWPFVersionString
{
// keep this same in majors releases
public const string Release = "1.0.0.0";
// change this for each nuget release
public const string Build = "1.1.30";
}
```
Put version info class under namespace. | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Yin-Chun Wang")]
[assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")]
[assembly: AssemblyVersion(ModernWPF._ModernWPFVersionString.Release)]
[assembly: AssemblyFileVersion(ModernWPF._ModernWPFVersionString.Build)]
[assembly: AssemblyInformationalVersion(ModernWPF._ModernWPFVersionString.Build)]
namespace ModernWPF
{
static class _ModernWPFVersionString
{
// keep this same in majors releases
public const string Release = "1.0.0.0";
// change this for each nuget release
public const string Build = "1.1.30";
}
}``` |
9a18e112-b0d5-48cc-b996-fef1c794dc4f | {
"language": "C#"
} | ```c#
using Devkoes.JenkinsManager.Model.Contract;
using Devkoes.JenkinsManager.UI;
using Devkoes.JenkinsManager.UI.Views;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
namespace Devkoes.JenkinsManager.VSPackage.ExposedServices
{
public class VisualStudioWindowHandler : IVisualStudioWindowHandler
{
public void ShowToolWindow()
{
// Get the instance number 0 of this tool window. This window is single instance so this instance
// is actually the only one.
// The last flag is set to true so that if the tool window does not exists it will be created.
ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true);
if ((null == window) || (null == window.Frame))
{
throw new NotSupportedException(Resources.CanNotCreateWindow);
}
IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
}
public void ShowSettingsWindow()
{
try
{
VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost));
}
catch (Exception ex)
{
ServicesContainer.OutputWindowLogger.LogOutput("Showing settings panel failed:", ex);
}
}
}
}
```
Revert "Logging has new overload for exceptions, use it" | ```c#
using Devkoes.JenkinsManager.Model.Contract;
using Devkoes.JenkinsManager.UI;
using Devkoes.JenkinsManager.UI.Views;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
namespace Devkoes.JenkinsManager.VSPackage.ExposedServices
{
public class VisualStudioWindowHandler : IVisualStudioWindowHandler
{
public void ShowToolWindow()
{
// Get the instance number 0 of this tool window. This window is single instance so this instance
// is actually the only one.
// The last flag is set to true so that if the tool window does not exists it will be created.
ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true);
if ((null == window) || (null == window.Frame))
{
throw new NotSupportedException(Resources.CanNotCreateWindow);
}
IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
}
public void ShowSettingsWindow()
{
try
{
VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost));
}
catch (Exception ex)
{
ServicesContainer.OutputWindowLogger.LogOutput(
"Showing settings panel failed:",
ex.ToString());
}
}
}
}
``` |
2a2736ad-a02e-48f6-8693-c81316dd0c68 | {
"language": "C#"
} | ```c#
using UnityEngine;
namespace PJEI.Invaders {
public class Level : MonoBehaviour {
public Alien[] lines;
public int width = 11;
public int pixelsBetweenAliens = 48;
private Alien[] aliens;
void Start() {
StartCoroutine(InitGame());
}
private System.Collections.IEnumerator InitGame() {
aliens = new Alien[lines.Length * width];
for (int i = lines.Length - 1; i >= 0; --i) {
for (int j = 0; j < width; ++j) {
var alien = (Alien)Instantiate(lines[i]);
alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens);
aliens[i * width + j] = alien;
yield return new WaitForSeconds(.1f);
}
}
foreach (var alien in aliens)
alien.Run();
}
}
}
```
Speed up alien start up positioning. | ```c#
using UnityEngine;
namespace PJEI.Invaders {
public class Level : MonoBehaviour {
public Alien[] lines;
public int width = 11;
public int pixelsBetweenAliens = 48;
private Alien[] aliens;
void Start() {
StartCoroutine(InitGame());
}
private System.Collections.IEnumerator InitGame() {
aliens = new Alien[lines.Length * width];
for (int i = lines.Length - 1; i >= 0; --i) {
for (int j = 0; j < width; ++j) {
var alien = (Alien)Instantiate(lines[i]);
alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens);
aliens[i * width + j] = alien;
yield return new WaitForSeconds(.05f);
}
}
foreach (var alien in aliens)
alien.Run();
}
}
}
``` |
caa114cd-6c82-46c7-a81c-c4e5127eea44 | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests
{
internal sealed class AuthorizeUser : Base
{
[Test]
public void CanAuthorizeUser()
{
const string email = "test@cronofy.com";
const string callbackUrl = "https://cronofy.com/test-callback";
const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";
Http.Stub(
HttpPost
.Url("https://api.cronofy.com/v1/service_account_authorizations")
.RequestHeader("Authorization", "Bearer " + AccessToken)
.RequestHeader("Content-Type", "application/json; charset=utf-8")
.RequestBodyFormat(
"{{\"email\":\"{0}\"," +
"\"callback_url\":\"{1}\"," +
"\"scope\":\"{2}\"" +
"}}",
email,
callbackUrl,
scopes)
.ResponseCode(202)
);
Client.AuthorizeUser(email, callbackUrl, scopes);
}
}
}
```
Add test for Enterprise Connect Authorize User with enumerable string | ```c#
using System;
using NUnit.Framework;
namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests
{
internal sealed class AuthorizeUser : Base
{
[Test]
public void CanAuthorizeUser()
{
const string email = "test@cronofy.com";
const string callbackUrl = "https://cronofy.com/test-callback";
const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";
Http.Stub(
HttpPost
.Url("https://api.cronofy.com/v1/service_account_authorizations")
.RequestHeader("Authorization", "Bearer " + AccessToken)
.RequestHeader("Content-Type", "application/json; charset=utf-8")
.RequestBodyFormat(
"{{\"email\":\"{0}\"," +
"\"callback_url\":\"{1}\"," +
"\"scope\":\"{2}\"" +
"}}",
email,
callbackUrl,
scopes)
.ResponseCode(202)
);
Client.AuthorizeUser(email, callbackUrl, scopes);
}
[Test]
public void CanAuthorizeUserWithEnumerableScopes()
{
const string email = "test@test.com";
const string callbackUrl = "https://test.com/test-callback";
string[] scopes = { "read_account", "list_calendars", "read_events", "create_event", "delete_event", "read_free_busy" };
Http.Stub(
HttpPost
.Url("https://api.cronofy.com/v1/service_account_authorizations")
.RequestHeader("Authorization", "Bearer " + AccessToken)
.RequestHeader("Content-Type", "application/json; charset=utf-8")
.RequestBodyFormat(
"{{\"email\":\"{0}\"," +
"\"callback_url\":\"{1}\"," +
"\"scope\":\"{2}\"" +
"}}",
email,
callbackUrl,
String.Join(" ", scopes))
.ResponseCode(202)
);
Client.AuthorizeUser(email, callbackUrl, scopes);
}
}
}
``` |
b55cc5bf-ebac-4073-9ec1-f9febb72c8bc | {
"language": "C#"
} | ```c#
using System;
using Mongo.Migration.Documents;
using Mongo.Migration.Documents.Serializers;
using Mongo.Migration.Services.Interceptors;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
namespace Mongo.Migration.Services.MongoDB
{
internal class MongoRegistrator : IMongoRegistrator
{
private readonly MigrationInterceptorProvider _provider;
private readonly DocumentVersionSerializer _serializer;
public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider)
{
_serializer = serializer;
_provider = provider;
}
public void Register()
{
BsonSerializer.RegisterSerializationProvider(_provider);
try
{
BsonSerializer.RegisterSerializer(typeof(DocumentVersion), _serializer);
}
catch (BsonSerializationException Exception)
{
// Catch if Serializer was registered already, not great. But for testing it must be catched.
}
}
}
}```
Use lookup before registering serializer | ```c#
using System;
using Mongo.Migration.Documents;
using Mongo.Migration.Documents.Serializers;
using Mongo.Migration.Services.Interceptors;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
namespace Mongo.Migration.Services.MongoDB
{
internal class MongoRegistrator : IMongoRegistrator
{
private readonly MigrationInterceptorProvider _provider;
private readonly DocumentVersionSerializer _serializer;
public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider)
{
_serializer = serializer;
_provider = provider;
}
public void Register()
{
RegisterSerializationProvider();
RegisterSerializer();
}
private void RegisterSerializationProvider()
{
BsonSerializer.RegisterSerializationProvider(_provider);
}
private void RegisterSerializer()
{
var foundSerializer = BsonSerializer.LookupSerializer(_serializer.ValueType);
if (foundSerializer == null)
BsonSerializer.RegisterSerializer(_serializer.ValueType, _serializer);
}
}
}``` |
e06d4b11-96e3-4edc-8c1a-fcced2387c44 | {
"language": "C#"
} | ```c#
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
namespace Propeller.Mvc.Model.Adapters
{
public class Image : IFieldAdapter
{
public string Url { get; set; }
public string Alt { get; set; }
public void InitAdapter(Item item, ID propId)
{
ImageField image = item.Fields[propId];
if (image == null)
return;
var mediaItem = image.MediaDatabase.GetItem(image.MediaID);
Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
Alt = image.Alt;
}
}
}```
Fix problem with image adapter when an item has empty standard values. | ```c#
using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
namespace Propeller.Mvc.Model.Adapters
{
public class Image : IFieldAdapter
{
public string Url { get; set; }
public string Alt { get; set; }
public void InitAdapter(Item item, ID propId)
{
Url = string.Empty;
Alt = string.Empty;
ImageField image = item.Fields[propId];
if (image == null ||image.MediaID == ItemIDs.Null)
return;
var mediaItem = image.MediaDatabase.GetItem(image.MediaID);
Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
Alt = image.Alt;
}
}
}``` |
c5f1d2ef-5beb-4ef1-b5c9-00a6856a3a07 | {
"language": "C#"
} | ```c#
using System.ComponentModel.DataAnnotations;
using System;
using asp_net_mvc_localization.Utils;
using Newtonsoft.Json.Serialization;
namespace asp_net_mvc_localization.Models
{
public class User
{
[Required]
public string Username { get; set; }
[Display]
[Required]
[MyEmailAddress]
public string Email { get; set; }
[Display]
[Required]
[MinLength(6)]
[MaxLength(64)]
public string Password { get; set; }
[Display]
[Range(1,125)]
public int Age { get; set; }
[Display]
public DateTime Birthday { get; set; }
[Display]
[Required]
[Range(0.1, 9.9)]
public double Rand { get; set; }
}
}```
Delete [Display](all work's without it), fix Date format in Create | ```c#
using System.ComponentModel.DataAnnotations;
using System;
using asp_net_mvc_localization.Utils;
using Newtonsoft.Json.Serialization;
namespace asp_net_mvc_localization.Models
{
public class User
{
[Required]
public string Username { get; set; }
[Required]
[MyEmailAddress]
public string Email { get; set; }
[Required]
[MinLength(6)]
[MaxLength(64)]
public string Password { get; set; }
[Range(1,125)]
public int Age { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime Birthday { get; set; }
[Required]
[Range(0.1, 9.9)]
public double Rand { get; set; }
}
}``` |
24217b12-7203-4a87-a1e4-2a4c4f92fe26 | {
"language": "C#"
} | ```c#
using System.Linq;
using JabbR.Services;
using Nancy;
using Nancy.ErrorHandling;
using Nancy.ViewEngines;
namespace JabbR.Nancy
{
public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler
{
private readonly IJabbrRepository _repository;
public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository)
: base(factory)
{
_repository = repository;
}
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
// only handle 40x and 50x
return (int)statusCode >= 400;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
string suggestRoomName = null;
if (statusCode == HttpStatusCode.NotFound &&
context.Request.Url.Path.Count(e => e == '/') == 1)
{
// trim / from start of path
var potentialRoomName = context.Request.Url.Path.Substring(1);
if (_repository.GetRoomByName(potentialRoomName) != null)
{
suggestRoomName = potentialRoomName;
}
}
var response = RenderView(
context,
"errorPage",
new
{
Error = statusCode,
ErrorCode = (int)statusCode,
SuggestRoomName = suggestRoomName
});
response.StatusCode = statusCode;
context.Response = response;
}
}
}```
Support 404 url suggestions for /rooms/xyz in addition to /xyz. | ```c#
using System.Text.RegularExpressions;
using JabbR.Services;
using Nancy;
using Nancy.ErrorHandling;
using Nancy.ViewEngines;
namespace JabbR.Nancy
{
public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler
{
private readonly IJabbrRepository _repository;
public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository)
: base(factory)
{
_repository = repository;
}
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
// only handle 40x and 50x
return (int)statusCode >= 400;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
string suggestRoomName = null;
if (statusCode == HttpStatusCode.NotFound)
{
var match = Regex.Match(context.Request.Url.Path, "^/(rooms/)?(?<roomName>[^/]+)$", RegexOptions.IgnoreCase);
if (match.Success)
{
var potentialRoomName = match.Groups["roomName"].Value;
if (_repository.GetRoomByName(potentialRoomName) != null)
{
suggestRoomName = potentialRoomName;
}
}
}
var response = RenderView(
context,
"errorPage",
new
{
Error = statusCode,
ErrorCode = (int)statusCode,
SuggestRoomName = suggestRoomName
});
response.StatusCode = statusCode;
context.Response = response;
}
}
}``` |
8fcbeb63-77a1-4b0c-a91f-02b733b50b07 | {
"language": "C#"
} | ```c#
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@{
Layout = "razor-layout.cshtml";
}
<h1>You're here based on ther German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
```
Fix typo on CultureView-de-De in Localization Demo | ```c#
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@{
Layout = "razor-layout.cshtml";
}
<h1>You're here based on the German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>
``` |
2c24569a-8427-42ac-9482-61293225759e | {
"language": "C#"
} | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
public class TheFeaturesProperty
{
[Fact]
public void ContainsExpectedFeatures()
{
var expected = "Cipher DPC ";
#if Q16HDRI
expected += "HDRI ";
#endif
#if WINDOWS_BUILD
expected += "OpenCL ";
#endif
#if OPENMP
expected += "OpenMP(2.0) ";
#endif
#if DEBUG_TEST
expected = "Debug " + expected;
#endif
Assert.Equal(expected, MagickNET.Features);
}
}
}
}
```
Use the new OperatingSystem class. | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickNETTests
{
public class TheFeaturesProperty
{
[Fact]
public void ContainsExpectedFeatures()
{
var expected = "Cipher DPC ";
#if Q16HDRI
expected += "HDRI ";
#endif
if (OperatingSystem.IsWindows)
expected += "OpenCL ";
#if OPENMP
expected += "OpenMP(2.0) ";
#endif
#if DEBUG_TEST
expected = "Debug " + expected;
#endif
Assert.Equal(expected, MagickNET.Features);
}
}
}
}
``` |
530a17eb-3f29-45e3-a060-988585d2b858 | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using RestSharp;
namespace TempoDB.Tests
{
[TestFixture]
public class TempoDBTests
{
[Test]
public void Defaults()
{
var tempodb = new TempoDB("key", "secret");
Assert.AreEqual("key", tempodb.Key);
Assert.AreEqual("secret", tempodb.Secret);
Assert.AreEqual("api.tempo-db.com", tempodb.Host);
Assert.AreEqual(443, tempodb.Port);
Assert.AreEqual(true, tempodb.Secure);
Assert.AreEqual("v1", tempodb.Version);
Assert.AreNotEqual(null, tempodb.Client);
Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client);
}
}
}
```
Use the correct assertion for testing null | ```c#
using NUnit.Framework;
using RestSharp;
namespace TempoDB.Tests
{
[TestFixture]
public class TempoDBTests
{
[Test]
public void Defaults()
{
var tempodb = new TempoDB("key", "secret");
Assert.AreEqual("key", tempodb.Key);
Assert.AreEqual("secret", tempodb.Secret);
Assert.AreEqual("api.tempo-db.com", tempodb.Host);
Assert.AreEqual(443, tempodb.Port);
Assert.AreEqual(true, tempodb.Secure);
Assert.AreEqual("v1", tempodb.Version);
Assert.IsNotNull(tempodb.Client);
Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client);
}
}
}
``` |
41bf8f1b-6c6b-4335-9955-d451f324ded0 | {
"language": "C#"
} | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
namespace StorageAzure.Tests
{
[TestClass()]
public class BlobTests
{
public Boolean Exist(string fileName)
{
var container = new BlobContanier().Create();
var blob = container.GetBlockBlobReference(fileName);
return blob.Exists();
}
[TestMethod()]
public void BlobPut()
{
var blob = new Blob();
var objeto = File.OpenRead(@"..\..\20160514_195832.jpg");
var fileName = Path.GetFileName(objeto.Name);
blob.Put(objeto);
objeto.Close();
Assert.IsTrue(Exist(fileName));
}
[TestMethod()]
public void BlobGet()
{
var blob = new Blob();
var fileName = "20160514_195832.jpg";
var fichero = blob.Get(fileName);
Assert.IsNotNull(fichero);
Assert.IsTrue(fichero.Length > 0);
}
[TestMethod()]
public void BlobDelete()
{
var blob = new Blob();
var fileName = "20160514_195832.jpg";
blob.Delete(fileName);
Assert.IsFalse(Exist(fileName));
}
}
}```
Test para comprobar qeu soporta ficheros de 55Mb. | ```c#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
namespace StorageAzure.Tests
{
[TestClass()]
public class BlobTests
{
public Boolean Exist(string fileName)
{
var container = new BlobContanier().Create();
var blob = container.GetBlockBlobReference(fileName);
return blob.Exists();
}
[TestMethod()]
public void BlobPut()
{
var blob = new Blob();
var objeto = File.OpenRead(@"..\..\20160514_195832.jpg");
var fileName = Path.GetFileName(objeto.Name);
blob.Put(objeto);
objeto.Close();
Assert.IsTrue(Exist(fileName));
}
[TestMethod()]
public void BlobPut_Fichero_de_55_Mb()
{
var blob = new Blob();
var objeto = File.OpenRead(@"..\..\20160512_194750.mp4");
var fileName = Path.GetFileName(objeto.Name);
blob.Put(objeto);
objeto.Close();
Assert.IsTrue(Exist(fileName));
}
[TestMethod()]
public void BlobGet()
{
var blob = new Blob();
var fileName = "20160514_195832.jpg";
var fichero = blob.Get(fileName);
Assert.IsNotNull(fichero);
Assert.IsTrue(fichero.Length > 0);
}
[TestMethod()]
public void BlobDelete()
{
var blob = new Blob();
var fileName = "20160514_195832.jpg";
blob.Delete(fileName);
Assert.IsFalse(Exist(fileName));
}
}
}``` |
c7e7f0f1-4bf8-4fa0-8742-f6eb6b6b6c75 | {
"language": "C#"
} | ```c#
namespace SkypeSharp {
public enum UserStatus {
OnlineStatus,
BuddyStatus,
ReceivedAuthRequest
}
public interface IUser : ISkypeObject {
string FullName { get; }
string Language { get; }
string Country { get; }
string City { get; }
void Authorize();
}
}```
Add some missing user statuses | ```c#
namespace SkypeSharp {
public enum UserStatus {
OnlineStatus,
BuddyStatus,
ReceivedAuthRequest,
IsAuthorized,
IsBlocked,
Timezone,
NROF_AUTHED_BUDDIES
}
public interface IUser : ISkypeObject {
string FullName { get; }
string Language { get; }
string Country { get; }
string City { get; }
void Authorize();
}
}``` |
77845cf9-6e10-4406-a7a5-e86bf7919d48 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
// ReSharper disable CheckNamespace
class DefaultBuild : GitHubBuild
{
public static void Main () => Execute<DefaultBuild> (x => x.Compile);
Target Restore => _ => _
.Executes (() =>
{
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild (s => DefaultSettings.MSBuildRestore);
else
NuGetRestore (SolutionFile);
});
Target Compile => _ => _
.DependsOn (Restore)
.Executes (() => MSBuild (s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion (MSBuildVersion)));
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles (SolutionDirectory, "*.xproj").Any ()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default (MSBuildVersion);
}
```
Change NuGetRestore to be executed unconditionally. | ```c#
using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
public static void Main () => Execute<DefaultBuild>(x => x.Compile);
Target Restore => _ => _
.Executes(() =>
{
NuGetRestore(SolutionFile);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion);
}
``` |
59474783-68d9-4c7e-b0dc-6b6e526613dd | {
"language": "C#"
} | ```c#
using System;
using Cake.Core.IO;
namespace Cake.Core.Scripting.Processors
{
/// <summary>
/// Processor for using statements.
/// </summary>
public sealed class UsingStatementProcessor : LineProcessor
{
/// <summary>
/// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class.
/// </summary>
/// <param name="environment">The environment.</param>
public UsingStatementProcessor(ICakeEnvironment environment)
: base(environment)
{
}
/// <summary>
/// Processes the specified line.
/// </summary>
/// <param name="processor">The script processor.</param>
/// <param name="context">The script processor context.</param>
/// <param name="currentScriptPath">The current script path.</param>
/// <param name="line">The line to process.</param>
/// <returns>
/// <c>true</c> if the processor handled the line; otherwise <c>false</c>.
/// </returns>
public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var tokens = Split(line);
if (tokens.Length <= 0)
{
return false;
}
if (!tokens[0].Equals("using", StringComparison.Ordinal))
{
return false;
}
var @namespace = tokens[1].TrimEnd(';');
context.AddNamespace(@namespace);
return true;
}
}
}```
Fix for using (IDisposable) statement | ```c#
using System;
using Cake.Core.IO;
namespace Cake.Core.Scripting.Processors
{
/// <summary>
/// Processor for using statements.
/// </summary>
public sealed class UsingStatementProcessor : LineProcessor
{
/// <summary>
/// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class.
/// </summary>
/// <param name="environment">The environment.</param>
public UsingStatementProcessor(ICakeEnvironment environment)
: base(environment)
{
}
/// <summary>
/// Processes the specified line.
/// </summary>
/// <param name="processor">The script processor.</param>
/// <param name="context">The script processor context.</param>
/// <param name="currentScriptPath">The current script path.</param>
/// <param name="line">The line to process.</param>
/// <returns>
/// <c>true</c> if the processor handled the line; otherwise <c>false</c>.
/// </returns>
public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var tokens = Split(line);
if (tokens.Length <= 1)
{
return false;
}
if (!tokens[0].Equals("using", StringComparison.Ordinal))
{
return false;
}
var @namespace = tokens[1].TrimEnd(';');
if (@namespace.StartsWith("("))
{
return false;
}
context.AddNamespace(@namespace);
return true;
}
}
}``` |
0e168ff6-b717-4906-90d7-7568ae4db36f | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using PacManGame;
namespace PacManGameTests
{
[TestFixture]
public class GameTimerTest
{
[Test]
public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1()
{
//Arrange
Board b = new Board(3, 4);
ITimer gameTimer = new GameTimer(500);
GameController gameController = new GameController(b, gameTimer);
gameTimer.Start();
//Act
Thread.Sleep(TimeSpan.FromMilliseconds(600));
// Assert
b.PacMan.Position.Should().Be(new Position(1, 1));
}
[Test]
public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled()
{
//Arrange
ITickable boardMock = Mock.Of<ITickable>();
FakeTimer timer = new FakeTimer();
GameController gameController = new GameController(boardMock, timer);
//Act
timer.OnElapsed();
//Assert
Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once);
}
}
public class FakeTimer : ITimer
{
public event EventHandler Elapsed;
public void Start()
{
throw new NotImplementedException();
}
public void OnElapsed()
{
if (Elapsed != null)
{
Elapsed(this, new EventArgs());
}
}
}
}```
Use a stub of ITimer instead of an actual implementation | ```c#
using System;
using System.Threading;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using PacManGame;
namespace PacManGameTests
{
[TestFixture]
public class GameTimerTest
{
[Test]
public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1()
{
//Arrange
Board b = new Board(3, 4);
ITimer gameTimer = new GameTimer(500);
GameController gameController = new GameController(b, gameTimer);
gameTimer.Start();
//Act
Thread.Sleep(TimeSpan.FromMilliseconds(600));
// Assert
b.PacMan.Position.Should().Be(new Position(1, 1));
}
[Test]
public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled()
{
//Arrange
ITickable boardMock = Mock.Of<ITickable>();
ITimer timerMock = Mock.Of<ITimer>();
GameController gameController = new GameController(boardMock, timerMock);
//Act
Mock.Get(timerMock).Raise(t => t.Elapsed += null, new EventArgs());
//Assert
Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once);
}
}
}``` |
6be835e9-65ab-4e4a-bf6a-a2e27b0241db | {
"language": "C#"
} | ```c#
using CommandLineParser.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LSTools.DebuggerFrontend
{
class Program
{
static void Main(string[] args)
{
var logFile = new FileStream(@"C:\Dev\DOS\LS\LsLib\DebuggerFrontend\bin\Debug\DAP.log", FileMode.Create);
var dap = new DAPStream();
dap.EnableLogging(logFile);
var dapHandler = new DAPMessageHandler(dap);
dapHandler.EnableLogging(logFile);
try
{
dap.RunLoop();
}
catch (Exception e)
{
using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true))
{
writer.Write(e.ToString());
Console.WriteLine(e.ToString());
}
}
}
}
}
```
Fix hardcoded DAP log path | ```c#
using CommandLineParser.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LSTools.DebuggerFrontend
{
class Program
{
static void Main(string[] args)
{
var currentPath = AppDomain.CurrentDomain.BaseDirectory;
var logFile = new FileStream(currentPath + "\\DAP.log", FileMode.Create);
var dap = new DAPStream();
dap.EnableLogging(logFile);
var dapHandler = new DAPMessageHandler(dap);
dapHandler.EnableLogging(logFile);
try
{
dap.RunLoop();
}
catch (Exception e)
{
using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true))
{
writer.Write(e.ToString());
Console.WriteLine(e.ToString());
}
}
}
}
}
``` |
71591571-3227-4a88-953b-cf8834d1e426 | {
"language": "C#"
} | ```c#
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Platform.GtkSharp
{
public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout
{
public PixelLayoutHandler()
{
Control = new Gtk.Fixed();
}
public void Add(Control child, int x, int y)
{
IGtkControl ctl = ((IGtkControl)child.Handler);
var gtkcontrol = (Gtk.Widget)child.ControlObject;
Control.Put(gtkcontrol, x, y);
ctl.Location = new Point(x, y);
gtkcontrol.ShowAll();
}
public void Move(Control child, int x, int y)
{
IGtkControl ctl = ((IGtkControl)child.Handler);
if (ctl.Location.X != x || ctl.Location.Y != y)
{
Control.Move (child.GetContainerWidget (), x, y);
ctl.Location = new Point(x, y);
}
}
public void Remove(Control child)
{
Control.Remove (child.GetContainerWidget ());
}
}
}
```
Fix adding controls to PixelLayout with a different container object | ```c#
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Platform.GtkSharp
{
public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout
{
public PixelLayoutHandler ()
{
Control = new Gtk.Fixed ();
}
public void Add (Control child, int x, int y)
{
var ctl = ((IGtkControl)child.Handler);
var gtkcontrol = child.GetContainerWidget ();
Control.Put (gtkcontrol, x, y);
ctl.Location = new Point (x, y);
if (this.Control.Visible)
gtkcontrol.ShowAll ();
}
public void Move (Control child, int x, int y)
{
var ctl = ((IGtkControl)child.Handler);
if (ctl.Location.X != x || ctl.Location.Y != y) {
Control.Move (child.GetContainerWidget (), x, y);
ctl.Location = new Point (x, y);
}
}
public void Remove (Control child)
{
Control.Remove (child.GetContainerWidget ());
}
}
}
``` |
b28b7ef6-d7c1-42fc-a06d-ed5df792f11d | {
"language": "C#"
} | ```c#
namespace WizardFramework.HTML
{
partial class HtmlWizardPage<TM>
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.webView = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webView
//
this.webView.AllowNavigation = false;
this.webView.AllowWebBrowserDrop = false;
this.webView.Dock = System.Windows.Forms.DockStyle.Fill;
this.webView.IsWebBrowserContextMenuEnabled = true;
this.webView.Location = new System.Drawing.Point(0, 0);
this.webView.MinimumSize = new System.Drawing.Size(20, 20);
this.webView.Name = "webView";
this.webView.Size = new System.Drawing.Size(150, 150);
this.webView.TabIndex = 0;
this.webView.WebBrowserShortcutsEnabled = true;
//
// HtmlWizardPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.webView);
this.Name = "HtmlWizardPage";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser webView;
}
}
```
Disable shortcuts and ContextMenu in web browser control. | ```c#
namespace WizardFramework.HTML
{
partial class HtmlWizardPage<TM>
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.webView = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webView
//
this.webView.AllowNavigation = false;
this.webView.AllowWebBrowserDrop = false;
this.webView.Dock = System.Windows.Forms.DockStyle.Fill;
this.webView.IsWebBrowserContextMenuEnabled = false;
this.webView.Location = new System.Drawing.Point(0, 0);
this.webView.MinimumSize = new System.Drawing.Size(20, 20);
this.webView.Name = "webView";
this.webView.Size = new System.Drawing.Size(150, 150);
this.webView.TabIndex = 0;
this.webView.WebBrowserShortcutsEnabled = false;
//
// HtmlWizardPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.webView);
this.Name = "HtmlWizardPage";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser webView;
}
}
``` |
4619bb0e-1f04-4e00-acae-8bdcb16d187e | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
namespace Azuria.Community
{
/// <summary>
/// </summary>
public class MessageEnumerable : IEnumerable<Message>
{
private readonly int _conferenceId;
private readonly bool _markAsRead;
private readonly Senpai _senpai;
internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true)
{
this._conferenceId = conferenceId;
this._senpai = senpai;
this._markAsRead = markAsRead;
}
#region Methods
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<Message> GetEnumerator()
{
return new MessageEnumerator(this._conferenceId, this._markAsRead, this._senpai);
}
#endregion
}
}```
Add property to whether mark new Messages as read or not | ```c#
using System.Collections;
using System.Collections.Generic;
namespace Azuria.Community
{
/// <summary>
/// </summary>
public class MessageEnumerable : IEnumerable<Message>
{
private readonly int _conferenceId;
private readonly Senpai _senpai;
internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true)
{
this._conferenceId = conferenceId;
this._senpai = senpai;
this.MarkAsRead = markAsRead;
}
#region Properties
/// <summary>
/// </summary>
public bool MarkAsRead { get; set; }
#endregion
#region Methods
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<Message> GetEnumerator()
{
return new MessageEnumerator(this._conferenceId, this.MarkAsRead, this._senpai);
}
#endregion
}
}``` |
d81ffb34-5fce-498c-a37f-bee5eec3449f | {
"language": "C#"
} | ```c#
using System;
namespace Avalonia.Styling
{
public class Styler : IStyler
{
public void ApplyStyles(IStyleable target)
{
_ = target ?? throw new ArgumentNullException(nameof(target));
// If the control has a themed templated parent then first apply the styles from
// the templated parent theme.
if (target.TemplatedParent is IStyleable styleableParent)
styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent);
// Next apply the control theme.
target.GetEffectiveTheme()?.TryAttach(target, target);
// Apply styles from the rest of the tree.
if (target is IStyleHost styleHost)
ApplyStyles(target, styleHost);
}
private void ApplyStyles(IStyleable target, IStyleHost host)
{
var parent = host.StylingParent;
if (parent != null)
ApplyStyles(target, parent);
if (host.IsStylesInitialized)
host.Styles.TryAttach(target, host);
}
}
}
```
Apply own control theme before templated parent's. | ```c#
using System;
namespace Avalonia.Styling
{
public class Styler : IStyler
{
public void ApplyStyles(IStyleable target)
{
_ = target ?? throw new ArgumentNullException(nameof(target));
// Apply the control theme.
target.GetEffectiveTheme()?.TryAttach(target, target);
// If the control has a themed templated parent then apply the styles from the
// templated parent theme.
if (target.TemplatedParent is IStyleable styleableParent)
styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent);
// Apply styles from the rest of the tree.
if (target is IStyleHost styleHost)
ApplyStyles(target, styleHost);
}
private void ApplyStyles(IStyleable target, IStyleHost host)
{
var parent = host.StylingParent;
if (parent != null)
ApplyStyles(target, parent);
if (host.IsStylesInitialized)
host.Styles.TryAttach(target, host);
}
}
}
``` |
a650dd98-53fb-43f7-8b23-1757e0d0726d | {
"language": "C#"
} | ```c#
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ZobShop.Models
{
public class ProductRating
{
public ProductRating(int rating, string content, int productId, User author)
{
this.Rating = rating;
this.Content = content;
this.ProductId = productId;
this.Author = author;
}
[Key]
public int ProductRatingId { get; set; }
public int Rating { get; set; }
public string Content { get; set; }
public int ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
[ForeignKey("Author")]
public string AuthorId { get; set; }
[ForeignKey("Id")]
public virtual User Author { get; set; }
}
}
```
Add default constructor for product rating | ```c#
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ZobShop.Models
{
public class ProductRating
{
public ProductRating()
{
}
public ProductRating(int rating, string content, Product product, User author)
{
this.Rating = rating;
this.Content = content;
this.Author = author;
this.Product = product;
}
[Key]
public int ProductRatingId { get; set; }
public int Rating { get; set; }
public string Content { get; set; }
public int ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
[ForeignKey("Author")]
public string AuthorId { get; set; }
[ForeignKey("Id")]
public virtual User Author { get; set; }
}
}
``` |
d7fb01be-f04d-4872-a6a6-b3be8b6b3a3c | {
"language": "C#"
} | ```c#
@inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel>
@using DotNetNuke.Web.Mvc.Helpers
@using R7.University.EduProgramProfiles.ViewModels
<td itemprop="eduCode">@Model.EduProfile.EduProgram.Code</td>
<td itemprop="eduName">@Model.EduProfileTitle</td>
<td itemprop="eduLevel">@Model.EduProfile.EduLevel.Title</td>
<td itemprop="eduForm">@Model.EduFormTitle</td>
<td itemprop="numberBFpriem">@Model.ActualFB</td>
<td itemprop="numberBRpriem">@Model.ActualRB</td>
<td itemprop="numberBMpriem">@Model.ActualMB</td>
<td itemprop="numberPpriem">@Model.ActualBC</td>
<td>@Model.ActualForeign</td>
```
Update microdata for actual number of students table | ```c#
@inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel>
@using DotNetNuke.Web.Mvc.Helpers
@using R7.University.EduProgramProfiles.ViewModels
<td itemprop="eduCode">@Model.EduProfile.EduProgram.Code</td>
<td itemprop="eduName">@Model.EduProfileTitle</td>
<td itemprop="eduLevel">@Model.EduProfile.EduLevel.Title</td>
<td itemprop="eduForm">@Model.EduFormTitle</td>
<td itemprop="numberBF">@Model.ActualFB</td>
<td itemprop="numberBR">@Model.ActualRB</td>
<td itemprop="numberBM">@Model.ActualMB</td>
<td itemprop="numberP">@Model.ActualBC</td>
<td itemprop="numberF">@Model.ActualForeign</td>
``` |
09938248-7be8-47a1-9d4d-447e486d308e | {
"language": "C#"
} | ```c#
//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたIListを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたTのIList</returns>
#else
/// <summary>
/// Returns shuffled IList of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IList of T.</returns>
#endif
public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList();
}
}
```
Make Shuffle<T> return IEnumerable<T> instead of IList<T>. | ```c#
//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたものを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたIEnumerable</returns>
#else
/// <summary>
/// Returns shuffled IEnumerable of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IEnumerable of T.</returns>
#endif
public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid());
}
}
``` |
aa0bb313-afc1-4bb0-9a25-f2d931786cd6 | {
"language": "C#"
} | ```c#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
/// <summary>
/// UIController holds references to GUI widgets and acts as data receiver for them.
/// </summary>
public class UIController : MonoBehaviour, IGUIUpdateTarget
{
public Text SpeedText;
public Slider ThrottleSlider;
public Slider EngineThrottleSlider;
public Text AltitudeText;
public void UpdateSpeed(float speed)
{
SpeedText.text = "IAS: " + (int)(speed * 1.94f) + " kn";
}
public void UpdateThrottle(float throttle)
{
ThrottleSlider.value = throttle;
}
public void UpdateEngineThrottle(float engineThrottle)
{
EngineThrottleSlider.value = engineThrottle;
}
public void UpdateAltitude(float altitude)
{
AltitudeText.text = "ALT: " + (int)(altitude * 3.28f) + " ft";
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
```
Switch from public properties to serializable private ones | ```c#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
/// <summary>
/// UIController holds references to GUI widgets and acts as data receiver for them.
/// </summary>
public class UIController : MonoBehaviour, IGUIUpdateTarget
{
[SerializeField]
private Text m_SpeedText;
[SerializeField]
private Text m_AltitudeText;
[SerializeField]
private Slider m_ThrottleSlider;
[SerializeField]
private Slider m_EngineThrottleSlider;
public void UpdateSpeed(float speed)
{
m_SpeedText.text = "IAS: " + (int)(speed * 1.94f) + " kn";
}
public void UpdateThrottle(float throttle)
{
m_ThrottleSlider.value = throttle;
}
public void UpdateEngineThrottle(float engineThrottle)
{
m_EngineThrottleSlider.value = engineThrottle;
}
public void UpdateAltitude(float altitude)
{
m_AltitudeText.text = "ALT: " + (int)(altitude * 3.28f) + " ft";
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
``` |
66f4145b-fae3-4903-8188-27531d84d68a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco
{
public class UserVariables : IVariableProvider
{
static readonly Dictionary<string, Func<string>> _variables = new Dictionary<string, Func<string>>();
public static void Add(string name, string value) => Add(name, () => value);
public static void Add(string name, Func<string> valueProvider)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (valueProvider == null)
throw new ArgumentNullException(nameof(valueProvider));
if (_variables.ContainsKey(name))
throw new ArgumentException($"User variable with the same name already exists: `{name}`");
_variables.Add(name, valueProvider);
}
public Dictionary<string, Func<string>> GetVariables() => _variables;
}
}
```
Allow to clear user defined vars. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco
{
public class UserVariables : IVariableProvider
{
static readonly Dictionary<string, Func<string>> _variables = new Dictionary<string, Func<string>>();
public static void Add(string name, string value) => Add(name, () => value);
public static void Add(string name, Func<string> valueProvider)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (valueProvider == null)
throw new ArgumentNullException(nameof(valueProvider));
if (_variables.ContainsKey(name))
throw new ArgumentException($"User variable with the same name already exists: `{name}`");
_variables.Add(name, valueProvider);
}
public static void Clear() => _variables.Clear();
public Dictionary<string, Func<string>> GetVariables() => _variables;
}
}
``` |
1bcfd15b-7874-45d5-a828-1a1726549965 | {
"language": "C#"
} | ```c#
namespace Samples
{
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
public class WpDriver : RemoteWebDriver, IHasTouchScreen
{
public WpDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
: base(commandExecutor, desiredCapabilities)
{
TouchScreen = new RemoteTouchScreen(this);
}
public WpDriver(ICapabilities desiredCapabilities)
: base(desiredCapabilities)
{
TouchScreen = new RemoteTouchScreen(this);
}
public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities)
: base(remoteAddress, desiredCapabilities)
{
TouchScreen = new RemoteTouchScreen(this);
}
public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
: base(remoteAddress, desiredCapabilities, commandTimeout)
{
TouchScreen = new RemoteTouchScreen(this);
}
public ITouchScreen TouchScreen { get; private set; }
}
}
```
Move touch screen initialization to property getter | ```c#
namespace Samples
{
#region
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
#endregion
public class WpDriver : RemoteWebDriver, IHasTouchScreen
{
#region Fields
private ITouchScreen touchScreen;
#endregion
#region Constructors and Destructors
public WpDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
: base(commandExecutor, desiredCapabilities)
{
}
public WpDriver(ICapabilities desiredCapabilities)
: base(desiredCapabilities)
{
}
public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities)
: base(remoteAddress, desiredCapabilities)
{
}
public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
: base(remoteAddress, desiredCapabilities, commandTimeout)
{
}
#endregion
#region Public Properties
public ITouchScreen TouchScreen
{
get
{
return this.touchScreen ?? (this.touchScreen = new RemoteTouchScreen(this));
}
}
#endregion
}
}
``` |
8b4ec02a-6059-458f-aeaa-00f1ff136366 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.Composition;
using System.Net.Http;
namespace NVika
{
internal sealed class AppVeyorBuildServer : IBuildServer
{
private readonly Logger _logger;
public string Name
{
get { return "AppVeyor"; }
}
[ImportingConstructor]
public AppVeyorBuildServer(Logger logger)
{
_logger = logger;
}
public bool CanApplyToCurrentContext()
{
return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR"));
}
public void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL"));
_logger.Debug("AppVeyor API url: {0}", httpClient.BaseAddress);
var responseTask = httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName });
responseTask.Wait();
_logger.Debug("AppVeyor CompilationMessage Response: {0}", responseTask.Result.StatusCode);
_logger.Debug(responseTask.Result.Content.ReadAsStringAsync().Result);
}
}
}
}
```
Add compilation message debug log | ```c#
using System;
using System.ComponentModel.Composition;
using System.Net.Http;
namespace NVika
{
internal sealed class AppVeyorBuildServer : IBuildServer
{
private readonly Logger _logger;
private readonly string _appVeyorAPIUrl;
public string Name
{
get { return "AppVeyor"; }
}
[ImportingConstructor]
public AppVeyorBuildServer(Logger logger)
{
_logger = logger;
_appVeyorAPIUrl = Environment.GetEnvironmentVariable("APPVEYOR_API_URL");
}
public bool CanApplyToCurrentContext()
{
return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR"));
}
public async void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(_appVeyorAPIUrl);
_logger.Debug("Send compilation message to AppVeyor:");
_logger.Debug("Message: {0}", message);
_logger.Debug("Category: {0}", category);
_logger.Debug("Details: {0}", details);
_logger.Debug("FileName: {0}", filename);
_logger.Debug("Line: {0}", line);
_logger.Debug("Column: {0}", offset);
_logger.Debug("ProjectName: {0}", projectName);
await httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName });
}
}
}
}
``` |
f2c4078a-66f2-441d-8598-80e439270882 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Primitives;
namespace osu.Framework.Graphics.Containers
{
public class SnapTargetContainer : SnapTargetContainer<Drawable>
{
}
/// <summary>
/// A <see cref="Container{T}"/> that acts a target for <see cref="EdgeSnappingContainer{T}"/>s.
/// It is automatically cached as <see cref="ISnapTargetContainer"/> so that it may be resolved by any
/// child <see cref="EdgeSnappingContainer{T}"/>s.
/// </summary>
public class SnapTargetContainer<T> : Container<T>, ISnapTargetContainer
where T : Drawable
{
public virtual RectangleF SnapRectangle => DrawRectangle;
public Quad SnapRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(SnapRectangle, other);
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs<ISnapTargetContainer>(this);
return dependencies;
}
}
}
```
Use Cached attribute rather than CreateChildDependencies | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Primitives;
namespace osu.Framework.Graphics.Containers
{
public class SnapTargetContainer : SnapTargetContainer<Drawable>
{
}
/// <summary>
/// A <see cref="Container{T}"/> that acts a target for <see cref="EdgeSnappingContainer{T}"/>s.
/// It is automatically cached as <see cref="ISnapTargetContainer"/> so that it may be resolved by any
/// child <see cref="EdgeSnappingContainer{T}"/>s.
/// </summary>
[Cached(typeof(ISnapTargetContainer))]
public class SnapTargetContainer<T> : Container<T>, ISnapTargetContainer
where T : Drawable
{
public virtual RectangleF SnapRectangle => DrawRectangle;
public Quad SnapRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(SnapRectangle, other);
}
}
``` |
52642a59-27ef-4ade-8ca2-501e3831ad08 | {
"language": "C#"
} | ```c#
using System.Diagnostics.CodeAnalysis;
using Microsoft.R.Editor.Application.Test.TestShell;
using Microsoft.R.Editor.ContentType;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.R.Editor.Application.Test.Validation {
[ExcludeFromCodeCoverage]
[TestClass]
public class ErrorTagTest {
[TestMethod]
[TestCategory("Interactive")]
public void R_ErrorTagsTest01() {
using (var script = new TestScript(RContentTypeDefinition.ContentType)) {
// Force tagger creation
var tagSpans = script.GetErrorTagSpans();
script.Type("x <- {");
script.Delete();
script.DoIdle(500);
tagSpans = script.GetErrorTagSpans();
string errorTags = script.WriteErrorTags(tagSpans);
Assert.AreEqual("[5 - 6] } expected\r\n", errorTags);
}
}
}
}
```
Add 'fix squiggly' to the test case | ```c#
using System.Diagnostics.CodeAnalysis;
using Microsoft.R.Editor.Application.Test.TestShell;
using Microsoft.R.Editor.ContentType;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.R.Editor.Application.Test.Validation {
[ExcludeFromCodeCoverage]
[TestClass]
public class ErrorTagTest {
[TestMethod]
[TestCategory("Interactive")]
public void R_ErrorTagsTest01() {
using (var script = new TestScript(RContentTypeDefinition.ContentType)) {
// Force tagger creation
var tagSpans = script.GetErrorTagSpans();
script.Type("x <- {");
script.Delete();
script.DoIdle(500);
tagSpans = script.GetErrorTagSpans();
string errorTags = script.WriteErrorTags(tagSpans);
Assert.AreEqual("[5 - 6] } expected\r\n", errorTags);
script.Type("}");
script.DoIdle(500);
tagSpans = script.GetErrorTagSpans();
Assert.AreEqual(0, tagSpans.Count);
}
}
}
}
``` |
29c23013-8bb3-4341-a931-cc7deb676b6e | {
"language": "C#"
} | ```c#
namespace LinqToTTreeInterfacesLib
{
/// <summary>
/// Interface for implementing an object that will contain a complete single query
/// </summary>
public interface IGeneratedCode
{
/// <summary>
/// Add a new statement to the current spot where the "writing" currsor is pointed.
/// </summary>
/// <param name="s"></param>
void Add(IStatement s);
/// <summary>
/// Book a variable at the inner most scope
/// </summary>
/// <param name="v"></param>
void Add(IVariable v);
/// <summary>
/// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code
/// (for example, a ROOT object that needs to be written to a TFile).
/// </summary>
/// <param name="v"></param>
void QueueForTransfer(string key, object value);
/// <summary>
/// Returns the outter most coding block
/// </summary>
IBookingStatementBlock CodeBody { get; }
/// <summary>
/// Adds an include file to be included for this query's C++ file.
/// </summary>
/// <param name="filename"></param>
void AddIncludeFile(string filename);
/// <summary>
/// Set the result of the current code contex.
/// </summary>
/// <param name="result"></param>
void SetResult(IVariable result);
/// <summary>
/// Returns the value that is the result of this calculation.
/// </summary>
IVariable ResultValue { get; }
}
}
```
Allow the scope popping code to work correctly when all you have is the Interface. | ```c#
namespace LinqToTTreeInterfacesLib
{
/// <summary>
/// Interface for implementing an object that will contain a complete single query
/// </summary>
public interface IGeneratedCode
{
/// <summary>
/// Add a new statement to the current spot where the "writing" currsor is pointed.
/// </summary>
/// <param name="s"></param>
void Add(IStatement s);
/// <summary>
/// Book a variable at the inner most scope
/// </summary>
/// <param name="v"></param>
void Add(IVariable v);
/// <summary>
/// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code
/// (for example, a ROOT object that needs to be written to a TFile).
/// </summary>
/// <param name="v"></param>
void QueueForTransfer(string key, object value);
/// <summary>
/// Returns the outter most coding block
/// </summary>
IBookingStatementBlock CodeBody { get; }
/// <summary>
/// Adds an include file to be included for this query's C++ file.
/// </summary>
/// <param name="filename"></param>
void AddIncludeFile(string filename);
/// <summary>
/// Set the result of the current code contex.
/// </summary>
/// <param name="result"></param>
void SetResult(IVariable result);
/// <summary>
/// Returns the value that is the result of this calculation.
/// </summary>
IVariable ResultValue { get; }
/// <summary>
/// Get/Set teh current scope...
/// </summary>
object CurrentScope { get; set; }
}
}
``` |
a10280ff-6cbd-486d-b081-a9f8c509d87e | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace SIL.Windows.Forms.Tests.Progress.LogBox
{
[TestFixture]
public class LogBoxTests
{
private Windows.Forms.Progress.LogBox progress;
[Test]
public void ShowLogBox()
{
Console.WriteLine("Showing LogBox");
using (var e = new LogBoxFormForTest())
{
progress = e.progress;
progress.WriteMessage("LogBox test");
progress.ShowVerbose = true;
for (int i = 0; i < 1000; i++)
{
progress.WriteVerbose(".");
}
progress.WriteMessage("done");
Console.WriteLine(progress.Text);
Console.WriteLine(progress.Rtf);
Console.WriteLine("Finished");
}
}
}
}
```
Disable a test hanging on TeamCity for Linux | ```c#
using System;
using NUnit.Framework;
namespace SIL.Windows.Forms.Tests.Progress.LogBox
{
[TestFixture]
public class LogBoxTests
{
private Windows.Forms.Progress.LogBox progress;
[Test]
[Category("KnownMonoIssue")] // this test hangs on TeamCity for Linux
public void ShowLogBox()
{
Console.WriteLine("Showing LogBox");
using (var e = new LogBoxFormForTest())
{
progress = e.progress;
progress.WriteMessage("LogBox test");
progress.ShowVerbose = true;
for (int i = 0; i < 1000; i++)
{
progress.WriteVerbose(".");
}
progress.WriteMessage("done");
Console.WriteLine(progress.Text);
Console.WriteLine(progress.Rtf);
Console.WriteLine("Finished");
}
}
}
}
``` |
645cda51-90b8-421c-b429-17fa77d1bd4e | {
"language": "C#"
} | ```c#
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace Stampsy.ImageSource
{
internal static class Extensions
{
public static IObservable<T> SurroundWith<T> (this IObservable<T> a, IObservable<T> b)
{
return b.Concat (a).Concat (b);
}
public static void RouteExceptions<T> (this Task task, IObserver<T> observer)
{
task.ContinueWith (t => {
observer.OnError (t.Exception.Flatten ());
}, TaskContinuationOptions.OnlyOnFaulted);
}
public static void RouteExceptions<T> (this Task task, TaskCompletionSource<T> tcs)
{
task.ContinueWith (t => {
tcs.TrySetException (t.Exception.Flatten ());
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
}
```
Add extension method to call Fetch on destination instance, e.g. _myFolder.Fetch ('dropbox://myfile.png') | ```c#
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace Stampsy.ImageSource
{
public static class Extensions
{
public static Task<TRequest> Fetch<TRequest> (this IDestination<TRequest> destination, Uri url)
where TRequest : Request
{
return ImageSource.Fetch (url, destination);
}
internal static IObservable<T> SurroundWith<T> (this IObservable<T> a, IObservable<T> b)
{
return b.Concat (a).Concat (b);
}
internal static void RouteExceptions<T> (this Task task, IObserver<T> observer)
{
task.ContinueWith (t => {
observer.OnError (t.Exception.Flatten ());
}, TaskContinuationOptions.OnlyOnFaulted);
}
internal static void RouteExceptions<T> (this Task task, TaskCompletionSource<T> tcs)
{
task.ContinueWith (t => {
tcs.TrySetException (t.Exception.Flatten ());
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
}
``` |
b57c0f1f-bde7-46ca-b868-92217671765f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType1]
[Target(@"
a: 'Text';
t: a type >>;
t dump_print
")]
[Output("(bit)*8[text_item]")]
public sealed class ArrayElementType : CompilerTest {}
}```
Access operator for array is now "item" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType1]
[Target(@"
a: 'Text';
t: a type item;
t dump_print
")]
[Output("(bit)*8[text_item]")]
public sealed class ArrayElementType : CompilerTest {}
}``` |
d07945b4-2030-45b7-a936-43db26ad1d8e | {
"language": "C#"
} | ```c#
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitleAttribute("Elders.Cronus")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus")]
[assembly: AssemblyProductAttribute("Elders.Cronus")]
[assembly: AssemblyVersionAttribute("2.0.0")]
[assembly: AssemblyInformationalVersionAttribute("2.0.0")]
[assembly: AssemblyFileVersionAttribute("2.0.0")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "2.0.0";
}
}
```
Prepare for new implementation of Aggregate Atomic Action | ```c#
// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("Elders.Cronus")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Cronus")]
[assembly: AssemblyCopyrightAttribute("Copyright © 2015")]
[assembly: AssemblyVersionAttribute("2.4.0.0")]
[assembly: AssemblyFileVersionAttribute("2.4.0.0")]
[assembly: AssemblyInformationalVersionAttribute("2.4.0-beta.1+1.Branch.release/2.4.0.Sha.3e4f8834fa8a63812fbfc3121045ffd5f065c6af")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "2.4.0.0";
}
}
``` |
9d1a9a57-4667-4a7f-a5c6-37b23a4e7702 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlogTemplate.Models;
namespace BlogTemplate.Services
{
public class SlugGenerator
{
private BlogDataStore _dataStore;
public SlugGenerator(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public string CreateSlug(string title)
{
Encoding utf8 = new UTF8Encoding(true);
string tempTitle = title;
char[] invalidChars = Path.GetInvalidPathChars();
foreach (char c in invalidChars)
{
string s = c.ToString();
string decodedS = utf8.GetString(c);
if (tempTitle.Contains(s))
{
int removeIdx = tempTitle.IndexOf(s);
tempTitle = tempTitle.Remove(removeIdx);
}
}
string slug = title.Replace(" ", "-");
int count = 0;
string tempSlug = slug;
while (_dataStore.CheckSlugExists(tempSlug))
{
count++;
tempSlug = $"{slug}-{count}";
}
return tempSlug;
}
}
}
```
Remove invalid characters from slug, but keep in title. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlogTemplate.Models;
namespace BlogTemplate.Services
{
public class SlugGenerator
{
private BlogDataStore _dataStore;
public SlugGenerator(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public string CreateSlug(string title)
{
string tempTitle = title;
char[] invalidChars = Path.GetInvalidFileNameChars();
foreach (char c in invalidChars)
{
tempTitle = tempTitle.Replace(c.ToString(), "");
}
string slug = tempTitle.Replace(" ", "-");
int count = 0;
string tempSlug = slug;
while (_dataStore.CheckSlugExists(tempSlug))
{
count++;
tempSlug = $"{slug}-{count}";
}
return tempSlug;
}
}
}
``` |
d44c1f7d-8dd9-47cc-bf6c-e0bf6e58676e | {
"language": "C#"
} | ```c#
using RainbowMage.OverlayPlugin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Cactbot {
public class CactbotOverlayConfig : OverlayConfigBase {
public static string CactbotAssemblyUri {
get { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); }
}
public static string CactbotDllRelativeUserUri {
get { return System.IO.Path.Combine(CactbotAssemblyUri, "../cactbot/user/"); }
}
public CactbotOverlayConfig(string name)
: base(name) {
// Cactbot only supports visibility toggling with the hotkey.
// It assumes all overlays are always locked and either are
// clickthru or not on a more permanent basis.
GlobalHotkeyType = GlobalHotkeyType.ToggleVisible;
}
private CactbotOverlayConfig() : base(null) {
}
public override Type OverlayType {
get { return typeof(CactbotOverlay); }
}
public bool LogUpdatesEnabled = true;
public double DpsUpdatesPerSecond = 3;
public string OverlayData = null;
public string RemoteVersionSeen = "0.0";
public string UserConfigFile = "";
}
}
```
Change default dps update rate to 0 | ```c#
using RainbowMage.OverlayPlugin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Cactbot {
public class CactbotOverlayConfig : OverlayConfigBase {
public static string CactbotAssemblyUri {
get { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); }
}
public static string CactbotDllRelativeUserUri {
get { return System.IO.Path.Combine(CactbotAssemblyUri, "../cactbot/user/"); }
}
public CactbotOverlayConfig(string name)
: base(name) {
// Cactbot only supports visibility toggling with the hotkey.
// It assumes all overlays are always locked and either are
// clickthru or not on a more permanent basis.
GlobalHotkeyType = GlobalHotkeyType.ToggleVisible;
}
private CactbotOverlayConfig() : base(null) {
}
public override Type OverlayType {
get { return typeof(CactbotOverlay); }
}
public bool LogUpdatesEnabled = true;
public double DpsUpdatesPerSecond = 0;
public string OverlayData = null;
public string RemoteVersionSeen = "0.0";
public string UserConfigFile = "";
}
}
``` |
d473a771-68cb-4e03-b3f7-ff375bca3ce5 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Pingu.Tests
{
class ToolHelper
{
public static ProcessResult RunPngCheck(string path)
{
var asm = typeof(ToolHelper).GetTypeInfo().Assembly;
var assemblyDir = Path.GetDirectoryName(asm.Location);
var pngcheckPath = Path.Combine(
assemblyDir,
"..",
"..",
"..",
"..",
"..",
"tools",
"pngcheck.exe");
return Exe(pngcheckPath, "-v", path);
}
public static ProcessResult Exe(string command, params string[] args)
{
var startInfo = new ProcessStartInfo {
FileName = command,
Arguments = string.Join(
" ",
args.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => "\"" + x + "\"")
),
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
var proc = Process.Start(startInfo);
var @out = proc.StandardOutput.ReadToEnd();
var err = proc.StandardError.ReadToEnd();
proc.WaitForExit(20000);
return new ProcessResult {
ExitCode = proc.ExitCode,
StandardOutput = @out,
StandardError = err
};
}
}
}
```
Enable tests running on !Windows too. | ```c#
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Pingu.Tests
{
class ToolHelper
{
public static ProcessResult RunPngCheck(string path)
{
var asm = typeof(ToolHelper).GetTypeInfo().Assembly;
var assemblyDir = Path.GetDirectoryName(asm.Location);
// It'll be on the path on Linux/Mac, we ship it for Windows.
var pngcheckPath = Path.DirectorySeparatorChar == '\\' ? Path.Combine(
assemblyDir,
"..",
"..",
"..",
"..",
"..",
"tools",
"pngcheck.exe") : "pngcheck";
return Exe(pngcheckPath, "-v", path);
}
public static ProcessResult Exe(string command, params string[] args)
{
var startInfo = new ProcessStartInfo {
FileName = command,
Arguments = string.Join(
" ",
args.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => "\"" + x + "\"")
),
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
var proc = Process.Start(startInfo);
var @out = proc.StandardOutput.ReadToEnd();
var err = proc.StandardError.ReadToEnd();
proc.WaitForExit(20000);
return new ProcessResult {
ExitCode = proc.ExitCode,
StandardOutput = @out,
StandardError = err
};
}
}
}
``` |
42e807be-6e1e-4bf3-ae9c-ca86b75495e6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomGen.Fluent
{
public interface IRandom : IFluentInterface
{
INumbers Numbers { get; }
INames Names { get; }
ITime Time { get; }
IText Text { get; }
IInternet Internet { get; }
IPhoneNumbers PhoneNumbers { get; }
/// <summary>
/// Returns a gen that chooses randomly from a list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="weights">Optional weights affecting the likelihood of an item being chosen. Same length as items</param>
Func<T> Items<T>(IEnumerable<T> items, IEnumerable<double> weights);
/// <summary>
/// Returns a gen that chooses randomly with equal weight for each item.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
Func<T> Items<T>(params T[] items);
/// <summary>
/// Returns a gen that chooses randomly from an Enum values
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="weights">Optional weights affecting the likelihood of a value being chosen. Same length as Enum values</param>
Func<T> Enum<T>(IEnumerable<double> weights = null) where T : struct, IConvertible;
/// <summary>
/// Generates random country names
/// Based on System.Globalisation
/// </summary>
Func<string> Countries();
}
}
```
Fix for supporting Items without weights. | ```c#
using System;
using System.Collections.Generic;
namespace RandomGen.Fluent
{
public interface IRandom : IFluentInterface
{
INumbers Numbers { get; }
INames Names { get; }
ITime Time { get; }
IText Text { get; }
IInternet Internet { get; }
IPhoneNumbers PhoneNumbers { get; }
/// <summary>
/// Returns a gen that chooses randomly from a list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="weights">Optional weights affecting the likelihood of an item being chosen. Same length as items</param>
Func<T> Items<T>(IEnumerable<T> items, IEnumerable<double> weights = null);
/// <summary>
/// Returns a gen that chooses randomly with equal weight for each item.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
Func<T> Items<T>(params T[] items);
/// <summary>
/// Returns a gen that chooses randomly from an Enum values
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="weights">Optional weights affecting the likelihood of a value being chosen. Same length as Enum values</param>
Func<T> Enum<T>(IEnumerable<double> weights = null) where T : struct, IConvertible;
/// <summary>
/// Generates random country names
/// Based on System.Globalisation
/// </summary>
Func<string> Countries();
}
}
``` |
5a6ef1f4-d7ad-44ce-998a-3639008d1e86 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinConfiguration
{
HitCirclePrefix,
HitCircleOverlap,
SliderBorderSize,
SliderPathRadius,
AllowSliderBallTint,
CursorExpand,
CursorRotate,
HitCircleOverlayAboveNumber,
HitCircleOverlayAboveNumer, // Some old skins will have this typo
SpinnerFrequencyModulate
}
}
```
Replace accidental tab with spaces | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinConfiguration
{
HitCirclePrefix,
HitCircleOverlap,
SliderBorderSize,
SliderPathRadius,
AllowSliderBallTint,
CursorExpand,
CursorRotate,
HitCircleOverlayAboveNumber,
HitCircleOverlayAboveNumer, // Some old skins will have this typo
SpinnerFrequencyModulate
}
}
``` |
fac98122-c7b2-43b3-a612-fef4541535e3 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameScreen : MonoBehaviour {
bool allowLevelLoad = true;
void OnEnable() {
allowLevelLoad = true;
}
public void LoadScene(string sceneName)
{
if (allowLevelLoad) {
allowLevelLoad = false;
SceneManager.LoadScene(sceneName);
}
}
// Update is called once per frame
void Update () {
}
}
```
Load next level after 0.33 seconds to prvent button from being stuck and animation to finish | ```c#
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameScreen : MonoBehaviour {
bool allowLevelLoad = true;
string nextLevel;
void OnEnable() {
allowLevelLoad = true;
}
public void LoadScene(string sceneName)
{
if (allowLevelLoad) {
allowLevelLoad = false;
nextLevel = sceneName;
Invoke("LoadNextLevel", 0.33f);
}
}
private void LoadNextLevel()
{
SceneManager.LoadScene(nextLevel);
}
}
``` |
0540e434-f7f7-4d4f-8c73-7cbacddcd4fa | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Markdig
{
/// <summary>
/// Provides a context that can be used as part of parsing Markdown documents.
/// </summary>
public sealed class MarkdownParserContext
{
/// <summary>
/// Gets or sets the context property collection.
/// </summary>
public IDictionary<object, object> Properties { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MarkdownParserContext" /> class.
/// </summary>
public MarkdownParserContext()
{
Properties = new Dictionary<object, object>();
}
}
}
```
Use Dictionary and removes setter | ```c#
using System.Collections.Generic;
namespace Markdig
{
/// <summary>
/// Provides a context that can be used as part of parsing Markdown documents.
/// </summary>
public sealed class MarkdownParserContext
{
/// <summary>
/// Gets or sets the context property collection.
/// </summary>
public Dictionary<object, object> Properties { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MarkdownParserContext" /> class.
/// </summary>
public MarkdownParserContext()
{
Properties = new Dictionary<object, object>();
}
}
}
``` |
b7c10c36-6737-4d79-946a-eb49054fd70d | {
"language": "C#"
} | ```c#
// Copyright © 2010-2015 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.Threading;
namespace CefSharp.Example
{
public class AsyncBoundObject
{
public void Error()
{
throw new Exception("This is an exception coming from C#");
}
public int Div(int divident, int divisor)
{
return divident / divisor;
}
public string Hello(string name)
{
return "Hello " + name;
}
public void DoSomething()
{
Thread.Sleep(1000);
}
}
}
```
Add DebuggerHidden attribute so VS doesn't break when `Break on User-Unhandled Exceptions` is checked | ```c#
// Copyright © 2010-2015 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.Diagnostics;
using System.Threading;
namespace CefSharp.Example
{
public class AsyncBoundObject
{
//We expect an exception here, so tell VS to ignore
[DebuggerHidden]
public void Error()
{
throw new Exception("This is an exception coming from C#");
}
//We expect an exception here, so tell VS to ignore
[DebuggerHidden]
public int Div(int divident, int divisor)
{
return divident / divisor;
}
public string Hello(string name)
{
return "Hello " + name;
}
public void DoSomething()
{
Thread.Sleep(1000);
}
}
}
``` |
3edc2b01-7427-4dc6-8121-45ec3a576ca5 | {
"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 System.Diagnostics;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Online.Solo;
using osu.Game.Rulesets;
using osu.Game.Scoring;
namespace osu.Game.Screens.Play
{
public class SoloPlayer : SubmittingPlayer
{
public SoloPlayer()
: this(null)
{
}
protected SoloPlayer(PlayerConfiguration configuration = null)
: base(configuration)
{
}
protected override APIRequest<APIScoreToken> CreateTokenRequest()
{
if (!(Beatmap.Value.BeatmapInfo.OnlineBeatmapID is int beatmapId))
return null;
if (!(Ruleset.Value.ID is int rulesetId) || Ruleset.Value.ID > ILegacyRuleset.MAX_LEGACY_RULESET_ID)
return null;
return new CreateSoloScoreRequest(beatmapId, rulesetId, Game.VersionHash);
}
protected override bool HandleTokenRetrievalFailure(Exception exception) => false;
protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token)
{
var beatmap = score.ScoreInfo.Beatmap;
Debug.Assert(beatmap.OnlineBeatmapID != null);
int beatmapId = beatmap.OnlineBeatmapID.Value;
return new SubmitSoloScoreRequest(beatmapId, token, score.ScoreInfo);
}
}
}
```
Copy score during submission process to ensure it isn't modified | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Online.Solo;
using osu.Game.Rulesets;
using osu.Game.Scoring;
namespace osu.Game.Screens.Play
{
public class SoloPlayer : SubmittingPlayer
{
public SoloPlayer()
: this(null)
{
}
protected SoloPlayer(PlayerConfiguration configuration = null)
: base(configuration)
{
}
protected override APIRequest<APIScoreToken> CreateTokenRequest()
{
if (!(Beatmap.Value.BeatmapInfo.OnlineBeatmapID is int beatmapId))
return null;
if (!(Ruleset.Value.ID is int rulesetId) || Ruleset.Value.ID > ILegacyRuleset.MAX_LEGACY_RULESET_ID)
return null;
return new CreateSoloScoreRequest(beatmapId, rulesetId, Game.VersionHash);
}
protected override bool HandleTokenRetrievalFailure(Exception exception) => false;
protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token)
{
var scoreCopy = score.DeepClone();
var beatmap = scoreCopy.ScoreInfo.Beatmap;
Debug.Assert(beatmap.OnlineBeatmapID != null);
int beatmapId = beatmap.OnlineBeatmapID.Value;
return new SubmitSoloScoreRequest(beatmapId, token, scoreCopy.ScoreInfo);
}
}
}
``` |
715ee602-4f76-4f77-8613-3106bf012053 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using omniBill.InnerComponents.Localization;
namespace omniBill.pages
{
/// <summary>
/// Interaction logic for AboutPage.xaml
/// </summary>
public partial class AboutPage : Page
{
public AboutPage()
{
InitializeComponent();
Version v = Assembly.GetEntryAssembly().GetName().Version;
lbVersion.Text = String.Format("v{0}.{1}.{2}", v.Major, v.Minor, v.Build);
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
}
```
Change the way version is displayed | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using omniBill.InnerComponents.Localization;
namespace omniBill.pages
{
/// <summary>
/// Interaction logic for AboutPage.xaml
/// </summary>
public partial class AboutPage : Page
{
public AboutPage()
{
InitializeComponent();
Version v = Assembly.GetEntryAssembly().GetName().Version;
String patch = (v.Build != 0) ? "." + v.Build.ToString() : String.Empty;
lbVersion.Text = String.Format("v{0}.{1}{2}", v.Major, v.Minor, patch);
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.