Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make sure to register interface rather than implementation | 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);
}
}
}
| 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);
}
}
}
|
Fix for chekcing the children belonging to MemberType tree. | 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));
}
}
}
| 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));
}
}
}
|
Add default kick message, inform who the kicker was | 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));
}
}
} | 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"));
}
}
} |
Fix tests - apparently CoreEventId.NavigationBaseIncludeIgnored now defaults to Error in EF Core 6. | 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)
{ }
}
}
| 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)
{ }
}
}
|
Fix link to remote R setup | // 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);
}
}
}
| // 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);
}
}
}
|
Make saved settings more readable | 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
}
}
| 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
}
}
|
Remove windows store test runner | 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;
}
}
}
| 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;
}
}
}
|
Revert "Tried to Figure Out Button: Failed" | 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);
}
}
}
}
| 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);
}
}
}
|
Add ScrollTo support to ScrollView | 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);
}
}
}
| 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;
}
}
}
}
}
|
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. | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: AssemblyDescription("Autofac multitenancy support library.")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Multitenant")]
[assembly: ComVisible(false)] |
Add model binder to binding config | 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());
}
}
} | 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());
}
}
} |
Address null ref when we can't get an Undo manager. | // 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;
}
}
} | // 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;
}
}
} |
Fix argon hit target area not being aligned correctly | // 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
},
};
}
}
}
| // 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;
}
}
}
|
Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable. | 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);
}
}
} | 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);
}
}
} |
Refactor to use UseBusDiagnostics extension | 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();
}
}
} | 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();
}
}
} |
Include the recording number in the default format | 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
};
}
}
}
| 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
};
}
}
}
|
Split enum test to 4 separate | 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>();
}
}
}
| 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>();
}
}
|
Return prefix and byte length | 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);
}
}
}
| 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);
}
}
}
|
Add FutureEmployment to data sources. | @{
ViewData["Title"] = "Data sources";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
| @{
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
|
Clean up syntax of index page | @{
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>
|
@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>
|
Add interpreter with skeleton game loop | using IFVM.Core;
namespace IFVM.Execution
{
public partial class Interpreter
{
public static uint Execute(Function function)
{
return 0;
}
}
}
| 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}");
}
}
}
}
|
Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet. | 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;
}
}
| 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;
}
}
|
Add missing `OverlayColourProvider` in test scene | // 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());
});
}
}
}
| // 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());
});
}
}
}
|
Use expected in tests for F.Always | 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));
}
}
} | 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));
}
}
} |
Allow dynamic recompilation of beatmap panel testcase | // 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
});
}
}
}
| // 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
});
}
}
}
|
Remove not used using statements | 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();
}
}
} | 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();
}
}
} |
Add CaseInsensitiveType (None, lower, UPPER) | 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; } = "";
}
} | 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; } = "";
}
} |
Allow more of the word for the reader count, as the writer count will always be v small | 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);
}
}
}
| 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);
}
}
}
|
Make input tablet start states be set right | 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;
}
}
| 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);
}
}
|
Add basic mapping functionality of log consumers | 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;
}
}
}
| 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);
}
}
}
|
Make test actually test drum behaviours | // 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;
}
}
}
| // 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());
}
}
}
|
Fix bug where running a project without export in a directory with a space was confusing the command line arg generator. | 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 };
}
}
}
| 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 };
}
}
}
|
Remove test websocket code from WF implementation | 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);
}
}
}
| 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);
}
}
}
|
Fix to apply for the library updates. | /* ------------------------------------------------------------------------- */
//
// 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());
}
}
}
| /* ------------------------------------------------------------------------- */
//
// 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());
}
}
}
|
Remove test of no longer existing method CompileApi. | 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);
}
}
}
| 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);
}
}
}
|
Change usage of connection provider for connection factory. | 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 });
}
}
}
| 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 });
}
}
}
}
|
Convert ErrorCause properties only when not null | 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);
}
}
}
| 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);
}
}
}
|
Use Type as a key...instead of a string. | 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?
}
} | 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?
}
} |
Use continue to reduce one indentation level. | 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);
}
}
}
}
}
}
| 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);
}
}
}
}
}
|
Add odd/even type to test scenes | // 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
};
}
}
}
| // 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
};
}
}
}
|
Remove "public" access modifier from test class | 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");
}
}
| 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");
}
}
|
Add message debugger display to show the message type | 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>();
}
} | 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>();
}
} |
Revert "Instance isn't found if class is on a disabled GameObject." | // 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;
}
}
} | // 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;
}
}
} |
Fix mef attributes project path provider | // 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);
}
}
}
| // 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);
}
}
}
|
Add googlebot and bingbot to list of crawler user agents | 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
}
}
| 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
}
}
|
Remove unnecessary comment and format file. | using System;
namespace Mitternacht.Modules.Verification.Exceptions {
public class UserAlreadyVerifyingException : Exception {}
public class UserAlreadyVerifiedException : Exception {}
public class UserCannotVerifyException : Exception { }
//public class Exception : Exception { }
}
| using System;
namespace Mitternacht.Modules.Verification.Exceptions {
public class UserAlreadyVerifyingException : Exception { }
public class UserAlreadyVerifiedException : Exception { }
public class UserCannotVerifyException : Exception { }
}
|
Add styles and scripts to admin Layout. | <!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>
| <!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>
|
Put version info class under namespace. | 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";
}
| 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";
}
} |
Revert "Logging has new overload for exceptions, use it" | 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);
}
}
}
}
| 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());
}
}
}
}
|
Add test for Enterprise Connect Authorize User with enumerable string | 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);
}
}
}
| 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);
}
}
}
|
Use lookup before registering serializer | 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.
}
}
}
} | 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);
}
}
} |
Fix problem with image adapter when an item has empty standard values. | 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;
}
}
} | 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;
}
}
} |
Delete [Display](all work's without it), fix Date format in Create | 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; }
}
} | 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; }
}
} |
Fix typo on CultureView-de-De in Localization Demo | @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>
| @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>
|
Use the new OperatingSystem class. | // 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);
}
}
}
}
| // 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);
}
}
}
}
|
Use the correct assertion for testing null | 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);
}
}
}
| 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);
}
}
}
|
Test para comprobar qeu soporta ficheros de 55Mb. | 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));
}
}
} | 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));
}
}
} |
Add some missing user statuses | 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();
}
} | 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();
}
} |
Fix for using (IDisposable) statement | 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;
}
}
} | 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;
}
}
} |
Use a stub of ITimer instead of an actual implementation | 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());
}
}
}
} | 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);
}
}
} |
Fix hardcoded DAP log path | 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());
}
}
}
}
}
| 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());
}
}
}
}
}
|
Fix adding controls to PixelLayout with a different container object | 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 ());
}
}
}
| 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 ());
}
}
}
|
Disable shortcuts and ContextMenu in web browser control. | 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;
}
}
| 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;
}
}
|
Add property to whether mark new Messages as read or not | 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
}
} | 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
}
} |
Apply own control theme before templated parent's. | 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);
}
}
}
| 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);
}
}
}
|
Add default constructor for product rating | 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; }
}
}
| 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; }
}
}
|
Make Shuffle<T> return IEnumerable<T> instead of IList<T>. | //
// 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();
}
}
| //
// 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());
}
}
|
Switch from public properties to serializable private ones | 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 ()
{
}
}
| 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 ()
{
}
}
|
Allow to clear user defined vars. | 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;
}
}
| 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;
}
}
|
Move touch screen initialization to property getter | 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; }
}
}
| 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
}
}
|
Add compilation message debug log | 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);
}
}
}
}
| 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 });
}
}
}
}
|
Use Cached attribute rather than CreateChildDependencies | // 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;
}
}
}
| // 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);
}
}
|
Add 'fix squiggly' to the test case | 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);
}
}
}
}
| 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);
}
}
}
}
|
Allow the scope popping code to work correctly when all you have is the Interface. |
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; }
}
}
|
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; }
}
}
|
Disable a test hanging on TeamCity for Linux | 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");
}
}
}
}
| 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");
}
}
}
}
|
Add extension method to call Fetch on destination instance, e.g. _myFolder.Fetch ('dropbox://myfile.png') | 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);
}
}
}
| 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);
}
}
}
|
Access operator for array is now "item" | 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 {}
} | 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 {}
} |
Prepare for new implementation of Aggregate Atomic Action | // <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";
}
}
| // <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";
}
}
|
Remove invalid characters from slug, but keep in title. | 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;
}
}
}
| 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;
}
}
}
|
Change default dps update rate to 0 | 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 = "";
}
}
| 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 = "";
}
}
|
Fix for supporting Items without weights. | 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();
}
}
| 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();
}
}
|
Replace accidental tab with spaces | // 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
}
}
| // 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
}
}
|
Load next level after 0.33 seconds to prvent button from being stuck and animation to finish | 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 () {
}
}
| 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);
}
}
|
Use Dictionary and removes setter | 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>();
}
}
}
| 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>();
}
}
}
|
Add DebuggerHidden attribute so VS doesn't break when `Break on User-Unhandled Exceptions` is checked | // 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);
}
}
}
| // 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);
}
}
}
|
Copy score during submission process to ensure it isn't modified | // 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);
}
}
}
| // 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);
}
}
}
|
Change the way version is displayed | 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;
}
}
}
| 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;
}
}
}
|
Fix 1M score being possible with only GREATs in mania | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class ManiaJudgement : Judgement
{
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Meh:
return 50;
case HitResult.Ok:
return 100;
case HitResult.Good:
return 200;
case HitResult.Great:
case HitResult.Perfect:
return 300;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class ManiaJudgement : Judgement
{
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Meh:
return 50;
case HitResult.Ok:
return 100;
case HitResult.Good:
return 200;
case HitResult.Great:
return 300;
case HitResult.Perfect:
return 320;
}
}
}
}
|
Make the about window have a space in the application name | using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
this.Text = String.Format("About {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = AssemblyVersion;
this.lastUpdatedBox.Text = LastUpdatedDate.ToString();
this.linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
#region Assembly Attribute Accessors
public static string AssemblyProduct {
get {
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if (attributes.Length == 0) {
return "";
}
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public static string AssemblyTitle {
get {
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0) {
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
if (!string.IsNullOrEmpty(titleAttribute.Title)) {
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public static string AssemblyVersion {
get {
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
#endregion Assembly Attribute Accessors
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
} | using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
this.Text = String.Format("About {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyTitle;
this.labelVersion.Text = AssemblyVersion;
this.lastUpdatedBox.Text = LastUpdatedDate.ToString();
this.linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
#region Assembly Attribute Accessors
public static string AssemblyTitle {
get {
return "Vigilant Cupcake";
}
}
public static string AssemblyVersion {
get {
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
#endregion Assembly Attribute Accessors
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
} |
Reset VM to be Service based | using System;
using System.Net.Http;
using System.Windows;
using SwitchClient.Classic;
using SwitchClient.Hyper;
namespace WpfSwitchClient
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
var client = new HttpClient()
{
BaseAddress = new Uri(String.Format("http://{0}:9090/", Environment.MachineName))
};
//var window = new MainWindow(new SwitchViewModel(new SwitchService(client)));
var window = new MainWindow(new SwitchHyperViewModel(client));
window.Show();
}
}
}
| using System;
using System.Net.Http;
using System.Windows;
using SwitchClient.Classic;
using SwitchClient.Hyper;
namespace WpfSwitchClient
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
var client = new HttpClient()
{
BaseAddress = new Uri(String.Format("http://{0}:9090/", Environment.MachineName))
};
var window = new MainWindow(new SwitchViewModel(new SwitchService(client)));
//var window = new MainWindow(new SwitchHyperViewModel(client));
window.Show();
}
}
}
|
Remove server header form http responses | using System;
using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FluentValidation.Mvc;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure;
using NLog;
using NLog.Targets;
using SFA.DAS.EAS.Infrastructure.Logging;
namespace SFA.DAS.EAS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private static RedisTarget _redisTarget; // Required to ensure assembly is copied to output.
protected void Application_Start()
{
LoggingConfig.ConfigureLogging();
TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("InstrumentationKey");
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
FluentValidationModelValidatorProvider.Configure();
}
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
_logger.Error(exception);
var tc = new TelemetryClient();
tc.TrackTrace($"{exception.Message} - {exception.InnerException}");
}
}
}
| using System;
using System.Security.Claims;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FluentValidation.Mvc;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure;
using NLog;
using NLog.Targets;
using SFA.DAS.EAS.Infrastructure.Logging;
namespace SFA.DAS.EAS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private static RedisTarget _redisTarget; // Required to ensure assembly is copied to output.
protected void Application_Start()
{
LoggingConfig.ConfigureLogging();
TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("InstrumentationKey");
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
FluentValidationModelValidatorProvider.Configure();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
application?.Context?.Response.Headers.Remove("Server");
}
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
_logger.Error(exception);
var tc = new TelemetryClient();
tc.TrackTrace($"{exception.Message} - {exception.InnerException}");
}
}
}
|
Update to default Razor snippet we use to help with Block List editor | @inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
@foreach (var layout in Model.Layout)
{
if (layout?.Udi == null) { continue; }
var data = layout.Data;
@Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout)
}
</div>
| @inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
if (!Model.Any()) { return; }
}
<div class="umb-block-list">
@foreach (var block in Model)
{
if (block?.ContentUdi == null) { continue; }
var data = block.Content;
@Html.Partial("BlockList/Components/" + data.ContentType.Alias, block)
}
</div>
|
Change field and variable names from context to handle | using System;
namespace PcscDotNet
{
public class PcscContext : IDisposable
{
private SCardContext _context;
private readonly Pcsc _pcsc;
private readonly IPcscProvider _provider;
public bool IsDisposed { get; private set; } = false;
public bool IsEstablished => _context.HasValue;
public Pcsc Pcsc => _pcsc;
public PcscContext(Pcsc pcsc)
{
_pcsc = pcsc;
_provider = pcsc.Provider;
}
public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc)
{
Establish(scope);
}
~PcscContext()
{
Dispose();
}
public unsafe PcscContext Establish(SCardScope scope)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish));
if (IsEstablished) throw new InvalidOperationException("Context has been established.");
SCardContext context;
_provider.SCardEstablishContext(scope, null, null, &context).ThrowIfNotSuccess();
_context = context;
return this;
}
public PcscContext Release()
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release));
if (IsEstablished)
{
_provider.SCardReleaseContext(_context).ThrowIfNotSuccess();
_context = SCardContext.Default;
}
return this;
}
public void Dispose()
{
if (IsDisposed) return;
Release();
GC.SuppressFinalize(this);
IsDisposed = true;
}
}
} | using System;
namespace PcscDotNet
{
public class PcscContext : IDisposable
{
private SCardContext _handle;
private readonly Pcsc _pcsc;
private readonly IPcscProvider _provider;
public bool IsDisposed { get; private set; } = false;
public bool IsEstablished => _handle.HasValue;
public Pcsc Pcsc => _pcsc;
public PcscContext(Pcsc pcsc)
{
_pcsc = pcsc;
_provider = pcsc.Provider;
}
public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc)
{
Establish(scope);
}
~PcscContext()
{
Dispose();
}
public unsafe PcscContext Establish(SCardScope scope)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish));
if (IsEstablished) throw new InvalidOperationException("Context has been established.");
SCardContext handle;
_provider.SCardEstablishContext(scope, null, null, &handle).ThrowIfNotSuccess();
_handle = handle;
return this;
}
public PcscContext Release()
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release));
if (IsEstablished)
{
_provider.SCardReleaseContext(_handle).ThrowIfNotSuccess();
_handle = SCardContext.Default;
}
return this;
}
public void Dispose()
{
if (IsDisposed) return;
Release();
GC.SuppressFinalize(this);
IsDisposed = true;
}
}
} |
Make TreeWalkForGitDir() delegate to LibGit2Sharp | namespace GitFlowVersion
{
using System.IO;
public class GitDirFinder
{
public static string TreeWalkForGitDir(string currentDirectory)
{
while (true)
{
var gitDir = Path.Combine(currentDirectory, @".git");
if (Directory.Exists(gitDir))
{
return gitDir;
}
var parent = Directory.GetParent(currentDirectory);
if (parent == null)
{
break;
}
currentDirectory = parent.FullName;
}
return null;
}
}
} | namespace GitFlowVersion
{
using System.IO;
using LibGit2Sharp;
public class GitDirFinder
{
public static string TreeWalkForGitDir(string currentDirectory)
{
string gitDir = Repository.Discover(currentDirectory);
if (gitDir != null)
{
return gitDir.TrimEnd(new []{ Path.DirectorySeparatorChar });
}
return null;
}
}
} |
Support both landscape and portrait mode | // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.SensorLandscape, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
| // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
|
Add ability to set width and height when setting the image | using WootzJs.Mvc.Mvc.Views.Css;
using WootzJs.Web;
namespace WootzJs.Mvc.Mvc.Views
{
public class Image : InlineControl
{
public Image()
{
}
public Image(string source)
{
Source = source;
}
public Image(string defaultSource, string highlightedSource)
{
Source = defaultSource;
MouseEntered += () => Source = highlightedSource;
MouseExited += () => Source = defaultSource;
}
public Image(string defaultSource, string highlightedSource, CssColor highlightColor)
{
Source = defaultSource;
MouseEntered += () =>
{
Source = highlightedSource;
Style.BackgroundColor = highlightColor;
};
MouseExited += () =>
{
Source = defaultSource;
Style.BackgroundColor = CssColor.Inherit;
};
}
public int Width
{
get { return int.Parse(Node.GetAttribute("width")); }
set { Node.SetAttribute("width", value.ToString()); }
}
public int Height
{
get { return int.Parse(Node.GetAttribute("height")); }
set { Node.SetAttribute("height", value.ToString()); }
}
public string Source
{
get { return Node.GetAttribute("src"); }
set { Node.SetAttribute("src", value); }
}
protected override Element CreateNode()
{
var node = Browser.Document.CreateElement("img");
node.Style.Display = "block";
return node;
}
}
} | using WootzJs.Mvc.Mvc.Views.Css;
using WootzJs.Web;
namespace WootzJs.Mvc.Mvc.Views
{
public class Image : InlineControl
{
public Image()
{
}
public Image(string source, int? width = null, int? height = null)
{
Source = source;
if (width != null)
Width = width.Value;
if (height != null)
Height = height.Value;
}
public Image(string defaultSource, string highlightedSource)
{
Source = defaultSource;
MouseEntered += () => Source = highlightedSource;
MouseExited += () => Source = defaultSource;
}
public Image(string defaultSource, string highlightedSource, CssColor highlightColor)
{
Source = defaultSource;
MouseEntered += () =>
{
Source = highlightedSource;
Style.BackgroundColor = highlightColor;
};
MouseExited += () =>
{
Source = defaultSource;
Style.BackgroundColor = CssColor.Inherit;
};
}
public int Width
{
get { return int.Parse(Node.GetAttribute("width")); }
set { Node.SetAttribute("width", value.ToString()); }
}
public int Height
{
get { return int.Parse(Node.GetAttribute("height")); }
set { Node.SetAttribute("height", value.ToString()); }
}
public string Source
{
get { return Node.GetAttribute("src"); }
set { Node.SetAttribute("src", value); }
}
protected override Element CreateNode()
{
var node = Browser.Document.CreateElement("img");
node.Style.Display = "block";
return node;
}
}
} |
Call signalr hub base method in case of exception in user codes of signalr hub events class | using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Foundation.Api.Middlewares.SignalR.Contracts;
namespace Foundation.Api.Middlewares.SignalR
{
public class MessagesHub : Hub
{
public override async Task OnConnected()
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnConnected(this);
await base.OnConnected();
}
public override async Task OnDisconnected(bool stopCalled)
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnDisconnected(this, stopCalled);
await base.OnDisconnected(stopCalled);
}
public override async Task OnReconnected()
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnReconnected(this);
await base.OnReconnected();
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Foundation.Api.Middlewares.SignalR.Contracts;
namespace Foundation.Api.Middlewares.SignalR
{
public class MessagesHub : Hub
{
public override async Task OnConnected()
{
try
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnConnected(this);
}
finally
{
await base.OnConnected();
}
}
public override async Task OnDisconnected(bool stopCalled)
{
try
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnDisconnected(this, stopCalled);
}
finally
{
await base.OnDisconnected(stopCalled);
}
}
public override async Task OnReconnected()
{
try
{
IOwinContext context = new OwinContext(Context.Request.Environment);
Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver");
await dependencyResolver.Resolve<IMessagesHubEvents>().OnReconnected(this);
}
finally
{
await base.OnReconnected();
}
}
}
} |
Use absolute path on linux | using System.Runtime.InteropServices;
namespace RebirthTracker
{
/// <summary>
/// Class to keep track of OS-specific configuration settings
/// </summary>
public static class Configuration
{
/// <summary>
/// Get the folder where files should be stored
/// </summary>
public static string GetDataDir()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return "..\\..\\..\\..\\..\\";
}
return "../../../../../../";
}
}
}
| using System.Runtime.InteropServices;
namespace RebirthTracker
{
/// <summary>
/// Class to keep track of OS-specific configuration settings
/// </summary>
public static class Configuration
{
/// <summary>
/// Get the folder where files should be stored
/// </summary>
public static string GetDataDir()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return "..\\..\\..\\..\\..\\";
}
return "/var/www/";
}
}
}
|
Create a TODO to revert the locking code. | using System;
using System.Text;
using P2E.Interfaces.Services;
namespace P2E.Services
{
public class UserCredentialsService : IUserCredentialsService
{
// Syncs console output/input between instance so that only one
// instance can request user credentials at any time.
private static readonly object LockObject = new object();
public string Loginname { get; private set; }
public string Password { get; private set; }
public void GetUserCredentials()
{
// Each instance can request credentials only once.
if (HasUserCredentials) return;
lock (LockObject)
{
if (HasUserCredentials) return;
Console.Out.Write("Username: ");
Loginname = Console.ReadLine();
Console.Out.Write("Password: ");
Password = GetPassword();
}
}
public bool HasUserCredentials => Loginname != null && Password != null;
private string GetPassword()
{
var password = new StringBuilder();
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password.Append(key.KeyChar);
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
return password.ToString();
}
}
} | using System;
using System.Text;
using P2E.Interfaces.Services;
namespace P2E.Services
{
public class UserCredentialsService : IUserCredentialsService
{
// TODO - revert that stuipd locking idea and introduce a Credentials class instead.
// Syncs console output/input between instance so that only one
// instance can request user credentials at any time.
private static readonly object LockObject = new object();
public string Loginname { get; private set; }
public string Password { get; private set; }
public void GetUserCredentials()
{
// Each instance can request credentials only once.
if (HasUserCredentials) return;
lock (LockObject)
{
if (HasUserCredentials) return;
Console.Out.Write("Username: ");
Loginname = Console.ReadLine();
Console.Out.Write("Password: ");
Password = GetPassword();
}
}
public bool HasUserCredentials => Loginname != null && Password != null;
private string GetPassword()
{
var password = new StringBuilder();
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password.Append(key.KeyChar);
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
return password.ToString();
}
}
} |
Add duration as statistical value for blocks in TeamCity | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
using Nuke.Common.Utilities;
namespace Nuke.Common.BuildServers
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : AnsiColorOutputSink
{
private readonly TeamCity _teamCity;
public TeamCityOutputSink(TeamCity teamCity)
: base(traceCode: "37", informationCode: "36", warningCode: "33", errorCode: "31", successCode: "32")
{
_teamCity = teamCity;
}
public override IDisposable WriteBlock(string text)
{
return DelegateDisposable.CreateBracket(
() => _teamCity.OpenBlock(text),
() => _teamCity.CloseBlock(text));
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
namespace Nuke.Common.BuildServers
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : AnsiColorOutputSink
{
private readonly TeamCity _teamCity;
public TeamCityOutputSink(TeamCity teamCity)
: base(traceCode: "37", informationCode: "36", warningCode: "33", errorCode: "31", successCode: "32")
{
_teamCity = teamCity;
}
public override IDisposable WriteBlock(string text)
{
var stopWatch = new Stopwatch();
return DelegateDisposable.CreateBracket(
() =>
{
_teamCity.OpenBlock(text);
stopWatch.Start();
},
() =>
{
_teamCity.CloseBlock(text);
_teamCity.AddStatisticValue(
$"NUKE_DURATION_{text.SplitCamelHumpsWithSeparator("_").ToUpper()}",
stopWatch.ElapsedMilliseconds.ToString());
stopWatch.Stop();
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.