Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix for display of hours | @model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.Hours Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div> | @model RedFolder.Podcast.Models.PodcastMetrics
<div class="podcast-metrics">
<div>
<h3 class="title">Number of episodes</h3>
<p class="metric">
@Model.NumberOfEpisodes
</p>
</div>
<div>
<h3 class="title">Total duration</h3>
<p class="metric">
@Model.TotalDuration.TotalHours.ToString("###") Hours, @Model.TotalDuration.Minutes Minutes
</p>
</div>
</div> |
Check if property has setter | using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
| using System.Linq;
namespace CmsEngine.Extensions
{
public static class ObjectExtensions
{
public static object MapTo(this object source, object target)
{
foreach (var sourceProp in source.GetType().GetProperties())
{
var targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
if (targetProp != null && targetProp.CanWrite && targetProp.GetSetMethod() != null && targetProp.GetType().Name == sourceProp.GetType().Name)
{
targetProp.SetValue(target, sourceProp.GetValue(source));
}
}
return target;
}
}
}
|
Set NullHandling to Ignore for key | using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO Need to not include key in serialization when its null to allow mb to use self-signed certificate.
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
| using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO This won't serialize key, but how does a user of this imposter know it's using the self-signed cert?
[JsonProperty("key", NullValueHandling = NullValueHandling.Ignore)]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
|
Put in defensive code to prevent crash when toggling wait cursor state. | using System;
using System.Linq;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Miscellaneous
{
/// ----------------------------------------------------------------------------------------
public class WaitCursor
{
/// ------------------------------------------------------------------------------------
public static void Show()
{
ToggleWaitCursorState(true);
}
/// ------------------------------------------------------------------------------------
public static void Hide()
{
ToggleWaitCursorState(false);
}
/// ------------------------------------------------------------------------------------
private static void ToggleWaitCursorState(bool turnOn)
{
Application.UseWaitCursor = turnOn;
foreach (var frm in Application.OpenForms.Cast<Form>())
{
if (frm.InvokeRequired)
frm.Invoke(new Action(() => frm.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default)));
else
frm.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default);
}
try
{
// I hate doing this, but setting the cursor property in .Net
// often doesn't otherwise take effect until it's too late.
Application.DoEvents();
}
catch { }
}
}
}
| using System;
using System.Linq;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Miscellaneous
{
/// ----------------------------------------------------------------------------------------
public class WaitCursor
{
/// ------------------------------------------------------------------------------------
public static void Show()
{
ToggleWaitCursorState(true);
}
/// ------------------------------------------------------------------------------------
public static void Hide()
{
ToggleWaitCursorState(false);
}
/// ------------------------------------------------------------------------------------
private static void ToggleWaitCursorState(bool turnOn)
{
Application.UseWaitCursor = turnOn;
foreach (var frm in Application.OpenForms.Cast<Form>().ToList())
{
Form form = frm; // Avoid resharper message about accessing foreach variable in closure.
try
{
if (form.InvokeRequired)
form.Invoke(new Action(() => form.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default)));
else
form.Cursor = (turnOn ? Cursors.WaitCursor : Cursors.Default);
}
catch
{
// Form may have closed and been disposed. Oh, well.
}
}
try
{
// I hate doing this, but setting the cursor property in .Net
// often doesn't otherwise take effect until it's too late.
Application.DoEvents();
}
catch { }
}
}
}
|
Use the managed thread id as identifier in our trace messages. | using System.Diagnostics;
namespace Renci.SshNet.Abstractions
{
internal static class DiagnosticAbstraction
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
private static readonly SourceSwitch SourceSwitch = new SourceSwitch("SshNetSwitch");
public static bool IsEnabled(TraceEventType traceEventType)
{
return SourceSwitch.ShouldTrace(traceEventType);
}
private static readonly TraceSource Loggging =
#if DEBUG
new TraceSource("SshNet.Logging", SourceLevels.All);
#else
new TraceSource("SshNet.Logging");
#endif // DEBUG
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
[Conditional("DEBUG")]
public static void Log(string text)
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
Loggging.TraceEvent(TraceEventType.Verbose, 1, text);
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
}
}
}
| using System.Diagnostics;
using System.Threading;
namespace Renci.SshNet.Abstractions
{
internal static class DiagnosticAbstraction
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
private static readonly SourceSwitch SourceSwitch = new SourceSwitch("SshNetSwitch");
public static bool IsEnabled(TraceEventType traceEventType)
{
return SourceSwitch.ShouldTrace(traceEventType);
}
private static readonly TraceSource Loggging =
#if DEBUG
new TraceSource("SshNet.Logging", SourceLevels.All);
#else
new TraceSource("SshNet.Logging");
#endif // DEBUG
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
[Conditional("DEBUG")]
public static void Log(string text)
{
#if FEATURE_DIAGNOSTICS_TRACESOURCE
Loggging.TraceEvent(TraceEventType.Verbose, Thread.CurrentThread.ManagedThreadId, text);
#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
}
}
}
|
Add a title for nested types | @{
Layout = "default";
Title = "Module";
}
<div class="row">
<div class="span1"></div>
<div class="span10" id="main">
<h1>@Model.Module.Name</h1>
<div class="xmldoc">
@Model.Module.Comment.FullText
</div>
@if (Model.Module.NestedTypes.Length > 0) {
<div>
<table class="table table-bordered type-list">
<thread>
<tr><td>Type</td><td>Description</td></tr>
</thread>
<tbody>
@foreach (var it in Model.Module.NestedTypes) {
<tr>
<td class="type-name">
<a href="@(it.UrlName).html">@Html.Encode(it.Name)</a>
</td>
<td class="xmldoc">@it.Comment.Blurb</td>
</tr>
}
</tbody>
</table>
</div>
}
@RenderPart("members", new {
Header = "Functions and values",
TableHeader = "Function or value",
Members = Model.Module.ValuesAndFuncs
})
@RenderPart("members", new {
Header = "Type extensions",
TableHeader = "Type extension",
Members = Model.Module.TypeExtensions
})
@RenderPart("members", new {
Header = "Active patterns",
TableHeader = "Active pattern",
Members = Model.Module.ActivePatterns
})
</div>
<div class="span1"></div>
</div> | @{
Layout = "default";
Title = "Module";
}
<div class="row">
<div class="span1"></div>
<div class="span10" id="main">
<h1>@Model.Module.Name</h1>
<div class="xmldoc">
@Model.Module.Comment.FullText
</div>
@if (Model.Module.NestedTypes.Length > 0) {
<h2>Nested types</h2>
<div>
<table class="table table-bordered type-list">
<thread>
<tr><td>Type</td><td>Description</td></tr>
</thread>
<tbody>
@foreach (var it in Model.Module.NestedTypes) {
<tr>
<td class="type-name">
<a href="@(it.UrlName).html">@Html.Encode(it.Name)</a>
</td>
<td class="xmldoc">@it.Comment.Blurb</td>
</tr>
}
</tbody>
</table>
</div>
}
@RenderPart("members", new {
Header = "Functions and values",
TableHeader = "Function or value",
Members = Model.Module.ValuesAndFuncs
})
@RenderPart("members", new {
Header = "Type extensions",
TableHeader = "Type extension",
Members = Model.Module.TypeExtensions
})
@RenderPart("members", new {
Header = "Active patterns",
TableHeader = "Active pattern",
Members = Model.Module.ActivePatterns
})
</div>
<div class="span1"></div>
</div> |
Fix call dot expression first test | namespace BScript.Tests.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BScript.Commands;
using BScript.Expressions;
using BScript.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CallDotExpressionTests
{
[TestMethod]
public void CreateCallDotExpression()
{
NameExpression nexpr = new NameExpression("foo");
IList<IExpression> exprs = new List<IExpression>() { new ConstantExpression(1), new ConstantExpression(2) };
var expr = new CallDotExpression(nexpr, exprs);
Assert.AreEqual(nexpr, expr.Expression);
Assert.AreSame(exprs, expr.ArgumentExpressions);
}
}
}
| namespace BScript.Tests.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BScript.Commands;
using BScript.Expressions;
using BScript.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CallDotExpressionTests
{
[TestMethod]
public void CreateCallDotExpression()
{
DotExpression dotexpr = new DotExpression(new NameExpression("foo"), "bar");
IList<IExpression> exprs = new List<IExpression>() { new ConstantExpression(1), new ConstantExpression(2) };
var expr = new CallDotExpression(dotexpr, exprs);
Assert.AreEqual(dotexpr, expr.Expression);
Assert.AreSame(exprs, expr.ArgumentExpressions);
}
}
}
|
Make sure the anchor is the parent element | using UnityEngine;
namespace Pear.InteractionEngine.Interactions
{
/// <summary>
/// Manipulating objects, such as resizing and moving, can be tricky when you have multiple scripts trying the modify the same thing.
/// This class creates an anchor element which is used to help these manipulations
/// </summary>
public class ObjectWithAnchor : MonoBehaviour
{
/// <summary>
/// Used to move and manipulate this object
/// </summary>
public Anchor AnchorElement;
void Awake()
{
if (AnchorElement != null)
return;
// Create the anchor element
GameObject anchor = new GameObject("Anchor");
AnchorElement = anchor.AddComponent<Anchor>();
AnchorElement.Child = this;
AnchorElement.transform.position = transform.position;
anchor.transform.SetParent(transform.parent, true);
transform.SetParent(AnchorElement.transform, true);
}
}
} | using UnityEngine;
namespace Pear.InteractionEngine.Interactions
{
/// <summary>
/// Manipulating objects, such as resizing and moving, can be tricky when you have multiple scripts trying the modify the same thing.
/// This class creates an anchor element which is used to help these manipulations
/// </summary>
public class ObjectWithAnchor : MonoBehaviour
{
/// <summary>
/// Used to move and manipulate this object
/// </summary>
public Anchor AnchorElement;
void Awake()
{
if (AnchorElement != null && AnchorElement.transform == transform.parent)
return;
// Create the anchor element
GameObject anchor = new GameObject("Anchor");
AnchorElement = anchor.AddComponent<Anchor>();
AnchorElement.Child = this;
AnchorElement.transform.position = transform.position;
anchor.transform.SetParent(transform.parent, true);
transform.SetParent(AnchorElement.transform, true);
}
}
} |
Fix a few 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.Extensions.ObjectExtensions;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
MusicController.CurrentTrack.AsNonNull().Tempo.Value = Clock.Rate;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using osu.Framework.Extensions.ObjectExtensions;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests.
/// </summary>
public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene
{
protected override void Update()
{
base.Update();
// note that this will override any mod rate application
if (MusicController.TrackLoaded)
{
Debug.Assert(MusicController.CurrentTrack != null);
MusicController.CurrentTrack.Tempo.Value = Clock.Rate;
}
}
}
}
|
Remove namespace and public from console app | using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| using System;
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
|
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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Attributed")]
[assembly: AssemblyDescription("Autofac Extensions for categorized discovery using attributes")]
[assembly: InternalsVisibleTo("Autofac.Tests.Extras.Attributed, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.Attributed")]
[assembly: InternalsVisibleTo("Autofac.Tests.Extras.Attributed, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)] |
Make equipped list a property instead of a field | using Newtonsoft.Json;
using OniBot.Interfaces;
using System.Collections.Generic;
namespace OniBot.CommandConfigs
{
public class SweepConfig : CommandConfig
{
public Dictionary<ulong, string> Equiped = new Dictionary<ulong, string>();
[JsonIgnore]
public override string ConfigKey => "sweep";
}
}
| using Newtonsoft.Json;
using OniBot.Interfaces;
using System.Collections.Generic;
namespace OniBot.CommandConfigs
{
public class SweepConfig : CommandConfig
{
public Dictionary<ulong, string> Equiped { get; set; } = new Dictionary<ulong, string>();
[JsonIgnore]
public override string ConfigKey => "sweep";
}
}
|
Remove editor functionality from VirtualBeatmapTrack | // 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.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
/// <summary>
/// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
/// </summary>
protected class VirtualBeatmapTrack : TrackVirtual
{
private const double excess_length = 1000;
private readonly IBeatmap beatmap;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
this.beatmap = beatmap;
updateVirtualLength();
}
protected override void UpdateState()
{
updateVirtualLength();
base.UpdateState();
}
private void updateVirtualLength()
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = excess_length;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + excess_length;
break;
default:
Length = lastObject.StartTime + excess_length;
break;
}
}
}
}
}
| // 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.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
/// <summary>
/// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
/// </summary>
protected class VirtualBeatmapTrack : TrackVirtual
{
private const double excess_length = 1000;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = excess_length;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + excess_length;
break;
default:
Length = lastObject.StartTime + excess_length;
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.EnterpriseLibraryConfigurator")]
[assembly: AssemblyDescription("Autofac support for Enterprise Library container configuration.")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.EnterpriseLibraryConfigurator")]
[assembly: ComVisible(false)] |
Use the AppSettings 'NuGetPackagePath' if exists and the default ~/Packages otherwise | using System;
using System.Web;
using System.Web.Hosting;
namespace NuGet.Server.Infrastructure {
public class PackageUtility {
internal static string PackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
public static Uri GetPackageUrl(string path, Uri baseUri) {
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path) {
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
| using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
namespace NuGet.Server.Infrastructure
{
public class PackageUtility
{
internal static string PackagePhysicalPath;
private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
static PackageUtility()
{
string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
if (string.IsNullOrEmpty(packagePath))
{
PackagePhysicalPath = DefaultPackagePhysicalPath;
}
else
{
PackagePhysicalPath = packagePath;
}
}
public static Uri GetPackageUrl(string path, Uri baseUri)
{
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path)
{
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
|
Fix local service discovery now that services are listening on 0.0.0.0 | using System;
using System.Linq;
using System.Net;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;
namespace KillrVideo.Protobuf.ServiceDiscovery
{
/// <summary>
/// Service discovery implementation that just points all service clients to the host/port where they
/// have been configured to run locally.
/// </summary>
public class LocalServiceDiscovery : IFindGrpcServices
{
private readonly IHostConfiguration _hostConfig;
private readonly Lazy<ServiceLocation> _localServicesIp;
public LocalServiceDiscovery(IHostConfiguration hostConfig)
{
if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
_hostConfig = hostConfig;
_localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
}
public ServiceLocation Find(ServiceDescriptor service)
{
return _localServicesIp.Value;
}
private ServiceLocation GetLocalGrpcServer()
{
// Get the host/port configuration for the Grpc Server
string host = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostConfigKey);
string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
int port = int.Parse(portVal);
return new ServiceLocation(host, port);
}
}
}
| using System;
using Google.Protobuf.Reflection;
using KillrVideo.Host.Config;
namespace KillrVideo.Protobuf.ServiceDiscovery
{
/// <summary>
/// Service discovery implementation that just points all service clients to 'localhost' and the port
/// where they have been configured to run locally.
/// </summary>
public class LocalServiceDiscovery : IFindGrpcServices
{
private readonly IHostConfiguration _hostConfig;
private readonly Lazy<ServiceLocation> _localServicesIp;
public LocalServiceDiscovery(IHostConfiguration hostConfig)
{
if (hostConfig == null) throw new ArgumentNullException(nameof(hostConfig));
_hostConfig = hostConfig;
_localServicesIp = new Lazy<ServiceLocation>(GetLocalGrpcServer);
}
public ServiceLocation Find(ServiceDescriptor service)
{
return _localServicesIp.Value;
}
private ServiceLocation GetLocalGrpcServer()
{
// Get the host/port configuration for the Grpc Server
string host = "localhost";
string portVal = _hostConfig.GetRequiredConfigurationValue(GrpcServerTask.HostPortKey);
int port = int.Parse(portVal);
return new ServiceLocation(host, port);
}
}
}
|
Set correct version number in main window | using System.Reflection;
using System.Windows;
namespace Arkivverket.Arkade.UI.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = string.Format(UI.Resources.UI.General_WindowTitle, typeof(App).Assembly.GetName().Version);
}
}
} | using System.Reflection;
using System.Windows;
namespace Arkivverket.Arkade.UI.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = string.Format(UI.Resources.UI.General_WindowTitle, "0.3.0"); // Todo - get correct application version from assembly
}
}
} |
Add a debug assert when a node is being reparented. | using System.Collections.Generic;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class ParentedNode : BaseNode
{
public TreeNode Parent { get; set; }
public IEnumerable<ParentedNode> GetParentChain()
{
var chain = new List<ParentedNode>();
ParentedNode current = this;
while (current.Parent != null)
{
chain.Add(current);
current = current.Parent;
}
chain.Reverse();
return chain;
}
public T GetNearestParent<T>() where T : ParentedNode
{
ParentedNode current = this;
while (current.Parent != null)
{
current = current.Parent;
if (current is T)
{
return (T)current;
}
}
return null;
}
}
}
| using System.Collections.Generic;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class ParentedNode : BaseNode
{
private TreeNode parent;
public TreeNode Parent
{
get => parent;
set
{
#if DEBUG
if (parent != null)
{
throw new System.InvalidOperationException("A node is being reparented");
}
#endif
parent = value;
}
}
public IEnumerable<ParentedNode> GetParentChain()
{
var chain = new List<ParentedNode>();
ParentedNode current = this;
while (current.Parent != null)
{
chain.Add(current);
current = current.Parent;
}
chain.Reverse();
return chain;
}
public T GetNearestParent<T>() where T : ParentedNode
{
ParentedNode current = this;
while (current.Parent != null)
{
current = current.Parent;
if (current is T)
{
return (T)current;
}
}
return null;
}
}
}
|
Set main page of bit application of cs client if no main page is provided (Due error/delay in initialization) | using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
MainPage = new ContentPage { };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
| using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
if (MainPage == null)
MainPage = new ContentPage { Title = "DefaultPage" };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
|
Expand the misspelled member name test | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
}
} | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
public Counter Decrement<T>()
{
Count--;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
WriteLine(printCounter.Dcrement<int>().Count);
}
} |
Use direct nuget public feed URLs | namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://go.microsoft.com/fwlink/?LinkID=206669";
public const string DefaultFeedUrl_v2 = "https://go.microsoft.com/fwlink/?LinkID=230477";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
} | namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://packages.nuget.org/v1/FeedService.svc/";
public const string DefaultFeedUrl_v2 = "https://www.nuget.org/api/v2/";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
}
|
Convert candidates to an array. | namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType);
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
| namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType).ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
|
Fix Clear-Bitmap being completely broken now, oops. | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
Bitmap bmp = null;
try {
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
SetBitmap(bmp);
} finally {
if (bmp != null) {
bmp.Dispose();
}
}
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
this.Bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
this.Graphics = Graphics.FromImage(this.Bitmap);
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
|
Use templated version of Resources.Load | using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load(HFT_WEB_DIR, typeof(TextAsset)) as TextAsset;
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
| using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load<TextAsset>(HFT_WEB_DIR);
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
|
Use the correct string for the warning key. (patch by olivier) | using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning"; //FIXME: Check this, i know it's wrong!
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning message";
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
|
Remove whitespace around app version | using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine;
}
return defaultValue;
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
} | using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine.Trim();
}
return defaultValue.Trim();
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
} |
Fix for one more IDE0078 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
internal static class Program
{
public static int Main(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
ShowUsage();
return 1;
}
var rulesetFilePath = args[0];
var editorconfigFilePath = args.Length == 2 ?
args[1] :
Path.Combine(Environment.CurrentDirectory, ".editorconfig");
try
{
Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return 2;
}
Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
return 0;
static void ShowUsage()
{
Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
return;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
namespace Microsoft.CodeAnalysis.RulesetToEditorconfig
{
internal static class Program
{
public static int Main(string[] args)
{
if (args.Length is < 1 or > 2)
{
ShowUsage();
return 1;
}
var rulesetFilePath = args[0];
var editorconfigFilePath = args.Length == 2 ?
args[1] :
Path.Combine(Environment.CurrentDirectory, ".editorconfig");
try
{
Converter.GenerateEditorconfig(rulesetFilePath, editorconfigFilePath);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return 2;
}
Console.WriteLine($"Successfully converted to '{editorconfigFilePath}'");
return 0;
static void ShowUsage()
{
Console.WriteLine("Usage: RulesetToEditorconfigConverter.exe <%ruleset_file%> [<%path_to_editorconfig%>]");
return;
}
}
}
}
|
Add a lock for StatisticCounter | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
if (_count == 0 || value > _maximum)
{
_maximum = value;
}
if (_count == 0 || value < _mininum)
{
_mininum = value;
}
_count++;
_total += value;
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private readonly object _lock = new object();
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
lock (_lock)
{
if (_count == 0 || value > _maximum)
{
_maximum = value;
}
if (_count == 0 || value < _mininum)
{
_mininum = value;
}
_count++;
_total += value;
}
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
|
Fix thumbnail retrieval options to actually work | using System;
using System.Collections.Generic;
namespace OneDrive
{
public class ThumbnailRetrievalOptions : RetrievalOptions
{
/// <summary>
/// List of thumbnail size names to return
/// </summary>
public string[] SelectThumbnailNames { get; set; }
/// <summary>
/// Retrieve the default thumbnails for an item
/// </summary>
public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }
/// <summary>
/// Returns a string like "select=small,medium" that can be used in an expand parameter value
/// </summary>
/// <returns></returns>
public override IEnumerable<ODataOption> ToOptions()
{
List<ODataOption> options = new List<ODataOption>();
SelectOData thumbnailSelect = null;
if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };
options.Add(new ExpandOData
{
PropertyToExpand = ApiConstants.ThumbnailsRelationshipName,
Select = thumbnailSelect
});
return EmptyCollection;
}
}
}
| using System;
using System.Collections.Generic;
namespace OneDrive
{
public class ThumbnailRetrievalOptions : RetrievalOptions
{
/// <summary>
/// List of thumbnail size names to return
/// </summary>
public string[] SelectThumbnailNames { get; set; }
/// <summary>
/// Retrieve the default thumbnails for an item
/// </summary>
public static ThumbnailRetrievalOptions Default { get { return new ThumbnailRetrievalOptions(); } }
/// <summary>
/// Returns a string like "select=small,medium" that can be used in an expand parameter value
/// </summary>
/// <returns></returns>
public override IEnumerable<ODataOption> ToOptions()
{
List<ODataOption> options = new List<ODataOption>();
SelectOData thumbnailSelect = null;
if (SelectThumbnailNames != null && SelectThumbnailNames.Length > 0)
{
thumbnailSelect = new SelectOData { FieldNames = SelectThumbnailNames };
options.Add(thumbnailSelect);
}
return options;
}
}
public static class ThumbnailSize
{
public const string Small = "small";
public const string Medium = "medium";
public const string Large = "large";
public const string SmallSquare = "smallSquare";
public const string MediumSquare = "mediumSquare";
public const string LargeSquare = "largeSquare";
public static string CustomSize(int width, int height, bool cropped)
{
return string.Format("c{0}x{1}{2}", width, height, cropped ? "_Crop" : "");
}
}
}
|
Add BsonSerializer for Date and Time | using System;
using InfinniPlatform.Sdk.Types;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace InfinniPlatform.DocumentStorage.MongoDB
{
/// <summary>
/// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
/// </summary>
internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
{
public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();
public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var reader = context.Reader;
var currentBsonType = reader.GetCurrentBsonType();
long totalSeconds;
switch (currentBsonType)
{
case BsonType.Double:
totalSeconds = (long)reader.ReadDouble();
break;
case BsonType.Int64:
totalSeconds = reader.ReadInt64();
break;
case BsonType.Int32:
totalSeconds = reader.ReadInt32();
break;
default:
throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
}
return new Time(totalSeconds);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
{
var writer = context.Writer;
writer.WriteDouble(value.TotalSeconds);
}
}
} | using System;
using InfinniPlatform.Sdk.Types;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace InfinniPlatform.DocumentStorage.MongoDB
{
/// <summary>
/// Реализует логику сериализации и десериализации <see cref="Time"/> для MongoDB.
/// </summary>
internal sealed class MongoTimeBsonSerializer : SerializerBase<Time>
{
public static readonly MongoTimeBsonSerializer Default = new MongoTimeBsonSerializer();
public override Time Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var reader = context.Reader;
var currentBsonType = reader.GetCurrentBsonType();
double totalSeconds;
switch (currentBsonType)
{
case BsonType.Double:
totalSeconds = reader.ReadDouble();
break;
case BsonType.Int64:
totalSeconds = reader.ReadInt64();
break;
case BsonType.Int32:
totalSeconds = reader.ReadInt32();
break;
default:
throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(typeof(Time))}' from BsonType '{currentBsonType}'.");
}
return new Time(totalSeconds);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Time value)
{
var writer = context.Writer;
writer.WriteDouble(value.TotalSeconds);
}
}
} |
Tweak beef001a to suppress Message when no additional shell items are present | using System;
using System.Text;
namespace ExtensionBlocks
{
public class Beef001a : BeefBase
{
public Beef001a(byte[] rawBytes)
: base(rawBytes)
{
if (Signature != 0xbeef001a)
{
throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
}
var len = 0;
var index = 10;
while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
{
len += 1;
}
var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);
FileDocumentTypeString = uname;
index += len + 3; // move past string and end of string marker
//is index 24?
//TODO get shell item list
Message =
"Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";
VersionOffset = BitConverter.ToInt16(rawBytes, index);
}
public string FileDocumentTypeString { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine();
sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");
return sb.ToString();
}
}
} | using System;
using System.Text;
namespace ExtensionBlocks
{
public class Beef001a : BeefBase
{
public Beef001a(byte[] rawBytes)
: base(rawBytes)
{
if (Signature != 0xbeef001a)
{
throw new Exception($"Signature mismatch! Should be Beef001a but is {Signature}");
}
var len = 0;
var index = 10;
while ((rawBytes[index + len] != 0x0 || rawBytes[index + len + 1] != 0x0))
{
len += 1;
}
var uname = Encoding.Unicode.GetString(rawBytes, index, len + 1);
FileDocumentTypeString = uname;
index += len + 3; // move past string and end of string marker
//is index 24?
//TODO get shell item list
if (index != 38)
{
Message =
"Unsupported Extension block. Please report to Report to saericzimmerman@gmail.com to get it added!";
}
VersionOffset = BitConverter.ToInt16(rawBytes, index);
}
public string FileDocumentTypeString { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine();
sb.AppendLine($"File Document Type String: {FileDocumentTypeString}");
return sb.ToString();
}
}
} |
Fix test case runs not being correctly isolated on mono | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost(AppDomain.CurrentDomain.FriendlyName.Replace(' ', '-'), realtime: false))
host.Run(new OsuTestCaseTestRunner(this));
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
Storage storage;
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
storage = host.Storage;
host.Run(new OsuTestCaseTestRunner(this));
}
// clean up after each run
storage.DeleteDirectory(string.Empty);
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
|
Handle console input in fbdev mode | using System;
using System.Linq;
using Avalonia;
namespace ControlCatalog.NetCore
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("--fbdev"))
AppBuilder.Configure<App>()
.InitializeWithLinuxFramebuffer(tl => tl.Content = new MainView());
else
AppBuilder.Configure<App>()
.UsePlatformDetect()
.Start<MainWindow>();
}
}
} | using System;
using System.Linq;
using Avalonia;
namespace ControlCatalog.NetCore
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("--fbdev")) AppBuilder.Configure<App>().InitializeWithLinuxFramebuffer(tl =>
{
tl.Content = new MainView();
System.Threading.ThreadPool.QueueUserWorkItem(_ => ConsoleSilencer());
});
else
AppBuilder.Configure<App>()
.UsePlatformDetect()
.Start<MainWindow>();
}
static void ConsoleSilencer()
{
Console.CursorVisible = false;
while (true)
Console.ReadKey();
}
}
} |
Fix broken build because of failing test | using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Resource;
using Moq;
using Xunit;
namespace Glimpse.Test.Core.Resource
{
public class ConfigurationShould
{
[Fact]
public void ReturnProperName()
{
var name = "glimpse_config";
var resource = new ConfigurationResource();
Assert.Equal(name, ConfigurationResource.InternalName);
Assert.Equal(name, resource.Name);
}
[Fact]
public void ReturnNoParameterKeys()
{
var resource = new ConfigurationResource();
Assert.Empty(resource.Parameters);
}
[Fact]
public void Execute()
{
var contextMock = new Mock<IResourceContext>();
var resource = new ConfigurationResource();
Assert.NotNull(resource.Execute(contextMock.Object));
}
}
} | using System;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework;
using Glimpse.Core.Resource;
using Glimpse.Core.ResourceResult;
using Moq;
using Xunit;
namespace Glimpse.Test.Core.Resource
{
public class ConfigurationShould
{
[Fact]
public void ReturnProperName()
{
var name = "glimpse_config";
var resource = new ConfigurationResource();
Assert.Equal(name, ConfigurationResource.InternalName);
Assert.Equal(name, resource.Name);
}
[Fact]
public void ReturnNoParameterKeys()
{
var resource = new ConfigurationResource();
Assert.Empty(resource.Parameters);
}
[Fact]
public void NotSupportNonPrivilegedExecution()
{
var resource = new PopupResource();
var contextMock = new Mock<IResourceContext>();
Assert.Throws<NotSupportedException>(() => resource.Execute(contextMock.Object));
}
[Fact(Skip = "Need to build out correct test here")]
public void Execute()
{
var contextMock = new Mock<IResourceContext>();
var configMock = new Mock<IGlimpseConfiguration>();
var resource = new ConfigurationResource();
var result = resource.Execute(contextMock.Object, configMock.Object);
var htmlResourceResult = result as HtmlResourceResult;
Assert.NotNull(result);
}
}
} |
Add Enabled = true, Exported = false | using System.Collections.Generic;
using Android.App;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver]
public class PushNotificationActionReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterAction(parameters);
var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
if (notificationId != -1)
{
var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);
if (notificationTag == null)
{
manager.Cancel(notificationId);
}
else
{
manager.Cancel(notificationTag, notificationId);
}
}
}
}
}
| using System.Collections.Generic;
using Android.App;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver(Enabled = true, Exported = false)]
public class PushNotificationActionReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterAction(parameters);
var manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt(DefaultPushNotificationHandler.ActionNotificationIdKey, -1);
if (notificationId != -1)
{
var notificationTag = extras.GetString(DefaultPushNotificationHandler.ActionNotificationTagKey, string.Empty);
if (notificationTag == null)
{
manager.Cancel(notificationId);
}
else
{
manager.Cancel(notificationTag, notificationId);
}
}
}
}
}
|
Reset timer if period is changed while it is running. | using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start()
{
Start(0);
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle()
{
return Toggle(0);
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Reset(0);
}
public void Reset(int delay)
{
Stop();
Start(delay);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
}
}
}
| using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start()
{
Start(0);
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle()
{
return Toggle(0);
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Reset(0);
}
public void Reset(int delay)
{
Stop();
Start(delay);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
if (_timer != null)
{
Reset();
}
}
}
}
|
Quit the Mac app after the window is closed | using AppKit;
using Foundation;
namespace Skia.OSX.Demo
{
[Register ("AppDelegate")]
public partial class AppDelegate : NSApplicationDelegate
{
public AppDelegate ()
{
}
public override void DidFinishLaunching (NSNotification notification)
{
// Insert code here to initialize your application
}
public override void WillTerminate (NSNotification notification)
{
// Insert code here to tear down your application
}
}
}
| using AppKit;
using Foundation;
namespace Skia.OSX.Demo
{
[Register ("AppDelegate")]
public partial class AppDelegate : NSApplicationDelegate
{
public AppDelegate ()
{
}
public override void DidFinishLaunching (NSNotification notification)
{
// Insert code here to initialize your application
}
public override void WillTerminate (NSNotification notification)
{
// Insert code here to tear down your application
}
public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender)
{
return true;
}
}
}
|
Make EZ mod able to fail in Taiko | // 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.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : ModEasy
{
public override string Description => @"Beats move slower, less accuracy required, and three lives!";
}
}
| // 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 Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : Mod, IApplicableToDifficulty, IApplicableFailOverride
{
public override string Name => "Easy";
public override string Acronym => "EZ";
public override string Description => @"Beats move slower, less accuracy required";
public override IconUsage? Icon => OsuIcon.ModEasy;
public override ModType Type => ModType.DifficultyReduction;
public override double ScoreMultiplier => 0.5;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModHardRock), typeof(ModDifficultyAdjust) };
public void ReadFromDifficulty(BeatmapDifficulty difficulty)
{
}
public void ApplyToDifficulty(BeatmapDifficulty difficulty)
{
const float ratio = 0.5f;
difficulty.CircleSize *= ratio;
difficulty.ApproachRate *= ratio;
difficulty.DrainRate *= ratio;
difficulty.OverallDifficulty *= ratio;
}
public bool PerformFail() => true;
public bool RestartOnFail => false;
}
}
|
Support for parsing equality operator with constant operand. | using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
[Test]
public void Correctly_parse_inequality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number != 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number != 5", actual);
}
}
} | using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
[Test]
public void Correctly_parse_inequality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number != 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number != 5", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_captured_constant_operand()
{
const int Number = 5;
Expression<Func<int, bool>> func = number => number == Number;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == " + Number, actual);
}
}
} |
Make clone root build config test more strict | using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;
namespace TeamCityApi.Tests.UseCases
{
public class CloneRootBuildConfigUseCaseTests
{
[Theory]
[AutoNSubstituteData]
public void Should_clone_root_build_config(
int buildId,
string newNameSyntax,
ITeamCityClient client,
IFixture fixture)
{
var sourceBuildId = buildId.ToString();
var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
var sut = new CloneRootBuildConfigUseCase(client);
sut.Execute(sourceBuildId, newNameSyntax).Wait();
var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
client.BuildConfigs.Received()
.CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
}
}
} | using System.Threading.Tasks;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
using TeamCityApi.Domain;
using TeamCityApi.Locators;
using TeamCityApi.Tests.Helpers;
using TeamCityApi.Tests.Scenarios;
using TeamCityApi.UseCases;
using Xunit;
using Xunit.Extensions;
namespace TeamCityApi.Tests.UseCases
{
public class CloneRootBuildConfigUseCaseTests
{
[Theory]
[AutoNSubstituteData]
public void Should_clone_root_build_config(
int buildId,
string newNameSyntax,
ITeamCityClient client,
IFixture fixture)
{
var sourceBuildId = buildId.ToString();
var scenario = new SingleBuildScenario(fixture, client, sourceBuildId);
var sut = new CloneRootBuildConfigUseCase(client);
sut.Execute(sourceBuildId, newNameSyntax).Wait();
var newBuildConfigName = scenario.BuildConfig.Name + Consts.SuffixSeparator + newNameSyntax;
client.BuildConfigs.Received(1)
.CopyBuildConfiguration(scenario.Project.Id, newBuildConfigName, scenario.BuildConfig.Id, Arg.Any<bool>(), Arg.Any<bool>());
}
}
} |
Set value type for Textarea to "TEXT". | using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
[PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true)]
public class TextAreaPropertyEditor : PropertyEditor
{
}
} | using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
[PropertyEditor(Constants.PropertyEditors.TextboxMultipleAlias, "Textarea", "textarea", IsParameterEditor = true, ValueType = "TEXT")]
public class TextAreaPropertyEditor : PropertyEditor
{
}
}
|
Rework clear scene method by collecting all roots | // 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
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var gameObject in Object.FindObjectsOfType<GameObject>())
{
//only destroy root objects
if (gameObject.transform.parent == null)
{
Object.DestroyImmediate(gameObject);
}
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Linq;
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var transform in Object.FindObjectsOfType<Transform>().Select(t => t.root).Distinct().ToList())
{
Object.DestroyImmediate(transform.gameObject);
}
}
}
}
|
Fix percent conversion to color. | namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(color.RGB, number.Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var values = args.Select(n => n.Value).ToList();
var rgb = values.Take(3).ToArray();
var alpha = values[3];
return new Color(rgb, alpha);
}
}
} | namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
var number = Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(color.RGB, number.Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
var args = Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var rgb = args.Take(3).Select(n => n.ToNumber(255.0)).ToArray();
var alpha = args[3].ToNumber(1.0);
return new Color(rgb, alpha);
}
}
} |
Update DMLib version to 0.8.1.0 | //------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
// Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(false)]
| //------------------------------------------------------------------------------
// <copyright file="SharedAssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
// <summary>
// Assembly global configuration.
// </summary>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.8.1.0")]
[assembly: AssemblyFileVersion("0.8.1.0")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure Storage")]
[assembly: AssemblyCopyright("Copyright © 2018 Microsoft Corp.")]
[assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(false)]
|
Set DebuggingSubProcess = Debugger.IsAttached rather than a hard coded value | using System;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private const bool debuggingSubProcess = true;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (debuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
| using System;
using System.Diagnostics;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private static readonly bool DebuggingSubProcess = Debugger.IsAttached;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (DebuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
|
Add a formated Json serialization option | using System;
using System.IO;
using System.Text;
namespace Eleven41.Helpers
{
public static class JsonHelper
{
public static string Serialize<T>(T obj)
{
return ServiceStack.Text.JsonSerializer.SerializeToString(obj, typeof(T));
}
public static void SerializeToStream<T>(T obj, Stream stream)
{
ServiceStack.Text.JsonSerializer.SerializeToStream(obj, stream);
}
public static T Deserialize<T>(string json)
{
return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(json);
}
public static T DeserializeFromStream<T>(Stream stream)
{
return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream);
}
}
} | using System;
using System.IO;
using System.Text;
using ServiceStack.Text;
namespace Eleven41.Helpers
{
public static class JsonHelper
{
public static string Serialize<T>(T obj)
{
return JsonSerializer.SerializeToString(obj, typeof(T));
}
public static string SerializeAndFormat<T>(T obj)
{
return obj.SerializeAndFormat();
}
public static void SerializeToStream<T>(T obj, Stream stream)
{
JsonSerializer.SerializeToStream(obj, stream);
}
public static T Deserialize<T>(string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
public static T DeserializeFromStream<T>(Stream stream)
{
return JsonSerializer.DeserializeFromStream<T>(stream);
}
}
} |
Fix challenge div displaying in Chrome. | <div id="challengeInbox" style="display: none;">
<p id="challengeText"></p>
<input type="button" onclick="acceptChallenge()" value="Accept" />
<input type="button" onclick="rejectChallenge()" value="Reject" />
</div>
<script>
function pollChallengeInbox() {
$.getJSON('@Url.Content("~/Poll/ChallengeInbox")', function (data) {
var div = document.getElementById("challengeInbox");
var text = document.getElementById("challengeText");
if (data.challenged) {
text.textContent = "Challenge from " + data.challenger;
div.style = "display: inline-block;";
} else {
div.style = "display: none;";
}
});
}
var challengePoller = window.setInterval(pollChallengeInbox, 5000);
pollChallengeInbox();
function acceptChallenge() {
answer(true);
};
function rejectChallenge() {
answer(false);
};
function answer(accepted) {
$.ajax({
type: "POST",
url: "Challenge/BattleAnswer",
data: { PlayerAccepts: accepted },
success: function (data) {
pollChallengeInbox();
}
});
}
</script>
| <div id="challengeInbox" style="display: none;">
<p id="challengeText"></p>
<input type="button" onclick="acceptChallenge()" value="Accept" />
<input type="button" onclick="rejectChallenge()" value="Reject" />
</div>
<script>
function pollChallengeInbox() {
$.getJSON('@Url.Content("~/Poll/ChallengeInbox")', function (data) {
var div = document.getElementById("challengeInbox");
var text = document.getElementById("challengeText");
if (data.challenged) {
text.textContent = "Challenge from " + data.challenger;
div.style.display = "inline-block";
} else {
div.style.display = "none";
}
});
}
var challengePoller = window.setInterval(pollChallengeInbox, 5000);
pollChallengeInbox();
function acceptChallenge() {
answer(true);
};
function rejectChallenge() {
answer(false);
};
function answer(accepted) {
$.ajax({
type: "POST",
url: "Challenge/BattleAnswer",
data: { PlayerAccepts: accepted },
success: function (data) {
pollChallengeInbox();
}
});
}
</script>
|
Fix failing tests on Travis | using System;
using NUnit.Framework;
namespace Plivo.Test
{
[TestFixture]
public class TestSignature
{
[Test]
public void TestSignatureV2Pass()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_token";
Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), true);
}
[Test]
public void TestSignatureV2Fail()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_tokens";
Assert.Equals(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken), false);
}
}
}
| using System;
using NUnit.Framework;
namespace Plivo.Test
{
[TestFixture]
public class TestSignature
{
[Test]
public void TestSignatureV2Pass()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_token";
Assert.True(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
}
[Test]
public void TestSignatureV2Fail()
{
string url = "https://answer.url";
string nonce = "12345";
string signature = "ehV3IKhLysWBxC1sy8INm0qGoQYdYsHwuoKjsX7FsXc=";
string authToken = "my_auth_tokens";
Assert.False(Utilities.XPlivoSignatureV2.VerifySignature(url, nonce, signature, authToken));
}
}
}
|
Fix horizontal scroll for Virtual list | using Silphid.Extensions;
using UnityEngine;
namespace Silphid.Showzup.ListLayouts
{
public class HorizontalListLayout : ListLayout
{
public float HorizontalSpacing;
public float ItemWidth;
protected float ItemOffsetX => ItemWidth + HorizontalSpacing;
public override Rect GetItemRect(int index, Vector2 viewportSize) =>
new Rect(
FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));
public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
new Vector2(
Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
viewportSize.y);
public override IndexRange GetVisibleIndexRange(Rect rect) =>
new IndexRange(
((rect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
((rect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
}
} | using Silphid.Extensions;
using UnityEngine;
namespace Silphid.Showzup.ListLayouts
{
public class HorizontalListLayout : ListLayout
{
public float HorizontalSpacing;
public float ItemWidth;
protected float ItemOffsetX => ItemWidth + HorizontalSpacing;
private Rect VisibleRect = new Rect();
public override Rect GetItemRect(int index, Vector2 viewportSize) =>
new Rect(
FirstItemPosition + new Vector2(ItemOffsetX * index, 0),
new Vector2(ItemWidth, viewportSize.y - (Padding.top + Padding.bottom)));
public override Vector2 GetContainerSize(int count, Vector2 viewportSize) =>
new Vector2(
Padding.left + ItemWidth * count + HorizontalSpacing * (count - 1).AtLeast(0) + Padding.right,
viewportSize.y);
public override IndexRange GetVisibleIndexRange(Rect visibleRect)
{
VisibleRect.Set(visibleRect.x*-1, visibleRect.y, visibleRect.width, visibleRect.height);
return new IndexRange(
((VisibleRect.xMin - FirstItemPosition.x) / ItemOffsetX).FloorInt(),
((VisibleRect.xMax - FirstItemPosition.x) / ItemOffsetX).FloorInt() + 1);
}
}
} |
Make polymorphic schema generation opt-in | using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
{
public PolymorphicSchemaGenerator(
SchemaGeneratorOptions options,
ISchemaGenerator rootGenerator,
IContractResolver contractResolver)
: base(options, rootGenerator, contractResolver)
{ }
protected override bool CanGenerateSchemaFor(Type type)
{
var subTypes = Options.SubTypesResolver(type);
return subTypes.Any();
}
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
{
var subTypes = Options.SubTypesResolver(type);
return new OpenApiSchema
{
OneOf = subTypes
.Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
.ToList()
};
}
}
} | using System;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class PolymorphicSchemaGenerator : ChainableSchemaGenerator
{
public PolymorphicSchemaGenerator(
SchemaGeneratorOptions options,
ISchemaGenerator rootGenerator,
IContractResolver contractResolver)
: base(options, rootGenerator, contractResolver)
{ }
protected override bool CanGenerateSchemaFor(Type type)
{
return (Options.GeneratePolymorphicSchemas && Options.SubTypesResolver(type).Any());
}
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
{
var subTypes = Options.SubTypesResolver(type);
return new OpenApiSchema
{
OneOf = subTypes
.Select(subType => RootGenerator.GenerateSchema(subType, schemaRepository))
.ToList()
};
}
}
} |
Add HttpClient to GetToolConsumerProfileAsync convenience method to make it easier to call from an integration test. | using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;
namespace LtiLibrary.NetCore.Profiles
{
public static class ToolConsumerProfileClient
{
/// <summary>
/// Get a ToolConsumerProfile from the service endpoint.
/// </summary>
/// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
/// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
/// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(string serviceUrl)
{
var profileResponse = new ToolConsumerProfileResponse();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));
var response = await client.GetAsync(serviceUrl);
profileResponse.StatusCode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
profileResponse.ToolConsumerProfile = await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
}
}
return profileResponse;
}
}
}
| using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using LtiLibrary.NetCore.Common;
using LtiLibrary.NetCore.Extensions;
namespace LtiLibrary.NetCore.Profiles
{
public static class ToolConsumerProfileClient
{
/// <summary>
/// Get a ToolConsumerProfile from the service endpoint.
/// </summary>
/// <param name="client">The HttpClient to use for the request.</param>
/// <param name="serviceUrl">The full URL of the ToolConsumerProfile service.</param>
/// <returns>A <see cref="ToolConsumerProfileResponse"/> which includes both the HTTP status code
/// and the <see cref="ToolConsumerProfile"/> if the HTTP status is a success code.</returns>
public static async Task<ToolConsumerProfileResponse> GetToolConsumerProfileAsync(HttpClient client, string serviceUrl)
{
var profileResponse = new ToolConsumerProfileResponse();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(LtiConstants.ToolConsumerProfileMediaType));
using (var response = await client.GetAsync(serviceUrl))
{
profileResponse.StatusCode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
profileResponse.ToolConsumerProfile =
await response.Content.ReadJsonAsObjectAsync<ToolConsumerProfile>();
profileResponse.ContentType = response.Content.Headers.ContentType.MediaType;
}
return profileResponse;
}
}
}
}
|
Remove unused functions (that generate by unity :p) | using UnityEngine.Events;
[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| using UnityEngine.Events;
[System.Serializable]
public class LiteNetLibLoadSceneEvent : UnityEvent<string, bool, float>
{
}
|
Rewrite Action Attack erased by mistake | using UnityEngine;
[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {
public override void Init(StateController controller) {
return;
}
public override void Act(StateController controller) {
}
}
| using UnityEngine;
[CreateAssetMenu (menuName = "AI/Actions/Enemy_Attack")]
public class Action_Attack : Action {
[SerializeField] float staminaRequired = 2f;
[SerializeField] float attackDelay = 1f;
[SerializeField] float attackDuration = 1f;
[SerializeField] float attackDamage = 1f;
[SerializeField] float attackRange = 2f;
float timer;
public override void Init(StateController controller) {
Debug.Log("ATTACK STATAE");
timer = attackDelay;
return;
}
public override void Act(StateController controller) {
attackRoutine(controller as Enemy_StateController);
}
private void attackRoutine(Enemy_StateController controller) {
Vector3 targetPosition = controller.chaseTarget.transform.position;
float distanceFromTarget = getDistanceFromTarget(targetPosition, controller);
bool hasStamina = controller.characterStatus.stamina.isEnough(staminaRequired);
if(hasStamina) {
if(timer >= attackDelay) {
timer = attackDelay;
controller.characterStatus.stamina.decrease(staminaRequired);
performAttack(controller, attackDamage, attackDuration);
timer = 0f;
} else {
timer += Time.deltaTime;
}
} else {
timer = attackDelay;
}
}
private void performAttack(Enemy_StateController controller, float attackDamage, float attackDuration) {
controller.anim.SetTrigger("AttackState");
controller.attackHandler.damage = attackDamage;
controller.attackHandler.duration = attackDuration;
controller.attackHandler.hitBox.enabled = true;
}
private float getDistanceFromTarget(Vector3 targetPosition, Enemy_StateController controller) {
Vector3 originPosition = controller.eyes.position;
Vector3 originToTargetVector = targetPosition - originPosition;
float distanceFromTarget = originToTargetVector.magnitude;
return distanceFromTarget;
}
}
|
Fix crash when items are added from non-WPF main thread | using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;
namespace SOVND.Client.Util
{
public class ChannelDirectory
{
public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();
public bool AddChannel(Channel channel)
{
if (channels.Where(x => x.Name == channel.Name).Count() > 0)
return false;
channels.Add(channel);
return true;
}
}
} | using System.Collections.ObjectModel;
using System.Linq;
using SOVND.Lib.Models;
namespace SOVND.Client.Util
{
public class ChannelDirectory
{
private readonly SyncHolder _sync;
public ObservableCollection<Channel> channels = new ObservableCollection<Channel>();
public ChannelDirectory(SyncHolder sync)
{
_sync = sync;
}
public bool AddChannel(Channel channel)
{
if (channels.Where(x => x.Name == channel.Name).Count() > 0)
return false;
if (_sync.sync != null)
_sync.sync.Send((x) => channels.Add(channel), null);
else
channels.Add(channel);
return true;
}
}
} |
Rename previously unknown GAF field | namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
| namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
|
Add ThrowsWithMessage() overload with format string | using System;
using Xunit;
namespace Cascara.Tests
{
public class AssertExtension : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
| using System;
using Xunit;
namespace Cascara.Tests
{
public class AssertExtension : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
where T : Exception
{
string message = string.Format(fmt, args);
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
|
Add logical operations to NuGit operations | using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;
namespace
produce
{
public class
NuGitModule : Module
{
public override void
Attach(ProduceRepository repository, Graph graph)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(graph, nameof(graph));
var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
graph.Dependency(nugitRestore, graph.Command("restore"));
var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
graph.Dependency(nugitUpdate, graph.Command("update"));
}
static void
Restore(ProduceRepository repository)
{
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
throw new UserException("nugit failed");
}
static void
Update(ProduceRepository repository)
{
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
throw new UserException("nugit failed");
}
}
}
| using MacroDiagnostics;
using MacroExceptions;
using MacroGuards;
namespace
produce
{
public class
NuGitModule : Module
{
public override void
Attach(ProduceRepository repository, Graph graph)
{
Guard.NotNull(repository, nameof(repository));
Guard.NotNull(graph, nameof(graph));
var nugitRestore = graph.Command("nugit-restore", _ => Restore(repository));
graph.Dependency(nugitRestore, graph.Command("restore"));
var nugitUpdate = graph.Command("nugit-update", _ => Update(repository));
graph.Dependency(nugitUpdate, graph.Command("update"));
}
static void
Restore(ProduceRepository repository)
{
using (LogicalOperation.Start("Restoring NuGit dependencies"))
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "restore") != 0)
throw new UserException("nugit failed");
}
static void
Update(ProduceRepository repository)
{
using (LogicalOperation.Start("Updating NuGit dependencies"))
if (ProcessExtensions.Execute(true, true, repository.Path, "cmd", "/c", "nugit", "update") != 0)
throw new UserException("nugit failed");
}
}
}
|
Fix non-existant ref vars in function calls. | using System;
namespace Hlpr
{
class WarpHelp
{
public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dis;
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
public static double Distance(Vector3d v1, Vector3d v2)
{
double dis, x1, x2, y1, y2, z1, z2;
ConvertVector3dToXYZCoords(v1, x1, y1, z1);
ConvertVector3dToXYZCoords(v2, x2, y2, z2);
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
}
} | using System;
namespace Hlpr
{
class WarpHelp
{
public static double Distance(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dis;
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
public static double Distance(Vector3d v1, Vector3d v2)
{
double dis, x1, x2, y1, y2, z1, z2;
ConvertVector3dToXYZCoords(v1, ref x1, ref y1, ref z1);
ConvertVector3dToXYZCoords(v2, ref x2, ref y2, ref z2);
dis = Math.Pow(x1-x2,2) + Math.Pow(y1-y2,2) + Math.Pow(z1-z2,2);
dis = Math.Pow(dis,0.5);
return dis;
}
}
} |
Make the JSON model over the API control be the correct casing & make Mads happy :) | using System;
namespace Umbraco.Web.Models.ContentEditing
{
public class RollbackVersion
{
public int VersionId { get; set; }
public DateTime VersionDate { get; set; }
public string VersionAuthorName { get; set; }
}
}
| using System;
using System.Runtime.Serialization;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "rollbackVersion", Namespace = "")]
public class RollbackVersion
{
[DataMember(Name = "versionId")]
public int VersionId { get; set; }
[DataMember(Name = "versionDate")]
public DateTime VersionDate { get; set; }
[DataMember(Name = "versionAuthorName")]
public string VersionAuthorName { get; set; }
}
}
|
Set Datawriter executing logs to debug level | using System;
using log4net;
using Quartz;
namespace DCS.Core.Scheduler
{
public sealed class CronTask : IJob
{
private readonly string _cronConfig;
private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
private readonly Action _task;
private readonly string _taskName;
public CronTask()
{
}
public CronTask(string taskName, string cronConfig, Action action)
{
_taskName = taskName;
_task = action;
_cronConfig = cronConfig;
}
public string TaskName
{
get { return _taskName; }
}
public string CronConfig
{
get { return _cronConfig; }
}
public void Execute(IJobExecutionContext context)
{
var task = (CronTask)context.MergedJobDataMap.Get("task");
// executes the task
_logger.Info("Executing task : " + task.TaskName);
task._task();
}
}
} | using System;
using log4net;
using Quartz;
namespace DCS.Core.Scheduler
{
public sealed class CronTask : IJob
{
private readonly string _cronConfig;
private readonly ILog _logger = LogManager.GetLogger(typeof(CronTask));
private readonly Action _task;
private readonly string _taskName;
public CronTask()
{
}
public CronTask(string taskName, string cronConfig, Action action)
{
_taskName = taskName;
_task = action;
_cronConfig = cronConfig;
}
public string TaskName
{
get { return _taskName; }
}
public string CronConfig
{
get { return _cronConfig; }
}
public void Execute(IJobExecutionContext context)
{
var task = (CronTask)context.MergedJobDataMap.Get("task");
// executes the task
_logger.Debug("Executing task : " + task.TaskName);
task._task();
}
}
} |
Update REST API version to v3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Services
{
internal class UrlBuilder : IUrlBuilder
{
const string _https = "https://";
const string _baseUrl = "zportal.nl/api";
const string _apiVersion = "v2";
const string _accessToken = "access_token";
public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
{
string url = GetUrl(auth.Host, endpoint, options);
if (url.Contains("?"))
url += "&";
else
url += "?";
url += $"{_accessToken}={auth.Token}";
return url;
}
public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
{
string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";
if (options != null)
{
url += "?";
foreach (var x in options)
{
url += $"{x.Key}={x.Value}&";
}
url = url.TrimEnd('&');
}
return url;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Services
{
internal class UrlBuilder : IUrlBuilder
{
const string _https = "https://";
const string _baseUrl = "zportal.nl/api";
const string _apiVersion = "v3";
const string _accessToken = "access_token";
public string GetAuthenticatedUrl(IAuthentication auth, string endpoint, Dictionary<string, string> options = null)
{
string url = GetUrl(auth.Host, endpoint, options);
if (url.Contains("?"))
url += "&";
else
url += "?";
url += $"{_accessToken}={auth.Token}";
return url;
}
public string GetUrl(string host, string endpoint, Dictionary<string, string> options = null)
{
string url = $"{_https}{host}.{_baseUrl}/{_apiVersion}/{endpoint}";
if (options != null)
{
url += "?";
foreach (var x in options)
{
url += $"{x.Key}={x.Value}&";
}
url = url.TrimEnd('&');
}
return url;
}
}
}
|
Call the disposeEmitter action on dispose | using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeBatcher();
});
}
}
}
| using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeEmitter();
});
}
}
}
|
Replace proprietary file header with BSD one | ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
| /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
|
Make flaky tests a bit less flaky | using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int FlakyAdd(int x, int y)
{
var rand = new Random();
if (rand.NextDouble() > 0.5)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
| using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int count2 = 0;
int FlakyAdd(int x, int y)
{
if(count2++ == 2)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
|
Add methods to manipulate MediaStoreItems | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
}
private void LoadMediaStore()
{
try
{
JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
this.MediaStoreItems = this.LoadMediaStore();
}
private Dictionary<string, string> LoadMediaStore()
{
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return new Dictionary<string, string>();
}
}
public void Add(string key, string fileName){
File.Copy(fileName, Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Add(key, Path.GetFileName(fileName));
this.UpdateMediaStoreRecord();
}
public void Remove(string key){
File.Delete(Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Remove(key);
this.UpdateMediaStoreRecord();
}
private void UpdateMediaStoreRecord(){
string record = JsonConvert.SerializeObject(this.MediaStoreItems);
File.WriteAllText(Path.Combine(mediaStoreRoot, ".mediastore"));
}
}
}
|
Add ProfilerInterceptor.GuardInternal() for public APIs even if they are hidden. | /*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
| /*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return ProfilerInterceptor.GuardInternal(() =>
resolver.GetContext()
);
}
public static void CaptureContext()
{
ProfilerInterceptor.GuardInternal(() =>
resolver.CaptureContext()
);
}
}
}
|
Fix potential null ref exception. | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret = objectWithInitializationStrategies.InitializationStrategies.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret =
(objectWithInitializationStrategies.InitializationStrategies ?? new List<InitializationStrategyBase>())
.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
|
Add exception to catch any incorrect defaults of `Bindable<string>` | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
public override Bindable<string> Current
{
get => base.Current;
set
{
if (value.Default == null)
throw new InvalidOperationException($"Bindable settings of type {nameof(Bindable<string>)} should have a non-null default value.");
base.Current = value;
}
}
}
}
|
Add missing methods to server interface | using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
}
} | using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
/// <summary>
/// Transfer the host of the currently joined room to another user in the room.
/// </summary>
/// <param name="userId">The new user which is to become host.</param>
Task TransferHost(long userId);
/// <summary>
/// As the host, update the settings of the currently joined room.
/// </summary>
/// <param name="settings">The new settings to apply.</param>
Task ChangeSettings(MultiplayerRoomSettings settings);
}
}
|
Handle null values in IsMultilineDocComment | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
if (documentationComment == null)
{
return false;
}
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
|
Improve a/an word extraction to avoid problematic cases like "Triple-A classification" | using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"\b(?<article>[Aa]n?) [""()‘’“”$'-]*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
| using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"(^|[\s""()‘’“”'])(?<article>[Aa]n?) [""()‘’“”$']*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
//watch out for dashes before "A" because of things like "Triple-A annotation"
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
|
Revert "FLEET-9992: Add extra property to use new long Id's" | using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public int[] AddressList { get; set; }
public long[] LocationList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public long[] AddressList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
|
Add debugger to HelloWorldBlacksboardAI example | using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
}
}
| using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
// attach the debugger component if executed in editor (helps to debug in the inspector)
#if UNITY_EDITOR
Debugger debugger = (Debugger)this.gameObject.AddComponent(typeof(Debugger));
debugger.BehaviorTree = behaviorTree;
#endif
}
}
|
Disable account online check for now. | // Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
var account = DB.Auth.Single<Account>(a => a.Email == loginName);
if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
| // Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
//var account = DB.Auth.Single<Account>(a => a.Email == loginName);
//if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
|
Fix incorrect font indexing in language dropdown | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1];
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var languages = LocalizationManager.instance.getAllLanguages();
LocalizationManager.Language language = languages[0];
//Determine langauge index based on sibling position and selectable languages
int index = 0;
int objectIndex = transform.GetSiblingIndex() - 1;
for (int i = 0; i < languages.Length; i++)
{
if (!languages[i].disableSelect)
{
if (index >= objectIndex)
{
language = languages[i];
Debug.Log(textComponent.text + " is " + language.getLanguageID());
break;
}
index++;
}
}
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
|
Throw correct exceptions for IO errors | #if !NETCOREAPP
using System.ComponentModel;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw new Win32Exception();
}
#endif
}
#if !NETCOREAPP
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
| #if !NETCOREAPP
using System;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw GetExceptionForLastWin32Error(sourceFilePath);
}
#endif
}
#if !NETCOREAPP
private static Exception GetExceptionForLastWin32Error(string path) => Marshal.GetLastWin32Error() switch
{
2 => new FileNotFoundException(null, path), // ERROR_FILE_NOT_FOUND
3 => new DirectoryNotFoundException(), // ERROR_PATH_NOT_FOUND
5 => new UnauthorizedAccessException(), // ERROR_ACCESS_DENIED
_ => new IOException()
};
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
|
Add better error logging to see why mono build is failing | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception)
{
}
}
Debugger.Launch();
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
private static readonly ILog _log = LogManager.GetLogger(typeof(Run));
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception exception)
{
_log.ErrorFormat("Error trying to create an instance of {0}. {1}{2}", type.FullName, Environment.NewLine, exception.ToString());
}
}
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
} |
Add tests for new eventing behavior. | using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;
namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var slackReport =
new WebHookErrorReportFilter(
new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
UserName = ConfigurationManager.AppSettings["slack:username"],
IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
Text = ConfigurationManager.AppSettings["slack:text"],
}
)
{
IgnoreHandled = true,
IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
};
filters.Add(slackReport, 1);
}
}
} | using System.Web;
using System.Web.Mvc;
using Pelasoft.AspNet.Mvc.Slack;
using System.Configuration;
namespace Pelasoft.AspNet.Mvc.Slack.TestWeb
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var slackReport =
new WebHookErrorReportFilter(
new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
UserName = ConfigurationManager.AppSettings["slack:username"],
IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"],
AttachmentColor = ConfigurationManager.AppSettings["slack:color"],
AttachmentTitle = ConfigurationManager.AppSettings["slack:title"],
AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"],
Text = ConfigurationManager.AppSettings["slack:text"],
}
)
{
IgnoreHandled = true,
IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) },
};
filters.Add(slackReport, 1);
var slackReportEvented = new WebHookErrorReportFilter();
slackReportEvented.OnExceptionReporting += slackReportEvented_OnExceptionReporting;
filters.Add(slackReportEvented);
}
static void slackReportEvented_OnExceptionReporting(ExceptionReportingEventArgs args)
{
args.Options = new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"])
{
Text = "Options reported via the event.",
ChannelName = ConfigurationManager.AppSettings["slack:channel"],
};
// args.CancelReport = true;
}
}
} |
Update the release/editorial endpoint schema | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
[XmlRoot("editorial")]
[ApiEndpoint("release/editorial")]
[Serializable]
public class ReleaseEditorial : HasReleaseIdParameter
{
[XmlElement("review")]
public Review Review { get; set; }
[XmlElement("staffRecommendation")]
public Review StaffRecommendation { get; set; }
[XmlElement("promotionalText")]
public string PromotionalText { get; set; }
}
public class Review
{
[XmlElement("text")]
public string Text { get; set; }
}
}
| using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
namespace SevenDigital.Api.Schema.ReleaseEndpoint
{
[XmlRoot("editorial")]
[ApiEndpoint("release/editorial")]
[Serializable]
public class ReleaseEditorial : HasReleaseIdParameter
{
[XmlElement("review")]
public TextItem Review { get; set; }
[XmlElement("promotionalText")]
public TextItem PromotionalText { get; set; }
}
public class TextItem
{
[XmlElement("text")]
public string Text { get; set; }
}
}
|
Revert "Revert "added try catch, test commit"" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
catch (Exception)
{
throw;
}
}
}
} |
Rename field to better match type. | using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;
namespace Mitternacht.Modules.Games.Services {
public class GamesService : IMService {
private readonly IBotConfigProvider _bc;
public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
public readonly ImmutableArray<string> EightBallResponses;
public readonly string TypingArticlesPath = "data/typing_articles2.json";
public GamesService(IBotConfigProvider bc) {
_bc = bc;
EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();
var timer = new Timer(_ => {
GirlRatings.Clear();
}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Mitternacht.Modules.Games.Common;
using Mitternacht.Services;
namespace Mitternacht.Modules.Games.Services {
public class GamesService : IMService {
private readonly IBotConfigProvider _bcp;
public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>();
public readonly ImmutableArray<string> EightBallResponses;
public readonly string TypingArticlesPath = "data/typing_articles2.json";
public GamesService(IBotConfigProvider bcp) {
_bcp = bcp;
EightBallResponses = _bcp.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();
var timer = new Timer(_ => {
GirlRatings.Clear();
}, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));
}
}
}
|
Call GetBaseException instead of manually unwrapping exception types. | using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception.GetType() == typeof(TargetInvocationException)) {
return exception.InnerException;
}
// Flatten the aggregate before getting the inner exception
if (exception.GetType() == typeof(AggregateException)) {
return ((AggregateException)exception).Flatten().InnerException;
}
return exception;
}
}
}
| using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception is AggregateException ||
exception is TargetInvocationException) {
return exception.GetBaseException();
}
return exception;
}
}
}
|
Return value in Dump ext. method. | using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value)
=> value.Inspect(title: "Dump");
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
| using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value) {
value.Inspect(title: "Dump");
return value;
}
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
|
Allow overriding of locomotion implementation | using Alensia.Core.Input;
using UnityEngine.Assertions;
namespace Alensia.Core.Locomotion
{
public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
where T : class, ILocomotion
{
public T Locomotion { get; }
public override bool Valid => base.Valid && Locomotion.Active;
protected LocomotionControl(T locomotion, IInputManager inputManager) : base(inputManager)
{
Assert.IsNotNull(locomotion, "locomotion != null");
Locomotion = locomotion;
}
}
} | using Alensia.Core.Input;
namespace Alensia.Core.Locomotion
{
public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T>
where T : class, ILocomotion
{
public abstract T Locomotion { get; }
public override bool Valid => base.Valid && Locomotion != null && Locomotion.Active;
protected LocomotionControl(IInputManager inputManager) : base(inputManager)
{
}
}
} |
Implement Map Point Tool Mouse events | using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ArcMapAddinVisibility
{
public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
{
public MapPointTool()
{
}
protected override void OnUpdate()
{
Enabled = ArcMap.Application != null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ArcMapAddinVisibility.Helpers;
namespace ArcMapAddinVisibility
{
public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool
{
public MapPointTool()
{
}
protected override void OnUpdate()
{
Enabled = ArcMap.Application != null;
}
protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
{
if (arg.Button != System.Windows.Forms.MouseButtons.Left)
return;
try
{
//Get the active view from the ArcMap static class.
IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;
var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;
Mediator.NotifyColleagues(Constants.NEW_MAP_POINT, point);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
protected override void OnMouseMove(MouseEventArgs arg)
{
IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;
var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint;
Mediator.NotifyColleagues(Constants.MOUSE_MOVE_POINT, point);
}
}
}
|
Fix for filename lowercase matches - to fix missing .PNG images | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocFunctions.Lib.Models.Github
{
public abstract class AbstractAction
{
public string FullFilename { get; set; }
public string CommitSha { get; set; }
public string CommitShaForRead { get; set; }
public string Path
{
get
{
if (FullFilename.Contains("/"))
{
return FullFilename.Replace("/" + Filename, "");
}
else
{
return FullFilename.Replace(Filename, "");
}
}
}
public string Filename
{
get
{
return System.IO.Path.GetFileName(FullFilename);
}
}
public bool IsBlogFile
{
get
{
return (Extension == ".md" || Extension == ".json");
}
}
public bool IsImageFile
{
get
{
return (Extension == ".png" || Extension == ".jpg" || Extension == ".gif");
}
}
private string Extension
{
get
{
return System.IO.Path.GetExtension(FullFilename);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocFunctions.Lib.Models.Github
{
public abstract class AbstractAction
{
public string FullFilename { get; set; }
public string CommitSha { get; set; }
public string CommitShaForRead { get; set; }
public string Path
{
get
{
if (FullFilename.Contains("/"))
{
return FullFilename.Replace("/" + Filename, "");
}
else
{
return FullFilename.Replace(Filename, "");
}
}
}
public string Filename
{
get
{
return System.IO.Path.GetFileName(FullFilename);
}
}
public bool IsBlogFile
{
get
{
return (Extension.ToLower() == ".md" || Extension.ToLower() == ".json");
}
}
public bool IsImageFile
{
get
{
return (Extension.ToLower() == ".png" || Extension.ToLower() == ".jpg" || Extension.ToLower() == ".gif");
}
}
private string Extension
{
get
{
return System.IO.Path.GetExtension(FullFilename);
}
}
}
}
|
Apply fixes to duplicate file | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
/// </summary>
[Flags]
public enum FindFirstFileExFlags
{
/// <summary>
/// Searches are case-sensitive.
/// </summary>
CaseSensitive,
/// <summary>
/// Uses a larger buffer for directory queries, which can increase performance of the find operation.
/// </summary>
LargeFetch,
}
}
}
| // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="FindFirstFileExFlags"/> nested enum.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Optional flags to pass to the <see cref="FindFirstFileEx"/> method.
/// </summary>
[Flags]
public enum FindFirstFileExFlags
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0,
/// <summary>
/// Searches are case-sensitive.
/// </summary>
CaseSensitive = 0x1,
/// <summary>
/// Uses a larger buffer for directory queries, which can increase performance of the find operation.
/// </summary>
LargeFetch = 0x2,
}
}
}
|
Disable test failing on VS2015 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Test
{
using System;
struct AA
{
static float[] m_afStatic1;
static void Main1()
{
ulong[] param2 = new ulong[10];
uint[] local5 = new uint[7];
try
{
try
{
int[] local8 = new int[7];
try
{
//.......
}
catch (Exception)
{
do
{
//.......
} while (m_afStatic1[233] > 0.0);
}
while (0 != local5[205])
return;
}
catch (IndexOutOfRangeException)
{
float[] local10 = new float[7];
while ((int)param2[168] != 1)
{
float[] local11 = new float[7];
}
}
}
catch (NullReferenceException) { }
}
static int Main()
{
try
{
Main1();
return -1;
}
catch (IndexOutOfRangeException)
{
return 100;
}
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Test
{
using System;
struct AA
{
static float[] m_afStatic1;
static void Main1()
{
ulong[] param2 = new ulong[10];
uint[] local5 = new uint[7];
try
{
try
{
int[] local8 = new int[7];
try
{
//.......
}
catch (Exception)
{
do
{
//.......
} while (m_afStatic1[233] > 0.0);
}
while (0 != local5[205])
return;
}
catch (IndexOutOfRangeException)
{
float[] local10 = new float[7];
while ((int)param2[168] != 1)
{
float[] local11 = new float[7];
}
}
}
catch (NullReferenceException) { }
}
static int Main()
{
try
{
// Issue #1421 RyuJIT generates incorrect exception handling scopes for IL generated by Roslyn
#if false
Main1();
return -1;
#endif
return 100;
}
catch (IndexOutOfRangeException)
{
return 100;
}
}
}
}
|
Add RSS Infomation for Andreas Bittner | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AndreasBittner : IAmACommunityMember
{
public string FirstName => "Andreas";
public string LastName => "Bittner";
public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
public string StateOrRegion => "Saxony, Germany";
public string EmailAddress => "";
public string TwitterHandle => "Andreas_Bittner";
public string GitHubHandle => "bobruhny";
public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri(""); } }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AndreasBittner : IAmACommunityMember
{
public string FirstName => "Andreas";
public string LastName => "Bittner";
public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2";
public string StateOrRegion => "Saxony, Germany";
public string EmailAddress => "";
public string TwitterHandle => "Andreas_Bittner";
public string GitHubHandle => "bobruhny";
public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755";
public GeoPosition Position => new GeoPosition(49,4833, 10,7167);
public Uri WebSite => new Uri("http://joinpowershell.de/de/new/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://joinpowershell.de/de/feed/"); } }
}
} |
Set UI exe assembly title | using System.Runtime.InteropServices;
using System.Windows;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: AssemblyTitle("Certify The Web (UI)")]
|
Enable TLS 1.1 and 1.2 and disable SSLv3 for external calls. | using StackExchange.Elastic;
namespace StackExchange.Opserver
{
public class OpserverCore
{
// Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
public static void Init()
{
try
{
ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
// We're going to get errors - that's kinda the point of monitoring
// No need to log every one here unless for crazy debugging
//ElasticException.ExceptionOccurred += e => Current.LogException(e);
}
catch { }
}
}
}
| using System.Net;
using StackExchange.Elastic;
namespace StackExchange.Opserver
{
public class OpserverCore
{
// Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
public static void Init()
{
try
{
ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
// We're going to get errors - that's kinda the point of monitoring
// No need to log every one here unless for crazy debugging
//ElasticException.ExceptionOccurred += e => Current.LogException(e);
}
catch { }
// Enable TLS only for SSL negotiation, SSL has been broken for some time.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
}
}
|
Implement unconditional toggle of the first item when a toolstrip menu is initialized. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Mirage.Urbanization.WinForms
{
public abstract class ToolstripMenuInitializer<TOption>
where TOption : IToolstripMenuOption
{
protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
{
foreach (var option in options)
{
var localOption = option;
var item = new ToolStripMenuItem(option.Name);
item.Click += (sender, e) =>
{
foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
x.Checked = false;
item.Checked = true;
_currentOption = localOption;
if (OnSelectionChanged != null)
OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
};
targetToopToolStripMenuItem.DropDownItems.Add(item);
item.PerformClick();
}
}
public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;
private TOption _currentOption;
public TOption GetCurrentOption() { return _currentOption; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Mirage.Urbanization.WinForms
{
public abstract class ToolstripMenuInitializer<TOption>
where TOption : IToolstripMenuOption
{
protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options)
{
ToolStripMenuItem first = null;
foreach (var option in options)
{
var localOption = option;
var item = new ToolStripMenuItem(option.Name);
item.Click += (sender, e) =>
{
foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>())
x.Checked = false;
item.Checked = true;
_currentOption = localOption;
if (OnSelectionChanged != null)
OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption));
};
targetToopToolStripMenuItem.DropDownItems.Add(item);
if (first == null)
first = item;
}
first.PerformClick();
}
public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged;
private TOption _currentOption;
public TOption GetCurrentOption() { return _currentOption; }
}
} |
Raise store mocking project version. | using System.Reflection;
[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("8.0.3.0")]
[assembly: AssemblyFileVersion("8.0.3.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.3")] | using System.Reflection;
[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("8.0.4.0")]
[assembly: AssemblyFileVersion("8.0.4.0")]
// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.4-prerelease01")] |
Debug Util: Wraps log error. | using System.Diagnostics;
using UnityEngine;
namespace Finegamedesign.Utils
{
/// <summary>
/// Wrapper of logging.
/// Conditionally compiles if in debug mode or editor.
/// </summary>
public sealed class DebugUtil
{
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Log(string message)
{
UnityEngine.Debug.Log(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void LogWarning(string message)
{
UnityEngine.Debug.LogWarning(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Assert(bool condition, string message = "")
{
UnityEngine.Debug.Assert(condition, message);
}
}
}
| using System.Diagnostics;
using UnityEngine;
namespace Finegamedesign.Utils
{
/// <summary>
/// Wrapper of logging.
/// Conditionally compiles if in debug mode or editor.
/// </summary>
public sealed class DebugUtil
{
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Log(string message)
{
UnityEngine.Debug.Log(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void LogWarning(string message)
{
UnityEngine.Debug.LogWarning(message);
}
public static void LogError(string message)
{
UnityEngine.Debug.LogError(message);
}
[Conditional("DEBUG")]
[Conditional("UNITY_EDITOR")]
public static void Assert(bool condition, string message = "")
{
UnityEngine.Debug.Assert(condition, message);
}
}
}
|
Update file version to 3.0.4.0 | using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.3.0";
}
}
| using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.4.0";
}
}
|
Add optional Url and ShowOnCashBasisReports fields for MJs | using System;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public class ManualJournal : ModelBase
{
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
[ItemId]
public Guid ManualJournalID { get; set; }
public DateTime? Date { get; set; }
public string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public string Narration { get; set; }
[XmlArrayItem("JournalLine")]
public ManualJournalLineItems JournalLines { get; set; }
}
public class ManualJournals : ModelList<ManualJournal>
{
}
} | using System;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public class ManualJournal : ModelBase
{
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
[ItemId]
public Guid ManualJournalID { get; set; }
public DateTime? Date { get; set; }
public string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public string Narration { get; set; }
public string Url { get; set; }
public bool? ShowOnCashBasisReports { get; set; }
[XmlArrayItem("JournalLine")]
public ManualJournalLineItems JournalLines { get; set; }
}
public class ManualJournals : ModelList<ManualJournal>
{
}
} |
Fix IsAppContainerProcess for Windows 7 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Security;
using System.Security.Principal;
namespace System
{
internal static class EnvironmentHelpers
{
private static volatile bool s_isAppContainerProcess;
private static volatile bool s_isAppContainerProcessInitalized;
internal const int TokenIsAppContainer = 29;
public static bool IsAppContainerProcess
{
get
{
if (!s_isAppContainerProcessInitalized)
{
s_isAppContainerProcess = HasAppContainerToken();
s_isAppContainerProcessInitalized = true;
}
return s_isAppContainerProcess;
}
}
[SecuritySafeCritical]
private static unsafe bool HasAppContainerToken()
{
int* dwIsAppContainerPtr = stackalloc int[1];
uint dwLength = 0;
using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
{
if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
{
throw new Win32Exception();
}
}
return (*dwIsAppContainerPtr != 0);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Security;
using System.Security.Principal;
namespace System
{
internal static class EnvironmentHelpers
{
private static volatile bool s_isAppContainerProcess;
private static volatile bool s_isAppContainerProcessInitalized;
internal const int TokenIsAppContainer = 29;
public static bool IsAppContainerProcess
{
get
{
if(!s_IsAppContainerProcessInitalized) {
if(Environment.OSVersion.Platform != PlatformID.Win32NT) {
s_IsAppContainerProcess = false;
} else if(Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) {
// Windows 7 or older.
s_IsAppContainerProcess = false;
} else {
s_IsAppContainerProcess = HasAppContainerToken();
}
s_IsAppContainerProcessInitalized = true;
}
return s_IsAppContainerProcess;
}
}
[SecuritySafeCritical]
private static unsafe bool HasAppContainerToken()
{
int* dwIsAppContainerPtr = stackalloc int[1];
uint dwLength = 0;
using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query))
{
if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength))
{
throw new Win32Exception();
}
}
return (*dwIsAppContainerPtr != 0);
}
}
}
|
Use standard syntax to build propfind requests | using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;
namespace WebDav.Request
{
internal static class PropfindRequestBuilder
{
public static string BuildRequestBody(string[] customProperties)
{
XNamespace webDavNs = "DAV:";
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var propfind = new XElement(webDavNs + "propfind", new XAttribute(XNamespace.Xmlns + "D", webDavNs));
propfind.Add(new XElement(webDavNs + "allprop"));
if (customProperties.Any())
{
var include = new XElement(webDavNs + "include");
foreach (var prop in customProperties)
{
include.Add(new XElement(webDavNs + prop));
}
propfind.Add(include);
}
doc.Add(propfind);
return doc.ToStringWithDeclaration();
}
}
}
| using System.Linq;
using System.Xml.Linq;
using WebDav.Helpers;
namespace WebDav.Request
{
internal static class PropfindRequestBuilder
{
public static string BuildRequestBody(string[] customProperties)
{
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var propfind = new XElement("{DAV:}propfind", new XAttribute(XNamespace.Xmlns + "D", "DAV:"));
propfind.Add(new XElement("{DAV:}allprop"));
if (customProperties.Any())
{
var include = new XElement("{DAV:}include");
foreach (var prop in customProperties)
{
include.Add(new XElement(XName.Get(prop, "DAV:")));
}
propfind.Add(include);
}
doc.Add(propfind);
return doc.ToStringWithDeclaration();
}
}
}
|
Add TilePOI to list of tile names | using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;
namespace MaterialColor.Core
{
public static class State
{
public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();
public static ConfiguratorState ConfiguratorState = new ConfiguratorState();
public static bool Disabled = false;
public static readonly List<string> TileNames = new List<string>
{
"Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane"
};
}
}
| using MaterialColor.Common.Data;
using System.Collections.Generic;
using UnityEngine;
namespace MaterialColor.Core
{
public static class State
{
public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>();
public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>();
public static ConfiguratorState ConfiguratorState = new ConfiguratorState();
public static bool Disabled = false;
public static readonly List<string> TileNames = new List<string>
{
"Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane", "TilePOI"
};
}
}
|
Add keywords to make finding audio offset adjustments easier in settings | // 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.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections.Audio
{
public class OffsetSettings : SettingsSubsection
{
protected override LocalisableString Header => "Offset Adjustment";
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double, OffsetSlider>
{
LabelText = "Audio offset",
Current = config.GetBindable<double>(OsuSetting.AudioOffset),
KeyboardStep = 1f
},
new SettingsButton
{
Text = "Offset wizard"
}
};
}
private class OffsetSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings.Sections.Audio
{
public class OffsetSettings : SettingsSubsection
{
protected override LocalisableString Header => "Offset Adjustment";
public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(new[] { "universal", "uo", "timing" });
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double, OffsetSlider>
{
LabelText = "Audio offset",
Current = config.GetBindable<double>(OsuSetting.AudioOffset),
KeyboardStep = 1f
},
new SettingsButton
{
Text = "Offset wizard"
}
};
}
private class OffsetSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => Current.Value.ToString(@"0ms");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.