Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a comment about when the MoE calculation will be wrong. | using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
namespace VstsMetrics.Commands.CycleTime
{
public static class WorkItemCycleTimeExtensions
{
public static IEnumerable<WorkItemCycleTimeSummary> Summarise(this IEnumerable<WorkItemCycleTime> cycleTimes)
{
var elapsedAverage = cycleTimes.Average(ct => ct.ElapsedCycleTimeInHours);
var workingAverage = cycleTimes.Average(ct => ct.ApproximateWorkingCycleTimeInHours);
var elapsedMoe = cycleTimes.MarginOfError(ct => ct.ElapsedCycleTimeInHours);
var workingMoe = cycleTimes.MarginOfError(ct => ct.ApproximateWorkingCycleTimeInHours);
return new[] {
new WorkItemCycleTimeSummary("Elapsed", elapsedAverage, elapsedMoe),
new WorkItemCycleTimeSummary("Approximate Working Time", workingAverage, workingMoe)
};
}
private static double MarginOfError(this IEnumerable<WorkItemCycleTime> cycleTimes, Func<WorkItemCycleTime, double> getter)
{
// http://www.dummies.com/education/math/statistics/how-to-calculate-the-margin-of-error-for-a-sample-mean/
return cycleTimes.Select(getter).PopulationStandardDeviation()
/ Math.Sqrt(cycleTimes.Count())
* 1.96;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
namespace VstsMetrics.Commands.CycleTime
{
public static class WorkItemCycleTimeExtensions
{
public static IEnumerable<WorkItemCycleTimeSummary> Summarise(this IEnumerable<WorkItemCycleTime> cycleTimes)
{
var elapsedAverage = cycleTimes.Average(ct => ct.ElapsedCycleTimeInHours);
var workingAverage = cycleTimes.Average(ct => ct.ApproximateWorkingCycleTimeInHours);
var elapsedMoe = cycleTimes.MarginOfError(ct => ct.ElapsedCycleTimeInHours);
var workingMoe = cycleTimes.MarginOfError(ct => ct.ApproximateWorkingCycleTimeInHours);
return new[] {
new WorkItemCycleTimeSummary("Elapsed", elapsedAverage, elapsedMoe),
new WorkItemCycleTimeSummary("Approximate Working Time", workingAverage, workingMoe)
};
}
private static double MarginOfError(this IEnumerable<WorkItemCycleTime> cycleTimes, Func<WorkItemCycleTime, double> getter)
{
// http://www.dummies.com/education/math/statistics/how-to-calculate-the-margin-of-error-for-a-sample-mean/
// If the central limit theorem does not apply, then this will be incorrect. This should be exposed somehow at some point.
return cycleTimes.Select(getter).PopulationStandardDeviation()
/ Math.Sqrt(cycleTimes.Count())
* 1.96;
}
}
} |
Move musig class in the musig namespace | #if HAS_SPAN
#nullable enable
using NBitcoin.Secp256k1.Musig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace NBitcoin.Secp256k1
{
#if SECP256K1_LIB
public
#endif
class MusigPartialSignature
{
#if SECP256K1_LIB
public
#else
internal
#endif
readonly Scalar E;
public MusigPartialSignature(Scalar e)
{
this.E = e;
}
public MusigPartialSignature(ReadOnlySpan<byte> in32)
{
this.E = new Scalar(in32, out var overflow);
if (overflow != 0)
throw new ArgumentOutOfRangeException(nameof(in32), "in32 is overflowing");
}
public void WriteToSpan(Span<byte> in32)
{
E.WriteToSpan(in32);
}
public byte[] ToBytes()
{
byte[] b = new byte[32];
WriteToSpan(b);
return b;
}
}
}
#endif
| #if HAS_SPAN
#nullable enable
using NBitcoin.Secp256k1.Musig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
namespace NBitcoin.Secp256k1.Musig
{
#if SECP256K1_LIB
public
#endif
class MusigPartialSignature
{
#if SECP256K1_LIB
public
#else
internal
#endif
readonly Scalar E;
public MusigPartialSignature(Scalar e)
{
this.E = e;
}
public MusigPartialSignature(ReadOnlySpan<byte> in32)
{
this.E = new Scalar(in32, out var overflow);
if (overflow != 0)
throw new ArgumentOutOfRangeException(nameof(in32), "in32 is overflowing");
}
public void WriteToSpan(Span<byte> in32)
{
E.WriteToSpan(in32);
}
public byte[] ToBytes()
{
byte[] b = new byte[32];
WriteToSpan(b);
return b;
}
}
}
#endif
|
Fix native AdjustImei class path | using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.Adjust");
}
ajcAdjustImei.CallStatic("readImei");
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.Adjust");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
| using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("readImei");
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
|
Include git information in json file | namespace StyleCop.Analyzers.Status.Generator
{
using System;
using System.IO;
using LibGit2Sharp;
using Newtonsoft.Json;
/// <summary>
/// The starting point of this application.
/// </summary>
internal class Program
{
/// <summary>
/// The starting point of this application.
/// </summary>
/// <param name="args">The command line parameters.</param>
internal static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to sln file required.");
return;
}
SolutionReader reader = SolutionReader.CreateAsync(args[0]).Result;
var diagnostics = reader.GetDiagnosticsAsync().Result;
string commitId;
using (Repository repository = new Repository(Path.GetDirectoryName(args[0])))
{
commitId = repository.Head.Tip.Sha;
}
var output = new
{
diagnostics,
commitId
};
Console.WriteLine(JsonConvert.SerializeObject(output));
}
}
}
| namespace StyleCop.Analyzers.Status.Generator
{
using System;
using System.IO;
using System.Linq;
using LibGit2Sharp;
using Newtonsoft.Json;
/// <summary>
/// The starting point of this application.
/// </summary>
internal class Program
{
/// <summary>
/// The starting point of this application.
/// </summary>
/// <param name="args">The command line parameters.</param>
internal static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to sln file required.");
return;
}
SolutionReader reader = SolutionReader.CreateAsync(args[0]).Result;
var diagnostics = reader.GetDiagnosticsAsync().Result;
Commit commit;
string commitId;
using (Repository repository = new Repository(Path.GetDirectoryName(args[0])))
{
commitId = repository.Head.Tip.Sha;
commit = repository.Head.Tip;
var output = new
{
diagnostics,
git = new
{
commit.Sha,
commit.Message,
commit.Author,
commit.Committer,
Parents = commit.Parents.Select(x => x.Sha)
}
};
Console.WriteLine(JsonConvert.SerializeObject(output));
}
}
}
}
|
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.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: AssemblyDescription("Autofac WCF Integration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Wcf, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Wcf, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
|
Add data contract attributes to ComparisionReport.cs | using System.Collections.Generic;
namespace Gigobyte.Daterpillar.Compare
{
public class ComparisonReport
{
public Counter Counters;
public Outcome Summary { get; set; }
public IList<Discrepancy> Discrepancies { get; set; }
public struct Counter
{
public int SourceTables;
public int DestTables;
}
}
} | using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Gigobyte.Daterpillar.Compare
{
[DataContract]
public class ComparisonReport : IEnumerable<Discrepancy>
{
public Counter Counters;
[DataMember]
public Outcome Summary { get; set; }
[DataMember]
public IList<Discrepancy> Discrepancies { get; set; }
public IEnumerator<Discrepancy> GetEnumerator()
{
foreach (var item in Discrepancies) { yield return item; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Counter
{
public int SourceTables;
public int DestTables;
}
}
} |
Fix metaData JSON property name case. | using System;
using Newtonsoft.Json;
using Toggl.Phoebe.Bugsnag.Json;
using System.Collections.Generic;
namespace Toggl.Phoebe.Bugsnag.Data
{
[JsonObject (MemberSerialization.OptIn)]
public class Event
{
[JsonProperty ("user", DefaultValueHandling = DefaultValueHandling.Ignore)]
public UserInfo User { get; set; }
[JsonProperty ("app")]
public ApplicationInfo App { get; set; }
[JsonProperty ("appState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ApplicationState AppState { get; set; }
[JsonProperty ("device", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemInfo System { get; set; }
[JsonProperty ("deviceState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemState SystemState { get; set; }
[JsonProperty ("context")]
public string Context { get; set; }
[JsonProperty ("severity"), JsonConverter (typeof(ErrorSeverityConverter))]
public ErrorSeverity Severity { get; set; }
[JsonProperty ("exceptions")]
public List<ExceptionInfo> Exceptions { get; set; }
[JsonProperty ("metadata")]
public Metadata Metadata { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using Toggl.Phoebe.Bugsnag.Json;
using System.Collections.Generic;
namespace Toggl.Phoebe.Bugsnag.Data
{
[JsonObject (MemberSerialization.OptIn)]
public class Event
{
[JsonProperty ("user", DefaultValueHandling = DefaultValueHandling.Ignore)]
public UserInfo User { get; set; }
[JsonProperty ("app")]
public ApplicationInfo App { get; set; }
[JsonProperty ("appState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ApplicationState AppState { get; set; }
[JsonProperty ("device", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemInfo System { get; set; }
[JsonProperty ("deviceState", DefaultValueHandling = DefaultValueHandling.Ignore)]
public SystemState SystemState { get; set; }
[JsonProperty ("context")]
public string Context { get; set; }
[JsonProperty ("severity"), JsonConverter (typeof(ErrorSeverityConverter))]
public ErrorSeverity Severity { get; set; }
[JsonProperty ("exceptions")]
public List<ExceptionInfo> Exceptions { get; set; }
[JsonProperty ("metaData")]
public Metadata Metadata { get; set; }
}
}
|
Make sure MercuryId do not get serialized. | using System.Runtime.Serialization;
namespace Plexo
{
[DataContract]
public class Currency
{
[DataMember]
public int CurrencyId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Plural { get; set; }
[DataMember]
public string Symbol { get; set; }
//Mercury Id is for internal use, no serialization required
public int MercuryId { get; set; }
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Plexo
{
[DataContract]
public class Currency
{
[DataMember]
public int CurrencyId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Plural { get; set; }
[DataMember]
public string Symbol { get; set; }
//Mercury Id is for internal use, no serialization required
[JsonIgnore]
public int MercuryId { get; set; }
}
} |
Fix registration of tooltip only highlighter | using JetBrains.TextControl.DocumentMarkup;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon.Attributes
{
[RegisterHighlighter(GUID_REFERENCE_TOOLTIP, EffectType = EffectType.TEXT)]
public static class AsmDefHighlightingAttributeIds
{
public const string GUID_REFERENCE_TOOLTIP = "ReSharper AsmDef GUID Reference Tooltip";
}
} | using JetBrains.TextControl.DocumentMarkup;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon.Attributes
{
// Rider doesn't support an empty set of attributes (all the implementations of IRiderHighlighterModelCreator
// return null), so we must define something. If we define an EffectType, ReSharper throws if we don't define it
// properly. But this is just a tooltip, and should have EffectType.NONE. So define one dummy attribute, this keeps
// both Rider and ReSharper happy
[RegisterHighlighter(GUID_REFERENCE_TOOLTIP, FontFamily = "Unused")]
public static class AsmDefHighlightingAttributeIds
{
public const string GUID_REFERENCE_TOOLTIP = "ReSharper AsmDef GUID Reference Tooltip";
}
} |
Fix metadata key, its the aggregate sequence number not the global one | // The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow
{
public sealed class MetadataKeys
{
public const string EventName = "event_name";
public const string EventVersion = "event_version";
public const string Timestamp = "timestamp";
public const string AggregateSequenceNumber = "global_sequence_number";
}
}
| // The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow
{
public sealed class MetadataKeys
{
public const string EventName = "event_name";
public const string EventVersion = "event_version";
public const string Timestamp = "timestamp";
public const string AggregateSequenceNumber = "aggregate_sequence_number";
}
}
|
Fix catch selection blueprint not displayed after copy-pasted | // 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.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public abstract class CatchSelectionBlueprint<THitObject> : HitObjectSelectionBlueprint<THitObject>
where THitObject : CatchHitObject
{
public override Vector2 ScreenSpaceSelectionPoint
{
get
{
float x = HitObject.OriginalX;
float y = HitObjectContainer.PositionAtTime(HitObject.StartTime);
return HitObjectContainer.ToScreenSpace(new Vector2(x, y + HitObjectContainer.DrawHeight));
}
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => SelectionQuad.Contains(screenSpacePos);
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
protected CatchSelectionBlueprint(THitObject hitObject)
: base(hitObject)
{
}
}
}
| // 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.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public abstract class CatchSelectionBlueprint<THitObject> : HitObjectSelectionBlueprint<THitObject>
where THitObject : CatchHitObject
{
protected override bool AlwaysShowWhenSelected => true;
public override Vector2 ScreenSpaceSelectionPoint
{
get
{
float x = HitObject.OriginalX;
float y = HitObjectContainer.PositionAtTime(HitObject.StartTime);
return HitObjectContainer.ToScreenSpace(new Vector2(x, y + HitObjectContainer.DrawHeight));
}
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => SelectionQuad.Contains(screenSpacePos);
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
protected CatchSelectionBlueprint(THitObject hitObject)
: base(hitObject)
{
}
}
}
|
Fix flags (Mac shouldn't be 0 based) | using System;
namespace Cake.Xamarin.Build
{
[Flags]
public enum BuildPlatforms
{
Mac = 0,
Windows = 1,
Linux = 2
}
}
| using System;
namespace Cake.Xamarin.Build
{
[Flags]
public enum BuildPlatforms
{
Mac = 1,
Windows = 2,
Linux = 4
}
}
|
Use bufferless stream to improve perf and resource usage | using System.IO;
using System.IO.Compression;
using System.Web;
namespace Kudu.Services
{
public static class HttpRequestExtensions
{
public static Stream GetInputStream(this HttpRequestBase request)
{
var contentEncoding = request.Headers["Content-Encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip"))
{
return new GZipStream(request.InputStream, CompressionMode.Decompress);
}
return request.InputStream;
}
}
}
| using System.IO;
using System.IO.Compression;
using System.Web;
namespace Kudu.Services
{
public static class HttpRequestExtensions
{
public static Stream GetInputStream(this HttpRequestBase request)
{
var contentEncoding = request.Headers["Content-Encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip"))
{
return new GZipStream(request.GetBufferlessInputStream(), CompressionMode.Decompress);
}
return request.GetBufferlessInputStream();
}
}
}
|
Remove need for function test to register telemetry source | using System.Diagnostics.Tracing;
using Glimpse.Agent.AspNet.Mvc;
using Glimpse.Agent.Web;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.FunctionalTest.Website
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGlimpse()
.RunningAgentWeb()
.RunningServerWeb()
.WithLocalAgent();
services.AddMvc();
services.AddTransient<MvcTelemetryListener>();
}
public void Configure(IApplicationBuilder app)
{
var telemetryListener = app.ApplicationServices.GetRequiredService<TelemetryListener>();
telemetryListener.SubscribeWithAdapter(app.ApplicationServices.GetRequiredService<MvcTelemetryListener>());
app.UseGlimpseServer();
app.UseGlimpseAgent();
app.UseMvcWithDefaultRoute();
}
}
}
| using System.Diagnostics.Tracing;
using Glimpse.Agent.AspNet.Mvc;
using Glimpse.Agent.Web;
using Glimpse.Server.Web;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.FunctionalTest.Website
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGlimpse()
.RunningAgentWeb()
.RunningServerWeb()
.WithLocalAgent();
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseGlimpseServer();
app.UseGlimpseAgent();
app.UseMvcWithDefaultRoute();
}
}
}
|
Allow substituting of internal types. | // Copyright (c) Samuel Cragg.
//
// Licensed under the MIT license. See LICENSE file in the project root for
// full license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Samuel Cragg")]
[assembly: AssemblyProduct("Crest.OpenApi")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("OpenApi.UnitTests")]
| // Copyright (c) Samuel Cragg.
//
// Licensed under the MIT license. See LICENSE file in the project root for
// full license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Samuel Cragg")]
[assembly: AssemblyProduct("Crest.OpenApi")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // NSubstitute
[assembly: InternalsVisibleTo("OpenApi.UnitTests")]
|
Reset the counter for the next playthrough - BH | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DestroyEnemy : MonoBehaviour {
public static int kills = 0;
void OnCollisionEnter (Collision col) {
if(col.gameObject.name.Contains("Monster")) {
kills += 1;
Destroy(col.gameObject);
if (kills >= 5) {
SceneManager.LoadScene ("GameWin", LoadSceneMode.Single);
}
}
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DestroyEnemy : MonoBehaviour {
public static int kills = 0;
void OnCollisionEnter (Collision col) {
if(col.gameObject.name.Contains("Monster")) {
kills += 1;
Destroy(col.gameObject);
if (kills >= 5) {
kills = 0;
SceneManager.LoadScene ("GameWin", LoadSceneMode.Single);
}
}
}
} |
Allow configure to be null | using System;
using Microsoft.Extensions.DependencyInjection;
using MR.Augmenter.Internal;
namespace MR.Augmenter
{
public static class AugmenterServiceCollectionExtensions
{
public static IAugmenterBuilder AddAugmenter(
this IServiceCollection services,
Action<AugmenterConfiguration> configure)
{
services.AddScoped<IAugmenter, Augmenter>();
var configuration = new AugmenterConfiguration();
configure(configuration);
configuration.Build();
services.AddSingleton(configuration);
return new AugmenterBuilder(services);
}
}
}
| using System;
using Microsoft.Extensions.DependencyInjection;
using MR.Augmenter.Internal;
namespace MR.Augmenter
{
public static class AugmenterServiceCollectionExtensions
{
/// <summary>
/// Adds augmenter to services.
/// </summary>
/// <param name="services"></param>
/// <param name="configure">Can be null.</param>
public static IAugmenterBuilder AddAugmenter(
this IServiceCollection services,
Action<AugmenterConfiguration> configure)
{
services.AddScoped<IAugmenter, Augmenter>();
var configuration = new AugmenterConfiguration();
configure?.Invoke(configuration);
configuration.Build();
services.AddSingleton(configuration);
return new AugmenterBuilder(services);
}
}
}
|
Set a default value for MP3 recording preset for new config files | using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
namespace AudioSharp.Config
{
public class ConfigHandler
{
public static void SaveConfig(Configuration config)
{
string json = JsonUtils.SerializeObject(config);
File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
}
public static Configuration ReadConfig()
{
string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
if (File.Exists(path))
{
string json = File.ReadAllText(path);
Configuration config = JsonUtils.DeserializeObject<Configuration>(json);
if (config.MP3EncodingPreset == 0)
config.MP3EncodingPreset = 1001;
return config;
}
return new Configuration()
{
RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
RecordingPrefix = "Recording{n}",
NextRecordingNumber = 1,
AutoIncrementRecordingNumber = true,
OutputFormat = "wav",
ShowTrayIcon = true,
GlobalHotkeys = new Dictionary<HotkeyType, Tuple<Key, ModifierKeys>>(),
RecordingSettingsPanelVisible = true,
RecordingOutputPanelVisible = true,
CheckForUpdates = true
};
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Input;
using AudioSharp.Utils;
namespace AudioSharp.Config
{
public class ConfigHandler
{
public static void SaveConfig(Configuration config)
{
string json = JsonUtils.SerializeObject(config);
File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json);
}
public static Configuration ReadConfig()
{
string path = Path.Combine(FileUtils.AppDataFolder, "settings.json");
if (File.Exists(path))
{
string json = File.ReadAllText(path);
Configuration config = JsonUtils.DeserializeObject<Configuration>(json);
if (config.MP3EncodingPreset == 0)
config.MP3EncodingPreset = 1001;
return config;
}
return new Configuration()
{
RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
RecordingPrefix = "Recording{n}",
NextRecordingNumber = 1,
AutoIncrementRecordingNumber = true,
OutputFormat = "wav",
ShowTrayIcon = true,
GlobalHotkeys = new Dictionary<HotkeyType, Tuple<Key, ModifierKeys>>(),
RecordingSettingsPanelVisible = true,
RecordingOutputPanelVisible = true,
CheckForUpdates = true,
MP3EncodingPreset = 1001
};
}
}
}
|
Update assembly and file version | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExtjsWd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ExtjsWd")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExtjsWd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ExtjsWd")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
|
Use safe cast for readability | using System.Linq;
using BobTheBuilder.ArgumentStore.Queries;
using JetBrains.Annotations;
namespace BobTheBuilder.Activation
{
internal class InstanceCreator
{
private readonly IArgumentStoreQuery constructorArgumentsQuery;
public InstanceCreator([NotNull]IArgumentStoreQuery constructorArgumentsQuery)
{
this.constructorArgumentsQuery = constructorArgumentsQuery;
}
public T CreateInstanceOf<T>() where T: class
{
var instanceType = typeof(T);
var constructor = instanceType.GetConstructors().Single();
var constructorArguments = constructorArgumentsQuery.Execute(instanceType);
return (T)constructor.Invoke(constructorArguments.Select(arg => arg.Value).ToArray());
}
}
}
| using System.Linq;
using BobTheBuilder.ArgumentStore.Queries;
using JetBrains.Annotations;
namespace BobTheBuilder.Activation
{
internal class InstanceCreator
{
private readonly IArgumentStoreQuery constructorArgumentsQuery;
public InstanceCreator([NotNull]IArgumentStoreQuery constructorArgumentsQuery)
{
this.constructorArgumentsQuery = constructorArgumentsQuery;
}
public T CreateInstanceOf<T>() where T: class
{
var instanceType = typeof(T);
var constructor = instanceType.GetConstructors().Single();
var constructorArguments = constructorArgumentsQuery.Execute(instanceType);
return constructor.Invoke(constructorArguments.Select(arg => arg.Value).ToArray()) as T;
}
}
}
|
Change Copyright page to License page. | using System;
using System.Web.Mvc;
using TeacherPouch.Models;
using TeacherPouch.Web.ViewModels;
namespace TeacherPouch.Web.Controllers
{
public partial class PagesController : ControllerBase
{
// GET: /
public virtual ViewResult Home()
{
return View(Views.Home);
}
public virtual ViewResult About()
{
return View(Views.About);
}
// GET: /Contact
public virtual ViewResult Contact()
{
var viewModel = new ContactViewModel();
return View(Views.Contact, viewModel);
}
// POST: /Contact
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Contact(ContactSubmission submision)
{
if (submision.IsValid)
{
if (!base.Request.IsLocal)
{
submision.SendEmail();
}
}
else
{
var viewModel = new ContactViewModel();
viewModel.ErrorMessage = "You must fill out the form before submitting.";
return View(Views.Contact, viewModel);
}
return RedirectToAction(Actions.ContactThanks());
}
// GET: /Contact/Thanks
public virtual ViewResult ContactThanks()
{
return View(Views.ContactThanks);
}
// GET: /Copyright
public virtual ViewResult Copyright()
{
return View(Views.Copyright);
}
}
}
| using System;
using System.Web.Mvc;
using TeacherPouch.Models;
using TeacherPouch.Web.ViewModels;
namespace TeacherPouch.Web.Controllers
{
public partial class PagesController : ControllerBase
{
// GET: /
public virtual ViewResult Home()
{
return View(Views.Home);
}
public virtual ViewResult About()
{
return View(Views.About);
}
// GET: /Contact
public virtual ViewResult Contact()
{
var viewModel = new ContactViewModel();
return View(Views.Contact, viewModel);
}
// POST: /Contact
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Contact(ContactSubmission submision)
{
if (submision.IsValid)
{
if (!base.Request.IsLocal)
{
submision.SendEmail();
}
}
else
{
var viewModel = new ContactViewModel();
viewModel.ErrorMessage = "You must fill out the form before submitting.";
return View(Views.Contact, viewModel);
}
return RedirectToAction(Actions.ContactThanks());
}
// GET: /Contact/Thanks
public virtual ViewResult ContactThanks()
{
return View(Views.ContactThanks);
}
// GET: /License
public virtual ViewResult License()
{
return View(Views.License);
}
}
}
|
Remove IScriptExtent.Translate method from extensions | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
return text.Split('\n').Select(line => line.TrimEnd('\r'));
}
public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta)
{
var newStartLineNumber = extent.StartLineNumber + lineDelta;
if (newStartLineNumber < 1)
{
throw new ArgumentException(
"Invalid line delta. Resulting start line number must be greather than 1.");
}
var newStartColumnNumber = extent.StartColumnNumber + columnDelta;
var newEndColumnNumber = extent.EndColumnNumber + columnDelta;
if (newStartColumnNumber < 1 || newEndColumnNumber < 1)
{
throw new ArgumentException(@"Invalid column delta.
Resulting start column and end column number must be greather than 1.");
}
return new ScriptExtent(
new ScriptPosition(
extent.File,
newStartLineNumber,
newStartColumnNumber,
extent.StartScriptPosition.Line),
new ScriptPosition(
extent.File,
extent.EndLineNumber + lineDelta,
newEndColumnNumber,
extent.EndScriptPosition.Line));
}
/// <summary>
/// Converts IScriptExtent to Range
/// </summary>
public static Range ToRange(this IScriptExtent extent)
{
return new Range(
extent.StartLineNumber,
extent.StartColumnNumber,
extent.EndLineNumber,
extent.EndColumnNumber);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
return text.Split('\n').Select(line => line.TrimEnd('\r'));
}
/// <summary>
/// Converts IScriptExtent to Range
/// </summary>
public static Range ToRange(this IScriptExtent extent)
{
return new Range(
extent.StartLineNumber,
extent.StartColumnNumber,
extent.EndLineNumber,
extent.EndColumnNumber);
}
}
}
|
Revert "Try to use SampleData instead of real data in the meantime" | using GitHub.Exports;
using GitHub.UI;
using GitHub.ViewModels;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using ReactiveUI;
namespace GitHub.VisualStudio.UI.Views
{
public class GenericPullRequestCreationView : SimpleViewUserControl<IPullRequestCreationViewModel, GenericPullRequestCreationView>
{ }
[ExportView(ViewType = UIViewType.PRCreation)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class PullRequestCreationView : GenericPullRequestCreationView
{
public PullRequestCreationView()
{
InitializeComponent();
// DataContextChanged += (s, e) => ViewModel = e.NewValue as IPullRequestCreationViewModel;
DataContextChanged += (s, e) => ViewModel = new GitHub.SampleData.PullRequestCreationViewModelDesigner() as IPullRequestCreationViewModel;
this.WhenActivated(d =>
{
});
}
}
}
| using GitHub.Exports;
using GitHub.UI;
using GitHub.ViewModels;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using ReactiveUI;
namespace GitHub.VisualStudio.UI.Views
{
public class GenericPullRequestCreationView : SimpleViewUserControl<IPullRequestCreationViewModel, GenericPullRequestCreationView>
{ }
[ExportView(ViewType = UIViewType.PRCreation)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class PullRequestCreationView : GenericPullRequestCreationView
{
public PullRequestCreationView()
{
InitializeComponent();
DataContextChanged += (s, e) => ViewModel = e.NewValue as IPullRequestCreationViewModel;
this.WhenActivated(d =>
{
});
}
}
}
|
Simplify release title with version selector | using System.Linq;
using System.Net;
using AngleSharp;
using AngleSharp.Parser.Html;
namespace WebDriverManager.DriverConfigs.Impl
{
public class OperaConfig : IDriverConfig
{
public virtual string GetName()
{
return "Opera";
}
public virtual string GetUrl32()
{
return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip";
}
public virtual string GetUrl64()
{
return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip";
}
public virtual string GetBinaryName()
{
return "operadriver.exe";
}
public virtual string GetLatestVersion()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var client = new WebClient())
{
var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases");
var parser = new HtmlParser(Configuration.Default.WithDefaultLoader());
var document = parser.Parse(htmlCode);
var version = document.QuerySelectorAll("[class~='release-title'] a")
.Select(element => element.TextContent)
.FirstOrDefault();
return version;
}
}
}
} | using System.Linq;
using System.Net;
using AngleSharp;
using AngleSharp.Parser.Html;
namespace WebDriverManager.DriverConfigs.Impl
{
public class OperaConfig : IDriverConfig
{
public virtual string GetName()
{
return "Opera";
}
public virtual string GetUrl32()
{
return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip";
}
public virtual string GetUrl64()
{
return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip";
}
public virtual string GetBinaryName()
{
return "operadriver.exe";
}
public virtual string GetLatestVersion()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var client = new WebClient())
{
var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases");
var parser = new HtmlParser(Configuration.Default.WithDefaultLoader());
var document = parser.Parse(htmlCode);
var version = document.QuerySelectorAll(".release-title > a")
.Select(element => element.TextContent)
.FirstOrDefault();
return version;
}
}
}
}
|
Add get best id method for season ids. | namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Newtonsoft.Json;
/// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt season.</summary>
public class TraktSeasonIds
{
/// <summary>Gets or sets the Trakt numeric id.</summary>
[JsonProperty(PropertyName = "trakt")]
public int Trakt { get; set; }
/// <summary>Gets or sets the numeric id from thetvdb.com</summary>
[JsonProperty(PropertyName = "tvdb")]
public int? Tvdb { get; set; }
/// <summary>Gets or sets the numeric id from themoviedb.org</summary>
[JsonProperty(PropertyName = "tmdb")]
public int? Tmdb { get; set; }
/// <summary>Gets or sets the numeric id from tvrage.com</summary>
[JsonProperty(PropertyName = "tvrage")]
public int? TvRage { get; set; }
/// <summary>Returns, whether any id has been set.</summary>
[JsonIgnore]
public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0;
}
}
| namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Newtonsoft.Json;
/// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt season.</summary>
public class TraktSeasonIds
{
/// <summary>Gets or sets the Trakt numeric id.</summary>
[JsonProperty(PropertyName = "trakt")]
public int Trakt { get; set; }
/// <summary>Gets or sets the numeric id from thetvdb.com</summary>
[JsonProperty(PropertyName = "tvdb")]
public int? Tvdb { get; set; }
/// <summary>Gets or sets the numeric id from themoviedb.org</summary>
[JsonProperty(PropertyName = "tmdb")]
public int? Tmdb { get; set; }
/// <summary>Gets or sets the numeric id from tvrage.com</summary>
[JsonProperty(PropertyName = "tvrage")]
public int? TvRage { get; set; }
/// <summary>Returns, whether any id has been set.</summary>
[JsonIgnore]
public bool HasAnyId => Trakt > 0 || Tvdb > 0 || Tvdb > 0 || TvRage > 0;
/// <summary>Gets the most reliable id from those that have been set.</summary>
/// <returns>The id as a string or an empty string, if no id is set.</returns>
public string GetBestId()
{
if (Trakt > 0)
return Trakt.ToString();
if (Tvdb.HasValue && Tvdb.Value > 0)
return Tvdb.Value.ToString();
if (Tmdb.HasValue && Tmdb.Value > 0)
return Tmdb.Value.ToString();
if (TvRage.HasValue && TvRage.Value > 0)
return TvRage.Value.ToString();
return string.Empty;
}
}
}
|
Test that all accounts decrypt correctly | using System.Linq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class VaultTest
{
[Test]
public void Create_returns_vault_with_correct_accounts()
{
var vault = Vault.Create(new Blob(TestData.Blob, 1));
Assert.AreEqual(TestData.Accounts.Length, vault.EncryptedAccounts.Length);
Assert.AreEqual(TestData.Accounts.Select(i => i.Url), vault.EncryptedAccounts.Select(i => i.Url));
}
[Test]
public void DecryptAccount_decrypts_account()
{
var vault = Vault.Create(new Blob(TestData.Blob, 1));
var account = vault.DecryptAccount(vault.EncryptedAccounts[0], "p8utF7ZB8yD06SrtrD4hsdvEOiBU1Y19cr2dhG9DWZg=".Decode64());
Assert.AreEqual(TestData.Accounts[0].Name, account.Name);
Assert.AreEqual(TestData.Accounts[0].Username, account.Username);
Assert.AreEqual(TestData.Accounts[0].Password, account.Password);
Assert.AreEqual(TestData.Accounts[0].Url, account.Url);
}
}
}
| using System.Linq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class VaultTest
{
[Test]
public void Create_returns_vault_with_correct_accounts()
{
var vault = Vault.Create(new Blob(TestData.Blob, 1));
Assert.AreEqual(TestData.Accounts.Length, vault.EncryptedAccounts.Length);
Assert.AreEqual(TestData.Accounts.Select(i => i.Url), vault.EncryptedAccounts.Select(i => i.Url));
}
[Test]
public void DecryptAccount_decrypts_accounts()
{
var vault = Vault.Create(new Blob(TestData.Blob, 1));
for (var i = 0; i < vault.EncryptedAccounts.Length; ++i)
{
var account = vault.DecryptAccount(vault.EncryptedAccounts[i],
"p8utF7ZB8yD06SrtrD4hsdvEOiBU1Y19cr2dhG9DWZg=".Decode64());
var expectedAccount = TestData.Accounts[i];
Assert.AreEqual(expectedAccount.Name, account.Name);
Assert.AreEqual(expectedAccount.Username, account.Username);
Assert.AreEqual(expectedAccount.Password, account.Password);
Assert.AreEqual(expectedAccount.Url, account.Url);
}
}
}
}
|
Remove "Portable" from namespace name in CoreAssets | using Urho.Gui;
using Urho.Resources;
namespace Urho.Portable
{
//TODO: generate this class using T4 from CoreData folder
public static class CoreAssets
{
public static ResourceCache Cache => Application.Current.ResourceCache;
public static class Models
{
public static Model Box => Cache.GetModel("Models/Box.mdl");
public static Model Cone => Cache.GetModel("Models/Cone.mdl");
public static Model Cylinder => Cache.GetModel("Models/Cylinder.mdl");
public static Model Plane => Cache.GetModel("Models/Plane.mdl");
public static Model Pyramid => Cache.GetModel("Models/Pyramid.mdl");
public static Model Sphere => Cache.GetModel("Models/Sphere.mdl");
public static Model Torus => Cache.GetModel("Models/Torus.mdl");
}
public static class Materials
{
public static Material DefaultGrey => Cache.GetMaterial("Materials/DefaultGrey.xml");
}
public static class Fonts
{
public static Font AnonymousPro => Cache.GetFont("Fonts/Anonymous Pro.ttf");
}
public static class RenderPaths
{
}
public static class Shaders
{
}
public static class Techniques
{
}
}
}
| using Urho.Gui;
using Urho.Resources;
namespace Urho
{
//TODO: generate this class using T4 from CoreData folder
public static class CoreAssets
{
public static ResourceCache Cache => Application.Current.ResourceCache;
public static class Models
{
public static Model Box => Cache.GetModel("Models/Box.mdl");
public static Model Cone => Cache.GetModel("Models/Cone.mdl");
public static Model Cylinder => Cache.GetModel("Models/Cylinder.mdl");
public static Model Plane => Cache.GetModel("Models/Plane.mdl");
public static Model Pyramid => Cache.GetModel("Models/Pyramid.mdl");
public static Model Sphere => Cache.GetModel("Models/Sphere.mdl");
public static Model Torus => Cache.GetModel("Models/Torus.mdl");
}
public static class Materials
{
public static Material DefaultGrey => Cache.GetMaterial("Materials/DefaultGrey.xml");
}
public static class Fonts
{
public static Font AnonymousPro => Cache.GetFont("Fonts/Anonymous Pro.ttf");
}
public static class RenderPaths
{
}
public static class Shaders
{
}
public static class Techniques
{
}
}
}
|
Replace main with top-level statements | using System;
using Microsoft.EntityFrameworkCore;
using SupportManager.Telegram.DAL;
using Topshelf;
namespace SupportManager.Telegram
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 2 && args[0].Equals("migrate", StringComparison.InvariantCultureIgnoreCase))
{
var filename = args[1];
var builder = new DbContextOptionsBuilder<UserDbContext>();
builder.UseSqlite($"Data Source={filename}");
var db = new UserDbContext(builder.Options);
db.Database.Migrate();
return;
}
var config = new Configuration();
var exitCode = HostFactory.Run(cfg =>
{
cfg.AddCommandLineDefinition("db", v => config.DbFileName = v);
cfg.AddCommandLineDefinition("botkey", v => config.BotKey = v);
cfg.AddCommandLineDefinition("url", v => config.SupportManagerUri = new Uri(v));
cfg.AddCommandLineDefinition("hostUrl", v => config.HostUri = new Uri(v));
cfg.Service<Service>(svc =>
{
svc.ConstructUsing(() => new Service(config));
svc.WhenStarted((s, h) => s.Start(h));
svc.WhenStopped((s, h) => s.Stop(h));
});
cfg.SetServiceName("SupportManager.Telegram");
cfg.SetDisplayName("SupportManager.Telegram");
cfg.SetDescription("SupportManager Telegram bot");
cfg.RunAsNetworkService();
cfg.StartAutomatically();
});
}
}
}
| using System;
using Microsoft.EntityFrameworkCore;
using SupportManager.Telegram;
using SupportManager.Telegram.Infrastructure;
using Topshelf;
if (args.Length == 2 && args[0].Equals("migrate", StringComparison.InvariantCultureIgnoreCase))
{
var db = DbContextFactory.Create(args[1]);
db.Database.Migrate();
return;
}
HostFactory.Run(cfg =>
{
var config = new Configuration();
cfg.AddCommandLineDefinition("db", v => config.DbFileName = v);
cfg.AddCommandLineDefinition("botkey", v => config.BotKey = v);
cfg.AddCommandLineDefinition("url", v => config.SupportManagerUri = new Uri(v));
cfg.AddCommandLineDefinition("hostUrl", v => config.HostUri = new Uri(v));
cfg.Service<Service>(svc =>
{
svc.ConstructUsing(() => new Service(config));
svc.WhenStarted((s, h) => s.Start(h));
svc.WhenStopped((s, h) => s.Stop(h));
});
cfg.SetServiceName("SupportManager.Telegram");
cfg.SetDisplayName("SupportManager.Telegram");
cfg.SetDescription("SupportManager Telegram bot");
cfg.RunAsNetworkService();
cfg.StartAutomatically();
}); |
Remove Id from storable object | using System;
using System.Collections.Generic;
namespace LazyStorage
{
public class StorableObject : IEquatable<StorableObject>
{
public int LazyStorageInternalId { get; set; }
public Dictionary<string, string> Info { get; }
public StorableObject()
{
Info = new Dictionary<string, string>();
}
public bool Equals(StorableObject other)
{
return (other.LazyStorageInternalId == LazyStorageInternalId);
}
}
} | using System;
using System.Collections.Generic;
namespace LazyStorage
{
public class StorableObject
{
public Dictionary<string, string> Info { get; }
public StorableObject()
{
Info = new Dictionary<string, string>();
}
}
} |
Allow anonymous on password reset requests | using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Core.DomainModel;
using Core.DomainServices;
using Presentation.Web.Models;
namespace Presentation.Web.Controllers.API
{
public class PasswordResetRequestController : BaseApiController
{
private readonly IUserService _userService;
private readonly IUserRepository _userRepository;
public PasswordResetRequestController(IUserService userService, IUserRepository userRepository)
{
_userService = userService;
_userRepository = userRepository;
}
// POST api/PasswordResetRequest
public HttpResponseMessage Post([FromBody] UserDTO input)
{
try
{
var user = _userRepository.GetByEmail(input.Email);
var request = _userService.IssuePasswordReset(user, null, null);
return Ok();
}
catch (Exception e)
{
return CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
// GET api/PasswordResetRequest
public HttpResponseMessage Get(string requestId)
{
try
{
var request = _userService.GetPasswordReset(requestId);
if (request == null) return NotFound();
var dto = AutoMapper.Mapper.Map<PasswordResetRequest, PasswordResetRequestDTO>(request);
var msg = CreateResponse(HttpStatusCode.OK, dto);
return msg;
}
catch (Exception e)
{
return CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
}
}
| using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Core.DomainModel;
using Core.DomainServices;
using Presentation.Web.Models;
namespace Presentation.Web.Controllers.API
{
[AllowAnonymous]
public class PasswordResetRequestController : BaseApiController
{
private readonly IUserService _userService;
private readonly IUserRepository _userRepository;
public PasswordResetRequestController(IUserService userService, IUserRepository userRepository)
{
_userService = userService;
_userRepository = userRepository;
}
// POST api/PasswordResetRequest
public HttpResponseMessage Post([FromBody] UserDTO input)
{
try
{
var user = _userRepository.GetByEmail(input.Email);
var request = _userService.IssuePasswordReset(user, null, null);
return Ok();
}
catch (Exception e)
{
return CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
// GET api/PasswordResetRequest
public HttpResponseMessage Get(string requestId)
{
try
{
var request = _userService.GetPasswordReset(requestId);
if (request == null) return NotFound();
var dto = AutoMapper.Mapper.Map<PasswordResetRequest, PasswordResetRequestDTO>(request);
var msg = CreateResponse(HttpStatusCode.OK, dto);
return msg;
}
catch (Exception e)
{
return CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
}
}
|
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);
}
}
}
|
Add capacity and time window data to route events. | using System;
using System.Collections.Generic;
namespace NFleet.Data
{
public class RouteEventData : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.routeevent";
public static string MIMEVersion = "2.0";
int IVersioned.VersionNumber { get; set; }
public string State { get; set; }
public double WaitingTimeBefore { get; set; }
public DateTime? ArrivalTime { get; set; }
public DateTime? DepartureTime { get; set; }
public List<Link> Meta { get; set; }
public string DataState { get; set; }
public string FeasibilityState { get; set; }
public int TaskEventId { get; set; }
public KPIData KPIs { get; set; }
public string Type { get; set; }
public LocationData Location { get; set; }
}
}
| using System;
using System.Collections.Generic;
namespace NFleet.Data
{
public class RouteEventData : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.routeevent";
public static string MIMEVersion = "2.0";
int IVersioned.VersionNumber { get; set; }
public string State { get; set; }
public double WaitingTimeBefore { get; set; }
public DateTime? ArrivalTime { get; set; }
public DateTime? DepartureTime { get; set; }
public List<Link> Meta { get; set; }
public string DataState { get; set; }
public string FeasibilityState { get; set; }
public int TaskEventId { get; set; }
public KPIData KPIs { get; set; }
public string Type { get; set; }
public LocationData Location { get; set; }
public List<CapacityData> Capacities { get; set; }
public List<TimeWindowData> TimeWindows { get; set; }
}
}
|
Change the method to expression body definition | using System;
using System.Linq;
using System.Text;
namespace SCPI
{
public class IDN : ICommand
{
public string Description => "Query the ID string of the instrument";
public string Manufacturer { get; private set; }
public string Model { get; private set; }
public string SerialNumber { get; private set; }
public string SoftwareVersion { get; private set; }
public string HelpMessage()
{
return nameof(IDN);
}
public string Command(params string[] parameters)
{
return "*IDN?";
}
public bool Parse(byte[] data)
{
// RIGOL TECHNOLOGIES,<model>,<serial number>,<software version>
var id = Encoding.ASCII.GetString(data).Split(',').Select(f => f.Trim());
// According to IEEE 488.2 there are four fields in the response
if (id.Count() == 4)
{
Manufacturer = id.ElementAt(0);
Model = id.ElementAt(1);
SerialNumber = id.ElementAt(2);
SoftwareVersion = id.ElementAt(3);
return true;
}
return false;
}
}
}
| using System.Linq;
using System.Text;
namespace SCPI
{
public class IDN : ICommand
{
public string Description => "Query the ID string of the instrument";
public string Manufacturer { get; private set; }
public string Model { get; private set; }
public string SerialNumber { get; private set; }
public string SoftwareVersion { get; private set; }
public string HelpMessage() => nameof(IDN);
public string Command(params string[] parameters) => "*IDN?";
public bool Parse(byte[] data)
{
// RIGOL TECHNOLOGIES,<model>,<serial number>,<software version>
var id = Encoding.ASCII.GetString(data).Split(',').Select(f => f.Trim());
// According to IEEE 488.2 there are four fields in the response
if (id.Count() == 4)
{
Manufacturer = id.ElementAt(0);
Model = id.ElementAt(1);
SerialNumber = id.ElementAt(2);
SoftwareVersion = id.ElementAt(3);
return true;
}
return false;
}
}
}
|
Add note about reusing of tooltips and the new behaviour | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Cursor
{
/// <summary>
/// Implementing this interface allows the implementing <see cref="Drawable"/> to display a custom tooltip if it is the child of a <see cref="TooltipContainer"/>.
/// Keep in mind that tooltips can only be displayed by a <see cref="TooltipContainer"/> if the <see cref="Drawable"/> implementing <see cref="IHasCustomTooltip"/> has <see cref="Drawable.HandlePositionalInput"/> set to true.
/// </summary>
public interface IHasCustomTooltip : ITooltipContentProvider
{
/// <summary>
/// The custom tooltip that should be displayed.
/// </summary>
/// <returns>The custom tooltip that should be displayed.</returns>
ITooltip GetCustomTooltip();
/// <summary>
/// Tooltip text that shows when hovering the drawable.
/// </summary>
object TooltipContent { get; }
}
/// <inheritdoc />
public interface IHasCustomTooltip<TContent> : IHasCustomTooltip
{
ITooltip IHasCustomTooltip.GetCustomTooltip() => GetCustomTooltip();
/// <inheritdoc cref="IHasCustomTooltip.GetCustomTooltip"/>
new ITooltip<TContent> GetCustomTooltip();
object IHasCustomTooltip.TooltipContent => TooltipContent;
/// <inheritdoc cref="IHasCustomTooltip.TooltipContent"/>
new TContent TooltipContent { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Cursor
{
/// <summary>
/// Implementing this interface allows the implementing <see cref="Drawable"/> to display a custom tooltip if it is the child of a <see cref="TooltipContainer"/>.
/// Keep in mind that tooltips can only be displayed by a <see cref="TooltipContainer"/> if the <see cref="Drawable"/> implementing <see cref="IHasCustomTooltip"/> has <see cref="Drawable.HandlePositionalInput"/> set to true.
/// </summary>
public interface IHasCustomTooltip : ITooltipContentProvider
{
/// <summary>
/// The custom tooltip that should be displayed.
/// </summary>
/// <remarks>
/// A tooltip may be reused between different drawables with different content if they share the same tooltip type.
/// Therefore it is recommended for all displayed content in the tooltip to be provided by <see cref="TooltipContent"/> instead.
/// </remarks>
/// <returns>The custom tooltip that should be displayed.</returns>
ITooltip GetCustomTooltip();
/// <summary>
/// Tooltip text that shows when hovering the drawable.
/// </summary>
object TooltipContent { get; }
}
/// <inheritdoc />
public interface IHasCustomTooltip<TContent> : IHasCustomTooltip
{
ITooltip IHasCustomTooltip.GetCustomTooltip() => GetCustomTooltip();
/// <inheritdoc cref="IHasCustomTooltip.GetCustomTooltip"/>
new ITooltip<TContent> GetCustomTooltip();
object IHasCustomTooltip.TooltipContent => TooltipContent;
/// <inheritdoc cref="IHasCustomTooltip.TooltipContent"/>
new TContent TooltipContent { get; }
}
}
|
Fix not null constraint failed exception | using NPoco;
using System;
namespace Dalian.Models
{
[PrimaryKey("SiteId")]
public class Sites
{
public string SiteId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Note { get; set; }
public string Source { get; set; }
public DateTime DateTime { get; set; }
public bool Active { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public string MetaKeywords { get; set; }
public int Status { get; set; }
public bool Bookmarklet { get; set; }
public bool ReadItLater { get; set; }
public bool Clipped { get; set; }
public string ArchiveUrl { get; set; }
public bool Highlight { get; set; }
public bool PersonalHighlight { get; set; }
}
} | using NPoco;
using System;
namespace Dalian.Models
{
[PrimaryKey("SiteId", AutoIncrement = false)]
public class Sites
{
public string SiteId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Note { get; set; }
public string Source { get; set; }
public DateTime DateTime { get; set; }
public bool Active { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public string MetaKeywords { get; set; }
public int Status { get; set; }
public bool Bookmarklet { get; set; }
public bool ReadItLater { get; set; }
public bool Clipped { get; set; }
public string ArchiveUrl { get; set; }
public bool Highlight { get; set; }
public bool PersonalHighlight { get; set; }
}
} |
Check if registered before trying. | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
namespace ServiceStack.DependencyInjection
{
public class DependencyResolver : IDisposable
{
private readonly ILifetimeScope _lifetimeScope;
public DependencyResolver(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public T Resolve<T>()
{
return _lifetimeScope.Resolve<T>();
}
public object Resolve(Type type)
{
return _lifetimeScope.Resolve(type);
}
public T TryResolve<T>()
{
try
{
return _lifetimeScope.Resolve<T>();
}
catch (DependencyResolutionException unusedException)
{
return default(T);
}
}
public void Dispose()
{
_lifetimeScope.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
namespace ServiceStack.DependencyInjection
{
public class DependencyResolver : IDisposable
{
private readonly ILifetimeScope _lifetimeScope;
public DependencyResolver(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public T Resolve<T>()
{
return _lifetimeScope.Resolve<T>();
}
public object Resolve(Type type)
{
return _lifetimeScope.Resolve(type);
}
public T TryResolve<T>()
{
if (_lifetimeScope.IsRegistered<T>())
{
try
{
return _lifetimeScope.Resolve<T>();
}
catch (DependencyResolutionException unusedException)
{
return default(T);
}
}
else
{
return default (T);
}
}
public void Dispose()
{
_lifetimeScope.Dispose();
}
}
}
|
Change expanded card content height to 200 | // 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.Input.Events;
using osu.Framework.Utils;
using osu.Game.Graphics.Containers;
namespace osu.Game.Beatmaps.Drawables.Cards
{
public class ExpandedContentScrollContainer : OsuScrollContainer
{
public const float HEIGHT = 400;
public ExpandedContentScrollContainer()
{
ScrollbarVisible = false;
}
protected override void Update()
{
base.Update();
Height = Math.Min(Content.DrawHeight, HEIGHT);
}
private bool allowScroll => !Precision.AlmostEquals(DrawSize, Content.DrawSize);
protected override bool OnDragStart(DragStartEvent e)
{
if (!allowScroll)
return false;
return base.OnDragStart(e);
}
protected override void OnDrag(DragEvent e)
{
if (!allowScroll)
return;
base.OnDrag(e);
}
protected override void OnDragEnd(DragEndEvent e)
{
if (!allowScroll)
return;
base.OnDragEnd(e);
}
protected override bool OnScroll(ScrollEvent e)
{
if (!allowScroll)
return false;
return base.OnScroll(e);
}
}
}
| // 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.Input.Events;
using osu.Framework.Utils;
using osu.Game.Graphics.Containers;
namespace osu.Game.Beatmaps.Drawables.Cards
{
public class ExpandedContentScrollContainer : OsuScrollContainer
{
public const float HEIGHT = 200;
public ExpandedContentScrollContainer()
{
ScrollbarVisible = false;
}
protected override void Update()
{
base.Update();
Height = Math.Min(Content.DrawHeight, HEIGHT);
}
private bool allowScroll => !Precision.AlmostEquals(DrawSize, Content.DrawSize);
protected override bool OnDragStart(DragStartEvent e)
{
if (!allowScroll)
return false;
return base.OnDragStart(e);
}
protected override void OnDrag(DragEvent e)
{
if (!allowScroll)
return;
base.OnDrag(e);
}
protected override void OnDragEnd(DragEndEvent e)
{
if (!allowScroll)
return;
base.OnDragEnd(e);
}
protected override bool OnScroll(ScrollEvent e)
{
if (!allowScroll)
return false;
return base.OnScroll(e);
}
}
}
|
Change message in register success | @model dynamic
@{
ViewBag.Title = "Регистрация успешна";
}
<h2>@ViewBag.Title</h2>
<p>Остался всего один клик! Проверьте свою почту, там лежит письмо от нас с просьбой подтвердить email...</p>
| @model dynamic
@{
ViewBag.Title = "Регистрация успешна";
}
<h2>@ViewBag.Title</h2>
<p>Остался всего один клик! Проверьте свою почту, там лежит письмо от нас с просьбой подтвердить email.</p>
|
Add --port option to samples | using System;
using Ooui;
namespace Samples
{
class Program
{
static void Main (string[] args)
{
new ButtonSample ().Publish ();
new TodoSample ().Publish ();
Console.ReadLine ();
}
}
}
| using System;
using Ooui;
namespace Samples
{
class Program
{
static void Main (string[] args)
{
for (var i = 0; i < args.Length; i++) {
var a = args[i];
switch (args[i]) {
case "-p" when i + 1 < args.Length:
case "--port" when i + 1 < args.Length:
{
int p;
if (int.TryParse (args[i + 1], out p)) {
UI.Port = p;
}
i++;
}
break;
}
}
new ButtonSample ().Publish ();
new TodoSample ().Publish ();
Console.ReadLine ();
}
}
}
|
Rename arguments to match base names | using Hangfire.Common;
using Hangfire.Console.Serialization;
using Hangfire.Console.Storage;
using Hangfire.Server;
using Hangfire.States;
using System;
namespace Hangfire.Console.Server
{
/// <summary>
/// Server filter to initialize and cleanup console environment.
/// </summary>
internal class ConsoleServerFilter : IServerFilter
{
private readonly ConsoleOptions _options;
public ConsoleServerFilter(ConsoleOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
_options = options;
}
public void OnPerforming(PerformingContext context)
{
var state = context.Connection.GetStateData(context.BackgroundJob.Id);
if (state == null)
{
// State for job not found?
return;
}
if (!string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase))
{
// Not in Processing state? Something is really off...
return;
}
var startedAt = JobHelper.DeserializeDateTime(state.Data["StartedAt"]);
context.Items["ConsoleContext"] = new ConsoleContext(
new ConsoleId(context.BackgroundJob.Id, startedAt),
new ConsoleStorage(context.Connection));
}
public void OnPerformed(PerformedContext context)
{
if (context.Canceled)
{
// Processing was been cancelled by one of the job filters
// There's nothing to do here, as processing hasn't started
return;
}
ConsoleContext.FromPerformContext(context)?.Expire(_options.ExpireIn);
}
}
}
| using Hangfire.Common;
using Hangfire.Console.Serialization;
using Hangfire.Console.Storage;
using Hangfire.Server;
using Hangfire.States;
using System;
namespace Hangfire.Console.Server
{
/// <summary>
/// Server filter to initialize and cleanup console environment.
/// </summary>
internal class ConsoleServerFilter : IServerFilter
{
private readonly ConsoleOptions _options;
public ConsoleServerFilter(ConsoleOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
_options = options;
}
public void OnPerforming(PerformingContext filterContext)
{
var state = filterContext.Connection.GetStateData(filterContext.BackgroundJob.Id);
if (state == null)
{
// State for job not found?
return;
}
if (!string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase))
{
// Not in Processing state? Something is really off...
return;
}
var startedAt = JobHelper.DeserializeDateTime(state.Data["StartedAt"]);
filterContext.Items["ConsoleContext"] = new ConsoleContext(
new ConsoleId(filterContext.BackgroundJob.Id, startedAt),
new ConsoleStorage(filterContext.Connection));
}
public void OnPerformed(PerformedContext filterContext)
{
if (filterContext.Canceled)
{
// Processing was been cancelled by one of the job filters
// There's nothing to do here, as processing hasn't started
return;
}
ConsoleContext.FromPerformContext(filterContext)?.Expire(_options.ExpireIn);
}
}
}
|
Destroy obstacles disabled at scene start | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DarkRoomObstacleEnable : MonoBehaviour
{
[SerializeField]
private float maxXDistance = 11f;
void Start ()
{
}
void Update ()
{
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
var shouldEnable = Mathf.Abs(MainCameraSingleton.instance.transform.position.x - child.position.x) <= maxXDistance;
if (shouldEnable != child.gameObject.activeInHierarchy)
child.gameObject.SetActive(shouldEnable);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class DarkRoomObstacleEnable : MonoBehaviour
{
[SerializeField]
private float maxXDistance = 11f;
void Start ()
{
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
if (!child.gameObject.activeInHierarchy)
Destroy(child.gameObject);
}
}
void Update ()
{
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
var shouldEnable = Mathf.Abs(MainCameraSingleton.instance.transform.position.x - child.position.x) <= maxXDistance;
if (shouldEnable != child.gameObject.activeInHierarchy)
child.gameObject.SetActive(shouldEnable);
}
}
}
|
Allow verb name to be optional. | using System;
namespace clipr
{
/// <summary>
/// Mark the property as a subcommand. (cf. 'svn checkout')
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class VerbAttribute : Attribute
{
/// <summary>
/// Name of the subcommand. If provided as an argument, it
/// will trigger parsing of the subcommand.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Description of the subcommand, suitable for help pages.
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Create a new subcommand.
/// </summary>
/// <param name="name"></param>
public VerbAttribute(string name)
{
Name = name;
}
/// <summary>
/// Create a new subcommand.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
public VerbAttribute(string name, string description)
{
Name = name;
Description = description;
}
}
}
| using System;
namespace clipr
{
/// <summary>
/// Mark the property as a subcommand. (cf. 'svn checkout')
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class VerbAttribute : Attribute
{
/// <summary>
/// Name of the subcommand. If provided as an argument, it
/// will trigger parsing of the subcommand.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Description of the subcommand, suitable for help pages.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Create a new subcommand.
/// </summary>
public VerbAttribute()
{
}
/// <summary>
/// Create a new subcommand.
/// </summary>
/// <param name="name"></param>
public VerbAttribute(string name)
{
Name = name;
}
/// <summary>
/// Create a new subcommand.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
public VerbAttribute(string name, string description)
{
Name = name;
Description = description;
}
}
}
|
Remove explicit build addin dependency version | #tool nuget:?package=XamarinComponent&version=1.1.0.32
#addin nuget:?package=Cake.Xamarin.Build&version=1.0.14.0
#addin nuget:?package=Cake.Xamarin
#addin nuget:?package=Cake.XCode
| #tool nuget:?package=XamarinComponent&version=1.1.0.32
#addin nuget:?package=Cake.Xamarin.Build
#addin nuget:?package=Cake.Xamarin
#addin nuget:?package=Cake.XCode
|
Fix video player tooltip going outside Form bounds | using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace TweetDuck.Video.Controls{
sealed class LabelTooltip : Label{
public LabelTooltip(){
Visible = false;
}
public void AttachTooltip(Control control, bool followCursor, string tooltip){
AttachTooltip(control, followCursor, args => tooltip);
}
public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArgs, string> tooltipFunc){
control.MouseEnter += control_MouseEnter;
control.MouseLeave += control_MouseLeave;
control.MouseMove += (sender, args) => {
Form form = control.FindForm();
Debug.Assert(form != null);
Text = tooltipFunc(args);
Location = form.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X-Width/2+(followCursor ? args.X : control.Width/2), -Height+Margin.Top-Margin.Bottom)));;
};
}
private void control_MouseEnter(object sender, EventArgs e){
Visible = true;
}
private void control_MouseLeave(object sender, EventArgs e){
Visible = false;
}
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace TweetDuck.Video.Controls{
sealed class LabelTooltip : Label{
public LabelTooltip(){
Visible = false;
}
public void AttachTooltip(Control control, bool followCursor, string tooltip){
AttachTooltip(control, followCursor, args => tooltip);
}
public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArgs, string> tooltipFunc){
control.MouseEnter += control_MouseEnter;
control.MouseLeave += control_MouseLeave;
control.MouseMove += (sender, args) => {
Form form = control.FindForm();
System.Diagnostics.Debug.Assert(form != null);
Text = tooltipFunc(args);
Point loc = form.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X+(followCursor ? args.X : control.Width/2), 0)));
loc.X = Math.Max(0, Math.Min(form.Width-Width, loc.X-Width/2));
loc.Y -= Height-Margin.Top+Margin.Bottom;
Location = loc;
};
}
private void control_MouseEnter(object sender, EventArgs e){
Visible = true;
}
private void control_MouseLeave(object sender, EventArgs e){
Visible = false;
}
}
}
|
Fix tax rule to be double not int | // Licensed under the GPL License, Version 3.0. See LICENSE in the git repository root for license information.
using Newtonsoft.Json;
namespace Ecwid.Models
{
/// <summary>
/// </summary>
public class TaxRule
{
/// <summary>
/// Gets or sets the tax in %.
/// </summary>
/// <value>
/// The tax.
/// </value>
[JsonProperty("tax")]
public int Tax { get; set; }
/// <summary>
/// Gets or sets the destination zone identifier.
/// </summary>
/// <value>
/// The zone identifier.
/// </value>
[JsonProperty("zoneId")]
public string ZoneId { get; set; }
}
} | // Licensed under the GPL License, Version 3.0. See LICENSE in the git repository root for license information.
using Newtonsoft.Json;
namespace Ecwid.Models
{
/// <summary>
/// </summary>
public class TaxRule
{
/// <summary>
/// Gets or sets the tax in %.
/// </summary>
/// <value>
/// The tax.
/// </value>
[JsonProperty("tax")]
public double Tax { get; set; }
/// <summary>
/// Gets or sets the destination zone identifier.
/// </summary>
/// <value>
/// The zone identifier.
/// </value>
[JsonProperty("zoneId")]
public string ZoneId { get; set; }
}
} |
Add PostgresException on postgresExceptionNames fixing select for NoWait locking exceptions | using System;
using System.Data;
using System.Data.Common;
namespace Rebus.AdoNet.Dialects
{
public class PostgreSql82Dialect : PostgreSqlDialect
{
protected override Version MinimumDatabaseVersion => new Version("8.2");
public override ushort Priority => 82;
public override bool SupportsReturningClause => true;
public override bool SupportsSelectForWithNoWait => true;
public override string SelectForNoWaitClause => "NOWAIT";
public override bool IsSelectForNoWaitLockingException(DbException ex)
{
if (ex != null && ex.GetType().Name == "NpgsqlException")
{
var psqlex = new PostgreSqlExceptionAdapter(ex);
return psqlex.Code == "55P03";
}
return false;
}
}
}
| using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
namespace Rebus.AdoNet.Dialects
{
public class PostgreSql82Dialect : PostgreSqlDialect
{
private static readonly IEnumerable<string> _postgresExceptionNames = new[] { "NpgsqlException", "PostgresException" };
protected override Version MinimumDatabaseVersion => new Version("8.2");
public override ushort Priority => 82;
public override bool SupportsReturningClause => true;
public override bool SupportsSelectForWithNoWait => true;
public override string SelectForNoWaitClause => "NOWAIT";
public override bool IsSelectForNoWaitLockingException(DbException ex)
{
if (ex != null && _postgresExceptionNames.Contains(ex.GetType().Name))
{
var psqlex = new PostgreSqlExceptionAdapter(ex);
return psqlex.Code == "55P03";
}
return false;
}
}
}
|
Add preprocessor to prevent compilation error | using UnityEditor;
using UnityEngine;
namespace Tactosy.Unity
{
[CustomEditor(typeof(Manager_Tactosy))]
public class TactosyEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Manager_Tactosy tactosyManager = (Manager_Tactosy) target;
foreach (var mappings in tactosyManager.FeedbackMappings)
{
var key = mappings.Key;
if (GUILayout.Button(key))
{
tactosyManager.Play(key);
}
}
if (GUILayout.Button("Turn Off"))
{
tactosyManager.TurnOff();
}
}
}
}
| #if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace Tactosy.Unity
{
#if UNITY_EDITOR
[CustomEditor(typeof(Manager_Tactosy))]
public class TactosyEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Manager_Tactosy tactosyManager = (Manager_Tactosy) target;
foreach (var mappings in tactosyManager.FeedbackMappings)
{
var key = mappings.Key;
if (GUILayout.Button(key))
{
tactosyManager.Play(key);
}
}
if (GUILayout.Button("Turn Off"))
{
tactosyManager.TurnOff();
}
}
}
#endif
}
|
Add registration options for signaturehelp request | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class SignatureHelpRequest
{
public static readonly
RequestType<TextDocumentPositionParams, SignatureHelp, object, object> Type =
RequestType<TextDocumentPositionParams, SignatureHelp, object, object>.Create("textDocument/signatureHelp");
}
public class ParameterInformation
{
public string Label { get; set; }
public string Documentation { get; set; }
}
public class SignatureInformation
{
public string Label { get; set; }
public string Documentation { get; set; }
public ParameterInformation[] Parameters { get; set; }
}
public class SignatureHelp
{
public SignatureInformation[] Signatures { get; set; }
public int? ActiveSignature { get; set; }
public int? ActiveParameter { get; set; }
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class SignatureHelpRequest
{
public static readonly
RequestType<TextDocumentPositionParams, SignatureHelp, object, SignatureHelpRegistrationOptions> Type =
RequestType<TextDocumentPositionParams, SignatureHelp, object, SignatureHelpRegistrationOptions>.Create("textDocument/signatureHelp");
}
public class SignatureHelpRegistrationOptions : TextDocumentRegistrationOptions
{
// We duplicate the properties of SignatureHelpOptions class here because
// we cannot derive from two classes. One way to get around this situation
// is to use define SignatureHelpOptions as an interface instead of a class.
public string[] TriggerCharacters { get; set; }
}
public class ParameterInformation
{
public string Label { get; set; }
public string Documentation { get; set; }
}
public class SignatureInformation
{
public string Label { get; set; }
public string Documentation { get; set; }
public ParameterInformation[] Parameters { get; set; }
}
public class SignatureHelp
{
public SignatureInformation[] Signatures { get; set; }
public int? ActiveSignature { get; set; }
public int? ActiveParameter { get; set; }
}
}
|
Add another mapping test, non-auto inc Pk | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Biggy.SqlCe.Tests {
[Trait("SQL CE Compact column mapping", "")]
public class SqlCEColumnMapping {
public string _connectionStringName = "chinook";
[Fact(DisplayName = "Maps Pk if specified by attribute")]
public void MapingSpecifiedPk() {
var db = new SqlCeStore<Album>(_connectionStringName); //, "Album"
var pkMap = db.TableMapping.PrimaryKeyMapping;
Assert.Single(pkMap);
Assert.Equal("Id", pkMap[0].PropertyName);
Assert.Equal("AlbumId", pkMap[0].ColumnName);
Assert.True(pkMap[0].IsAutoIncementing);
}
[Fact(DisplayName = "Maps Pk even if wasn't specified by attribute")]
public void MapingNotSpecifiedPk() {
var db = new SqlCeStore<Genre>(_connectionStringName); //, "Genre"
var pkMap = db.TableMapping.PrimaryKeyMapping;
Assert.Single(pkMap);
Assert.Equal("Id", pkMap[0].PropertyName);
Assert.Equal("GenreId", pkMap[0].ColumnName);
Assert.True(pkMap[0].IsAutoIncementing);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Biggy.SqlCe.Tests {
[Trait("SQL CE Compact column mapping", "")]
public class SqlCEColumnMapping {
public string _connectionStringName = "chinook";
[Fact(DisplayName = "Maps Pk if specified by attribute")]
public void MapingSpecifiedPk() {
var db = new SqlCeStore<Album>(_connectionStringName); //, "Album"
var pkMap = db.TableMapping.PrimaryKeyMapping;
Assert.Single(pkMap);
Assert.Equal("Id", pkMap[0].PropertyName);
Assert.Equal("AlbumId", pkMap[0].ColumnName);
Assert.True(pkMap[0].IsAutoIncementing);
}
[Fact(DisplayName = "Maps Pk even if wasn't specified by attribute")]
public void MapingNotSpecifiedPk() {
var db = new SqlCeStore<Genre>(_connectionStringName); //, "Genre"
var pkMap = db.TableMapping.PrimaryKeyMapping;
Assert.Single(pkMap);
Assert.Equal("Id", pkMap[0].PropertyName);
Assert.Equal("GenreId", pkMap[0].ColumnName);
Assert.True(pkMap[0].IsAutoIncementing);
}
[Fact(DisplayName = "Properly maps Pk when is not auto incrementing")]
public void MapingNotAutoIncPk()
{
var db = new SqlCeDocumentStore<MonkeyDocument>(_connectionStringName);
var pkMap = db.TableMapping.PrimaryKeyMapping;
Assert.Single(pkMap);
Assert.Equal("Name", pkMap[0].PropertyName);
Assert.Equal("Name", pkMap[0].ColumnName);
Assert.Equal(typeof(string), pkMap[0].DataType);
Assert.False(pkMap[0].IsAutoIncementing);
}
}
}
|
Disable 2 s/r tests that demonstrate known chorus problems | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Bloom.Publish;
using BloomTemp;
using Chorus.VcsDrivers.Mercurial;
using LibChorus.TestUtilities;
using NUnit.Framework;
using Palaso.IO;
using Palaso.Progress.LogBox;
namespace BloomTests
{
[TestFixture]
public class SendReceiveTests
{
[Test]
public void CreateOrLocate_FolderHasAccentedLetter_FindsIt()
{
using (var setup = new RepositorySetup("Abé Books"))
{
Assert.NotNull(HgRepository.CreateOrLocate(setup.Repository.PathToRepo, new ConsoleProgress()));
}
}
[Test]
public void CreateOrLocate_FolderHasAccentedLetter2_FindsIt()
{
using (var testRoot = new TemporaryFolder("bloom sr test"))
{
string path = Path.Combine(testRoot.FolderPath, "Abé Books");
Directory.CreateDirectory(path);
Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress()));
Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress()));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Bloom.Publish;
using BloomTemp;
using Chorus.VcsDrivers.Mercurial;
using LibChorus.TestUtilities;
using NUnit.Framework;
using Palaso.IO;
using Palaso.Progress.LogBox;
namespace BloomTests
{
[TestFixture]
public class SendReceiveTests
{
[Test, Ignore("not yet")]
public void CreateOrLocate_FolderHasAccentedLetter_FindsIt()
{
using (var setup = new RepositorySetup("Abé Books"))
{
Assert.NotNull(HgRepository.CreateOrLocate(setup.Repository.PathToRepo, new ConsoleProgress()));
}
}
[Test, Ignore("not yet")]
public void CreateOrLocate_FolderHasAccentedLetter2_FindsIt()
{
using (var testRoot = new TemporaryFolder("bloom sr test"))
{
string path = Path.Combine(testRoot.FolderPath, "Abé Books");
Directory.CreateDirectory(path);
Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress()));
Assert.NotNull(HgRepository.CreateOrLocate(path, new ConsoleProgress()));
}
}
}
}
|
Fix reset ball ui for local and multiplayer | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ResetBallUI : NetworkBehaviour {
private void OnGUI()
{
GUILayout.BeginArea(new Rect(Screen.width - 150, 10, 140, 40));
if (GUILayout.Button("Reset Ball Position"))
{
CmdResetBallPosition();
}
GUILayout.EndArea();
}
[Command]
private void CmdResetBallPosition()
{
var ball = GameObject.FindGameObjectWithTag("Ball");
if(ball != null)
{
ball.GetComponent<Ball>().ResetPosition();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
public class ResetBallUI : NetworkBehaviour {
// Message handle for the client id message
private short RESPAWN_MESSAGE = 1003;
void OnServerStart()
{
NetworkServer.RegisterHandler(RESPAWN_MESSAGE, OnResetBallPosition);
}
private void OnGUI()
{
GUILayout.BeginArea(new Rect(Screen.width - 150, 10, 140, 40));
if (GUILayout.Button("Reset Ball Position"))
{
ResetBallPosition();
}
GUILayout.EndArea();
}
[Server]
private void OnResetBallPosition(NetworkMessage netMsg)
{
ResetBallPosition();
}
private void ResetBallPosition()
{
if (NetworkServer.connections.Count > 0 || !NetworkManager.singleton.isNetworkActive)
{
// If local or the server reset the ball position
var ball = GameObject.FindGameObjectWithTag("Ball");
if(ball != null)
{
ball.GetComponent<Ball>().ResetPosition();
}
}
else
{
// Send an empty message of type respawn message
NetworkManager.singleton.client.connection.Send(RESPAWN_MESSAGE, new EmptyMessage());
}
}
}
|
Change still image capture parameters. | using System;
using System.Timers;
using Shell.Execute;
namespace PiDashcam
{
public class StillCam
{
Timer timer;
int imgcounter;
public StillCam()
{
timer = new Timer(10000);
timer.Elapsed += Timer_Elapsed;
timer.Start();
imgcounter = 1;
}
public void Stop()
{
timer.Stop();
}
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
ProgramLauncher.Execute("raspistill", String.Format("-o {0}.jpg",imgcounter++));
}
}
}
| using System;
using System.Timers;
using Shell.Execute;
namespace PiDashcam
{
public class StillCam
{
Timer timer;
int imgcounter;
public StillCam()
{
timer = new Timer(6000);
timer.Elapsed += Timer_Elapsed;
timer.Start();
imgcounter = 1;
}
public void Stop()
{
timer.Stop();
}
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
ProgramLauncher.Execute("raspistill", String.Format("-h 1920 -v 1080 -n -o {0}.jpg",imgcounter++));
}
}
}
|
Tweak tests to reflect new interface for log timing | using CertiPay.Common.Logging;
using NUnit.Framework;
using System;
using System.Threading;
namespace CertiPay.Common.Tests.Logging
{
public class MetricLoggingExtensionsTests
{
private static readonly ILog Log = LogManager.GetLogger<MetricLoggingExtensionsTests>();
[Test]
public void Use_Log_Timer_No_Identifier()
{
using (Log.Timer("Use_Log_Timer"))
{
// Cool stuff happens here
}
}
[Test]
public void Use_Log_Timer_With_Debug()
{
using (Log.Timer("Use_Log_Timer_With_Debug", level: LogLevel.Debug))
{
// Debug tracking happens here
}
}
[Test]
public void Takes_Longer_Than_Threshold()
{
using (Log.Timer("Takes_Longer_Than_Threshold", warnIfExceeds: TimeSpan.FromMilliseconds(100)))
{
Thread.Sleep(TimeSpan.FromMilliseconds(150));
}
}
[Test]
public void Object_Context_Provided()
{
using (Log.Timer("Object_Context_Provided", new { id = 10, userId = 12 }))
{
// Cool stuff happens here
}
}
}
} | using CertiPay.Common.Logging;
using NUnit.Framework;
using System;
using System.Threading;
namespace CertiPay.Common.Tests.Logging
{
public class MetricLoggingExtensionsTests
{
private static readonly ILog Log = LogManager.GetLogger<MetricLoggingExtensionsTests>();
[Test]
public void Use_Log_Timer_No_Identifier()
{
using (Log.Timer("Use_Log_Timer"))
{
// Cool stuff happens here
}
}
[Test]
public void Takes_Longer_Than_Threshold()
{
using (Log.Timer("Takes_Longer_Than_Threshold", warnIfExceeds: TimeSpan.FromMilliseconds(100)))
{
Thread.Sleep(TimeSpan.FromMilliseconds(150));
}
}
[Test]
public void Object_Context_Provided()
{
using (Log.Timer("Object_Context_Provided {id} {userId}", new { id = 10, userId = 12 }))
{
// Cool stuff happens here
}
}
}
} |
Set targetGameObject = null on ReturnToHive state exit as this target was overriding the target position when the boids switched back to exploring | using UnityEngine;
public class ReturnToHiveState : State
{
Arrive arrive;
public ReturnToHiveState(GameObject gameObject) : base(gameObject)
{
this.gameObject = gameObject;
}
public override void Enter()
{
arrive = gameObject.GetComponent<Arrive>();
arrive.targetGameObject = gameObject.transform.parent.gameObject;
}
public override void Exit()
{
}
public override void Update()
{
if (Vector3.Distance(gameObject.transform.position, gameObject.transform.parent.transform.position) < 1.0f)
{
gameObject.transform.parent.GetComponent<BeeSpawner>().pollenCount += gameObject.GetComponent<Bee>().collectedPollen;
gameObject.GetComponent<Bee>().collectedPollen = 0.0f;
gameObject.GetComponent<StateMachine>().SwitchState(new ExploreState(gameObject));
}
}
}
| using UnityEngine;
public class ReturnToHiveState : State
{
Arrive arrive;
public ReturnToHiveState(GameObject gameObject) : base(gameObject)
{
this.gameObject = gameObject;
}
public override void Enter()
{
arrive = gameObject.GetComponent<Arrive>();
arrive.targetGameObject = gameObject.transform.parent.gameObject;
}
public override void Exit()
{
arrive.targetGameObject = null;
}
public override void Update()
{
if (Vector3.Distance(gameObject.transform.position, gameObject.transform.parent.transform.position) < 1.0f)
{
gameObject.transform.parent.GetComponent<BeeSpawner>().pollenCount += gameObject.GetComponent<Bee>().collectedPollen;
gameObject.GetComponent<Bee>().collectedPollen = 0.0f;
gameObject.GetComponent<StateMachine>().SwitchState(new ExploreState(gameObject));
}
}
}
|
Tidy up error handling in WriteExpression | namespace Veil.Compiler
{
internal partial class VeilTemplateCompiler
{
private static void EmitWriteExpression<T>(VeilCompilerState<T> state, SyntaxTreeNode.WriteExpressionNode node)
{
state.Emitter.LoadWriterToStack();
state.PushExpressionScopeOnStack(node.Expression);
state.Emitter.LoadExpressionFromCurrentModelOnStack(node.Expression);
if (node.HtmlEncode && node.Expression.ResultType == typeof(string))
{
var method = typeof(Helpers).GetMethod("HtmlEncode");
state.Emitter.Call(method);
}
else
{
state.Emitter.CallWriteFor(node.Expression.ResultType);
}
}
}
} | using System.Reflection;
namespace Veil.Compiler
{
internal partial class VeilTemplateCompiler
{
private static MethodInfo htmlEncodeMethod = typeof(Helpers).GetMethod("HtmlEncode");
private static void EmitWriteExpression<T>(VeilCompilerState<T> state, SyntaxTreeNode.WriteExpressionNode node)
{
state.Emitter.LoadWriterToStack();
state.PushExpressionScopeOnStack(node.Expression);
state.Emitter.LoadExpressionFromCurrentModelOnStack(node.Expression);
if (node.HtmlEncode)
{
if (node.Expression.ResultType != typeof(string)) throw new VeilCompilerException("Tried to HtmlEncode an expression that does not evaluate to a string");
state.Emitter.Call(htmlEncodeMethod);
}
else
{
state.Emitter.CallWriteFor(node.Expression.ResultType);
}
}
}
} |
Add short term caching to sandbox html response to avoid repeated download by the browser. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Witness.Controllers
{
public class SandboxController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Witness.Controllers
{
public class SandboxController : Controller
{
public ActionResult Index()
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(1));
return View();
}
}
}
|
Make the generic type self-documenting. | namespace Sep.Git.Tfs.Core.TfsInterop
{
public class WrapperFor<T>
{
private readonly T _wrapped;
public WrapperFor(T wrapped)
{
_wrapped = wrapped;
}
public T Unwrap()
{
return _wrapped;
}
public static T Unwrap(object wrapper)
{
return ((WrapperFor<T>)wrapper).Unwrap();
}
}
}
| namespace Sep.Git.Tfs.Core.TfsInterop
{
public class WrapperFor<TFS_TYPE>
{
private readonly TFS_TYPE _wrapped;
public WrapperFor(TFS_TYPE wrapped)
{
_wrapped = wrapped;
}
public TFS_TYPE Unwrap()
{
return _wrapped;
}
public static TFS_TYPE Unwrap(object wrapper)
{
return ((WrapperFor<TFS_TYPE>)wrapper).Unwrap();
}
}
}
|
Disable logging for shutdown of dotnet process by default | // Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Execution;
using Nuke.Common.Tools.DotNet;
namespace Nuke.Common.CI
{
[PublicAPI]
[AttributeUsage(AttributeTargets.Class)]
public class ShutdownDotNetBuildServerOnFinish : Attribute, IOnBuildFinished
{
public void OnBuildFinished(NukeBuild build)
{
// Note https://github.com/dotnet/cli/issues/11424
DotNetTasks.DotNet("build-server shutdown");
}
}
}
| // Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Execution;
using Nuke.Common.Tools.DotNet;
namespace Nuke.Common.CI
{
[PublicAPI]
[AttributeUsage(AttributeTargets.Class)]
public class ShutdownDotNetBuildServerOnFinish : Attribute, IOnBuildFinished
{
public bool EnableLogging { get; set; }
public void OnBuildFinished(NukeBuild build)
{
// Note https://github.com/dotnet/cli/issues/11424
DotNetTasks.DotNet("build-server shutdown", logInvocation: EnableLogging, logOutput: EnableLogging);
}
}
}
|
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.NHibernate 3.0.0")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.NHibernate 3.0.0")]
|
Set only Razor view Engine | namespace WarehouseSystem.Web
{
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WarehouseSystem.Web.App_Start;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DbConfig.Initialize();
AutoMapperConfig.Execute();
}
}
}
| namespace WarehouseSystem.Web
{
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WarehouseSystem.Web.App_Start;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DbConfig.Initialize();
AutoMapperConfig.Execute();
}
}
}
|
Make numeric_resolution on date mapping nullable | using System.Collections.Generic;
using Newtonsoft.Json;
using System;
using Newtonsoft.Json.Converters;
namespace Nest
{
[JsonObject(MemberSerialization.OptIn)]
public class DateMapping : MultiFieldMapping, IElasticType, IElasticCoreType
{
public DateMapping():base("date")
{
}
/// <summary>
/// The name of the field that will be stored in the index. Defaults to the property/field name.
/// </summary>
[JsonProperty("index_name")]
public string IndexName { get; set; }
[JsonProperty("store")]
public bool? Store { get; set; }
[JsonProperty("index"), JsonConverter(typeof(StringEnumConverter))]
public NonStringIndexOption? Index { get; set; }
[JsonProperty("format")]
public string Format { get; set; }
[JsonProperty("precision_step")]
public int? PrecisionStep { get; set; }
[JsonProperty("boost")]
public double? Boost { get; set; }
[JsonProperty("null_value")]
public DateTime? NullValue { get; set; }
[JsonProperty("ignore_malformed")]
public bool? IgnoreMalformed { get; set; }
[JsonProperty("doc_values")]
public bool? DocValues { get; set; }
[JsonProperty("numeric_resolution")]
public NumericResolutionUnit NumericResolution { get; set; }
}
} | using System.Collections.Generic;
using Newtonsoft.Json;
using System;
using Newtonsoft.Json.Converters;
namespace Nest
{
[JsonObject(MemberSerialization.OptIn)]
public class DateMapping : MultiFieldMapping, IElasticType, IElasticCoreType
{
public DateMapping():base("date")
{
}
/// <summary>
/// The name of the field that will be stored in the index. Defaults to the property/field name.
/// </summary>
[JsonProperty("index_name")]
public string IndexName { get; set; }
[JsonProperty("store")]
public bool? Store { get; set; }
[JsonProperty("index"), JsonConverter(typeof(StringEnumConverter))]
public NonStringIndexOption? Index { get; set; }
[JsonProperty("format")]
public string Format { get; set; }
[JsonProperty("precision_step")]
public int? PrecisionStep { get; set; }
[JsonProperty("boost")]
public double? Boost { get; set; }
[JsonProperty("null_value")]
public DateTime? NullValue { get; set; }
[JsonProperty("ignore_malformed")]
public bool? IgnoreMalformed { get; set; }
[JsonProperty("doc_values")]
public bool? DocValues { get; set; }
[JsonProperty("numeric_resolution")]
public NumericResolutionUnit? NumericResolution { get; set; }
}
} |
Remove nested div to fix style issue | @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel
<div class="das-panel das-panel--featured">
@if (Model.ReservedFundingToShow != null)
{
<h3 class="das-panel__heading">Apprenticeship funding secured</h3>
<dl class="das-definition-list das-definition-list--with-separator">
<dt class="das-definition-list__title">Legal entity:</dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd>
<dt class="das-definition-list__title">Training course:</dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd>
<dt class="das-definition-list__title">Start and end date: </dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd>
</dl>
}
@if (Model.RecentlyAddedReservationId != null &&
Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId)
{
<p>We're dealing with your request for funding, please check back later.</p>
}
<p><a href="@Url.ReservationsAction("reservations")" class="das-panel__link">Check and secure funding now</a> </p>
</div> | @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel
@if (Model.ReservedFundingToShow != null)
{
<h3 class="das-panel__heading">Apprenticeship funding secured</h3>
<dl class="das-definition-list das-definition-list--with-separator">
<dt class="das-definition-list__title">Legal entity:</dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShowLegalEntityName</dd>
<dt class="das-definition-list__title">Training course:</dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShow.CourseName</dd>
<dt class="das-definition-list__title">Start and end date: </dt>
<dd class="das-definition-list__definition">@Model.ReservedFundingToShow.StartDate.ToString("MMMM yyyy") to @Model.ReservedFundingToShow.EndDate.ToString("MMMM yyyy")</dd>
</dl>
}
@if (Model.RecentlyAddedReservationId != null &&
Model.ReservedFundingToShow?.ReservationId != Model.RecentlyAddedReservationId)
{
<p>We're dealing with your request for funding, please check back later.</p>
}
<p><a href="@Url.ReservationsAction("reservations")" class="das-panel__link">Check and secure funding now</a> </p> |
Add basic GET & POST methods into the MatchServices. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
namespace DailySoccerAppService.Controllers
{
public class MatchesController : ApiController
{
public ApiServices Services { get; set; }
[HttpGet]
public GetMatchesRespond GetMatches(GetMatchesRequest request)
{
var now = DateTime.Now;
var matches = new List<MatchInformation>
{
new MatchInformation
{
Id = 1,
BeginDate = now,
LeagueName = "Premier League",
TeamHome = new TeamInformation
{
Id = 1,
Name = "FC Astana",
CurrentScore = 1,
CurrentPredictionPoints = 7,
WinningPredictionPoints = 5
},
TeamAway = new TeamInformation
{
Id = 2,
Name = "Atletico Madrid",
CurrentScore = 0,
CurrentPredictionPoints = 3,
},
},
};
return new GetMatchesRespond
{
CurrentDate = now,
AccountInfo = new AccountInformation
{
Points = 255,
RemainingGuessAmount = 5,
CurrentOrderedCoupon = 15
},
Matches = matches
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
namespace DailySoccerAppService.Controllers
{
public class MatchesController : ApiController
{
public ApiServices Services { get; set; }
// GET: api/Matches
[HttpGet]
public string Get()
{
return "Respond by GET method";
}
[HttpPost]
public string Post(int id)
{
return "Respond by POST method, your ID: " + id;
}
[HttpPost]
public GetMatchesRespond GetMatches(GetMatchesRequest request)
{
var now = DateTime.Now;
var matches = new List<MatchInformation>
{
new MatchInformation
{
Id = 1,
BeginDate = now,
LeagueName = "Premier League",
TeamHome = new TeamInformation
{
Id = 1,
Name = "FC Astana",
CurrentScore = 1,
CurrentPredictionPoints = 7,
WinningPredictionPoints = 5
},
TeamAway = new TeamInformation
{
Id = 2,
Name = "Atletico Madrid",
CurrentScore = 0,
CurrentPredictionPoints = 3,
},
},
};
return new GetMatchesRespond
{
CurrentDate = now,
AccountInfo = new AccountInformation
{
Points = 255,
RemainingGuessAmount = 5,
CurrentOrderedCoupon = 15
},
Matches = matches
};
}
}
}
|
Fix bug where Smaller wouldn't exit properly | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Threading;
namespace Smaller
{
public class RunJobController
{
private static readonly EventWaitHandle _showSignal = new EventWaitHandle(false, EventResetMode.AutoReset, "Smaller.ShowSignal");
public void TriggerRunJobs()
{
_showSignal.Set();
}
private RunJobController()
{
StartListenForJobs();
}
private static readonly RunJobController _instance = new RunJobController();
public static RunJobController Instance
{
get { return _instance; }
}
private void RunJobs()
{
Action x = () =>
{
//if (Application.Current.MainWindow == null)
//{
// Application.Current.MainWindow = new MainWindow();
// Application.Current.MainWindow.Show();
//}
new JobRunner().Run();
};
Application.Current.Dispatcher.Invoke(x, DispatcherPriority.Send);
}
private void StartListenForJobs()
{
new Thread(() =>
{
while (true)
{
_showSignal.WaitOne();
RunJobs();
}
}).Start();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Threading;
namespace Smaller
{
public class RunJobController
{
private static readonly EventWaitHandle _showSignal = new EventWaitHandle(false, EventResetMode.AutoReset, "Smaller.ShowSignal");
public void TriggerRunJobs()
{
_showSignal.Set();
}
private RunJobController()
{
StartListenForJobs();
}
private static readonly RunJobController _instance = new RunJobController();
public static RunJobController Instance
{
get { return _instance; }
}
private void RunJobs()
{
Action x = () =>
{
//if (Application.Current.MainWindow == null)
//{
// Application.Current.MainWindow = new MainWindow();
// Application.Current.MainWindow.Show();
//}
new JobRunner().Run();
};
Application.Current.Dispatcher.Invoke(x, DispatcherPriority.Send);
}
private void StartListenForJobs()
{
new Thread(() =>
{
// only wait for signals while the app is running
while (Application.Current != null)
{
if (_showSignal.WaitOne(500))
{
RunJobs();
}
}
}).Start();
}
}
}
|
Fix path to local key file | using System;
using System.IO;
namespace Cake.AppVeyor.Tests
{
public static class Keys
{
const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}";
static string appVeyorApiToken;
public static string AppVeyorApiToken {
get
{
if (appVeyorApiToken == null)
{
// Check for a local file with a token first
var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", ".appveyorapitoken");
if (File.Exists(localFile))
appVeyorApiToken = File.ReadAllText(localFile);
// Next check for an environment variable
if (string.IsNullOrEmpty(appVeyorApiToken))
appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token");
// Finally use the const value
if (string.IsNullOrEmpty(appVeyorApiToken))
appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN;
}
return appVeyorApiToken;
}
}
}
}
| using System;
using System.IO;
namespace Cake.AppVeyor.Tests
{
public static class Keys
{
const string YOUR_APPVEYOR_API_TOKEN = "{APPVEYOR_APITOKEN}";
static string appVeyorApiToken;
public static string AppVeyorApiToken {
get
{
if (appVeyorApiToken == null)
{
// Check for a local file with a token first
var localFile = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", ".appveyorapitoken");
if (File.Exists(localFile))
appVeyorApiToken = File.ReadAllText(localFile);
// Next check for an environment variable
if (string.IsNullOrEmpty(appVeyorApiToken))
appVeyorApiToken = Environment.GetEnvironmentVariable("appveyor_api_token");
// Finally use the const value
if (string.IsNullOrEmpty(appVeyorApiToken))
appVeyorApiToken = YOUR_APPVEYOR_API_TOKEN;
}
return appVeyorApiToken;
}
}
}
}
|
Add a test with a specific writer. | using System;
using NUnit.Framework;
using FbxSharp;
namespace FbxSharpTests
{
[TestFixture]
public class ObjectPrinterTest
{
[Test]
public void QuoteQuotesAndEscapeStrings()
{
Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz"));
Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789"));
Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-="));
// Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\"));
// Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\""));
Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?"));
Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r"));
Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n"));
Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t"));
}
}
}
| using System;
using NUnit.Framework;
using FbxSharp;
using System.IO;
namespace FbxSharpTests
{
[TestFixture]
public class ObjectPrinterTest
{
[Test]
public void QuoteQuotesAndEscapeStrings()
{
Assert.AreEqual("\"abcdefghijklmnopqrstuvwxyz\"", ObjectPrinter.quote("abcdefghijklmnopqrstuvwxyz"));
Assert.AreEqual("\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"", ObjectPrinter.quote("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.AreEqual("\"0123456789\"", ObjectPrinter.quote("0123456789"));
Assert.AreEqual("\"`~!@#$%^&*()_+-=\"", ObjectPrinter.quote("`~!@#$%^&*()_+-="));
// Assert.AreEqual("\"\\\\\"", ObjectPrinter.quote("\\"));
// Assert.AreEqual("\"\\\"\"", ObjectPrinter.quote("\""));
Assert.AreEqual("\"[]{}|;:',<.>/?\"", ObjectPrinter.quote("[]{}|;:',<.>/?"));
Assert.AreEqual("\"\\r\"", ObjectPrinter.quote("\r"));
Assert.AreEqual("\"\\n\"", ObjectPrinter.quote("\n"));
Assert.AreEqual("\"\\t\"", ObjectPrinter.quote("\t"));
}
[Test]
public void PrintPropertyPrintsTheProperty()
{
// given
var prop = new PropertyT<double>("something");
var printer = new ObjectPrinter();
var writer = new StringWriter();
var expected =
@" Name = something
Type = Double (MonoType)
Value = 0
SrcObjectCount = 0
DstObjectCount = 0
";
// when
printer.PrintProperty(prop, writer);
// then
Assert.AreEqual(expected, writer.ToString());
}
}
}
|
Revert "Bump WebApi version to 5.10.3" | using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.10.2.0")]
[assembly: AssemblyFileVersion("5.10.2.0")]
| using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.10.1.0")]
[assembly: AssemblyFileVersion("5.10.1.0")]
|
Fix a forest crash in ZZT. | using System;
using Roton.Emulation.Core;
using Roton.Emulation.Data;
using Roton.Emulation.Data.Impl;
using Roton.Infrastructure.Impl;
namespace Roton.Emulation.Interactions.Impl
{
[Context(Context.Original, 0x14)]
[Context(Context.Super, 0x14)]
public sealed class ForestInteraction : IInteraction
{
private readonly Lazy<IEngine> _engine;
private IEngine Engine => _engine.Value;
public ForestInteraction(Lazy<IEngine> engine)
{
_engine = engine;
}
public void Interact(IXyPair location, int index, IXyPair vector)
{
Engine.ClearForest(location);
Engine.UpdateBoard(location);
var forestIndex = Engine.State.ForestIndex;
var forestSongLength = Engine.Sounds.Forest.Length;
Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength;
Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2);
if (!Engine.Alerts.Forest)
return;
Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage);
Engine.Alerts.Forest = false;
}
}
} | using System;
using Roton.Emulation.Core;
using Roton.Emulation.Data;
using Roton.Emulation.Data.Impl;
using Roton.Infrastructure.Impl;
namespace Roton.Emulation.Interactions.Impl
{
[Context(Context.Original, 0x14)]
[Context(Context.Super, 0x14)]
public sealed class ForestInteraction : IInteraction
{
private readonly Lazy<IEngine> _engine;
private IEngine Engine => _engine.Value;
public ForestInteraction(Lazy<IEngine> engine)
{
_engine = engine;
}
public void Interact(IXyPair location, int index, IXyPair vector)
{
Engine.ClearForest(location);
Engine.UpdateBoard(location);
var forestSongLength = Engine.Sounds.Forest.Length;
var forestIndex = Engine.State.ForestIndex % forestSongLength;
Engine.State.ForestIndex = (forestIndex + 2) % forestSongLength;
Engine.PlaySound(3, Engine.Sounds.Forest, forestIndex, 2);
if (!Engine.Alerts.Forest)
return;
Engine.SetMessage(0xC8, Engine.Alerts.ForestMessage);
Engine.Alerts.Forest = false;
}
}
} |
Enable configuration of Json Serializer | //-------------------------------------------------------------------------------
// <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG">
// Copyright (c) MMS AG, 2008-2015
// </copyright>
//-------------------------------------------------------------------------------
namespace MMS.ServiceBus.Pipeline
{
using System;
using System.IO;
using Newtonsoft.Json;
public class NewtonsoftJsonMessageSerializer : IMessageSerializer
{
public string ContentType
{
get
{
return "application/json";
}
}
public void Serialize(object message, Stream body)
{
var streamWriter = new StreamWriter(body);
var writer = new JsonTextWriter(streamWriter);
var serializer = new JsonSerializer();
serializer.Serialize(writer, message);
streamWriter.Flush();
body.Flush();
body.Position = 0;
}
public object Deserialize(Stream body, Type messageType)
{
var streamReader = new StreamReader(body);
var reader = new JsonTextReader(streamReader);
var serializer = new JsonSerializer();
return serializer.Deserialize(reader, messageType);
}
}
} | //-------------------------------------------------------------------------------
// <copyright file="NewtonsoftJsonMessageSerializer.cs" company="MMS AG">
// Copyright (c) MMS AG, 2008-2015
// </copyright>
//-------------------------------------------------------------------------------
namespace MMS.ServiceBus.Pipeline
{
using System;
using System.IO;
using Newtonsoft.Json;
public class NewtonsoftJsonMessageSerializer : IMessageSerializer
{
private readonly Func<JsonSerializerSettings> settings;
public NewtonsoftJsonMessageSerializer() : this(() => null)
{
}
public NewtonsoftJsonMessageSerializer(Func<JsonSerializerSettings> settings)
{
this.settings = settings;
}
public string ContentType
{
get
{
return "application/json";
}
}
public void Serialize(object message, Stream body)
{
var streamWriter = new StreamWriter(body);
var writer = new JsonTextWriter(streamWriter);
var serializer = JsonSerializer.Create(this.settings());
serializer.Serialize(writer, message);
streamWriter.Flush();
body.Flush();
body.Position = 0;
}
public object Deserialize(Stream body, Type messageType)
{
var streamReader = new StreamReader(body);
var reader = new JsonTextReader(streamReader);
var serializer = JsonSerializer.Create(this.settings());
return serializer.Deserialize(reader, messageType);
}
}
} |
Allow context to be null when querying for initial data. | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContextExtensions.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the context extensions class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Data.InMemory
{
using System.Collections.Generic;
using Kephas.Data.Capabilities;
using Kephas.Diagnostics.Contracts;
using Kephas.Services;
/// <summary>
/// Extension methods for <see cref="IContext"/>.
/// </summary>
public static class ContextExtensions
{
/// <summary>
/// Gets the initial data.
/// </summary>
/// <param name="context">The context to act on.</param>
/// <returns>
/// An enumeration of entity information.
/// </returns>
public static IEnumerable<IEntityInfo> GetInitialData(this IContext context)
{
Requires.NotNull(context, nameof(context));
return context[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>;
}
/// <summary>
/// Sets the initial data.
/// </summary>
/// <param name="context">The context to act on.</param>
/// <param name="initialData">The initial data.</param>
public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData)
{
Requires.NotNull(context, nameof(context));
context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData;
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContextExtensions.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the context extensions class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Data.InMemory
{
using System.Collections.Generic;
using Kephas.Data.Capabilities;
using Kephas.Diagnostics.Contracts;
using Kephas.Services;
/// <summary>
/// Extension methods for <see cref="IContext"/>.
/// </summary>
public static class ContextExtensions
{
/// <summary>
/// Gets the initial data.
/// </summary>
/// <param name="context">The context to act on.</param>
/// <returns>
/// An enumeration of entity information.
/// </returns>
public static IEnumerable<IEntityInfo> GetInitialData(this IContext context)
{
return context?[nameof(InMemoryDataContextConfiguration.InitialData)] as IEnumerable<IEntityInfo>;
}
/// <summary>
/// Sets the initial data.
/// </summary>
/// <param name="context">The context to act on.</param>
/// <param name="initialData">The initial data.</param>
public static void SetInitialData(this IContext context, IEnumerable<IEntityInfo> initialData)
{
Requires.NotNull(context, nameof(context));
context[nameof(InMemoryDataContextConfiguration.InitialData)] = initialData;
}
}
} |
Change GetService call to GetRequiredService | // Copyright (c) Microsoft Open Technologies, Inc. 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.AspNet.Security.DataProtection.KeyManagement;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Security.DataProtection
{
public class DefaultDataProtectionProvider : IDataProtectionProvider
{
private readonly IDataProtectionProvider _innerProvider;
public DefaultDataProtectionProvider()
{
// use DI defaults
var collection = new ServiceCollection();
var defaultServices = DataProtectionServices.GetDefaultServices();
collection.Add(defaultServices);
var serviceProvider = collection.BuildServiceProvider();
_innerProvider = (IDataProtectionProvider)serviceProvider.GetService(typeof(IDataProtectionProvider));
CryptoUtil.Assert(_innerProvider != null, "_innerProvider != null");
}
public DefaultDataProtectionProvider(
[NotNull] IOptions<DataProtectionOptions> optionsAccessor,
[NotNull] IKeyManager keyManager)
{
KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager));
var options = optionsAccessor.Options;
_innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator))
? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator)
: rootProvider;
}
public IDataProtector CreateProtector([NotNull] string purpose)
{
return _innerProvider.CreateProtector(purpose);
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. 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.AspNet.Security.DataProtection.KeyManagement;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Security.DataProtection
{
public class DefaultDataProtectionProvider : IDataProtectionProvider
{
private readonly IDataProtectionProvider _innerProvider;
public DefaultDataProtectionProvider()
{
// use DI defaults
var collection = new ServiceCollection();
var defaultServices = DataProtectionServices.GetDefaultServices();
collection.Add(defaultServices);
var serviceProvider = collection.BuildServiceProvider();
_innerProvider = serviceProvider.GetRequiredService<IDataProtectionProvider>();
}
public DefaultDataProtectionProvider(
[NotNull] IOptions<DataProtectionOptions> optionsAccessor,
[NotNull] IKeyManager keyManager)
{
KeyRingBasedDataProtectionProvider rootProvider = new KeyRingBasedDataProtectionProvider(new KeyRingProvider(keyManager));
var options = optionsAccessor.Options;
_innerProvider = (!String.IsNullOrEmpty(options.ApplicationDiscriminator))
? (IDataProtectionProvider)rootProvider.CreateProtector(options.ApplicationDiscriminator)
: rootProvider;
}
public IDataProtector CreateProtector([NotNull] string purpose)
{
return _innerProvider.CreateProtector(purpose);
}
}
}
|
Remove name from assembly info; this looks silly on NuGet. | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")]
[assembly: AssemblyProduct("DanTup's DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")]
[assembly: AssemblyCompany("Danny Tuppeny")]
[assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")]
[assembly: AssemblyProduct("DartAnalysis.NET: A .NET wrapper around Google's Analysis Server for Dart.")]
[assembly: AssemblyCompany("Danny Tuppeny")]
[assembly: AssemblyCopyright("Copyright Danny Tuppeny © 2014")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.*")]
[assembly: InternalsVisibleTo("DanTup.DartAnalysis.Tests")]
|
Add some test tracing to Index action | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
string foo = ConfigurationManager.AppSettings["foo"];
ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo);
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now);
Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now);
Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now);
return View();
}
public ActionResult About()
{
string foo = ConfigurationManager.AppSettings["foo"];
ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo);
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} |
Support driver constructor standing parameter for season list request | using ErgastApi.Client.Attributes;
using ErgastApi.Responses;
namespace ErgastApi.Requests
{
public class SeasonListRequest : StandardRequest<SeasonResponse>
{
// Value not used
// ReSharper disable once UnassignedGetOnlyAutoProperty
[UrlTerminator, UrlSegment("seasons")]
protected object Seasons { get; }
}
} | using ErgastApi.Client.Attributes;
using ErgastApi.Responses;
namespace ErgastApi.Requests
{
public class SeasonListRequest : StandardRequest<SeasonResponse>
{
[UrlSegment("constructorStandings")]
public int? ConstructorStanding { get; set; }
[UrlSegment("driverStandings")]
public int? DriverStanding { get; set; }
// Value not used
// ReSharper disable once UnassignedGetOnlyAutoProperty
[UrlTerminator, UrlSegment("seasons")]
protected object Seasons { get; }
}
} |
Remove API route trailing slash to avoid AWS API Gateway modification | using System.Threading.Tasks;
using Sinch.ServerSdk.Callouts;
using Sinch.WebApiClient;
public interface ICalloutApiEndpoints
{
[HttpPost("calling/v1/callouts/")]
Task<CalloutResponse> Callout([ToBody] CalloutRequest request);
} | using System.Threading.Tasks;
using Sinch.ServerSdk.Callouts;
using Sinch.WebApiClient;
public interface ICalloutApiEndpoints
{
[HttpPost("calling/v1/callouts")]
Task<CalloutResponse> Callout([ToBody] CalloutRequest request);
} |
Add DebugBox for debugging issues in popup windows | namespace ImGui.Development
{
public class GUIDebug
{
public static void SetWindowPosition(string windowName, Point position)
{
var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName);
if (possibleWindow != null)
{
possibleWindow.Position = position;
}
}
}
} | using ImGui.Rendering;
namespace ImGui.Development
{
public class GUIDebug
{
public static void SetWindowPosition(string windowName, Point position)
{
var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName);
if (possibleWindow != null)
{
possibleWindow.Position = position;
}
}
}
}
namespace ImGui
{
public partial class GUI
{
public static void DebugBox(int id, Rect rect, Color color)
{
var window = GetCurrentWindow();
if (window.SkipItems)
return;
//get or create the root node
var container = window.AbsoluteVisualList;
var node = (Node)container.Find(visual => visual.Id == id);
if (node == null)
{
//create node
node = new Node(id, $"DebugBox<{id}>");
node.UseBoxModel = true;
node.RuleSet.Replace(GUISkin.Current[GUIControlName.Box]);
node.RuleSet.BackgroundColor = color;
container.Add(node);
}
node.ActiveSelf = true;
// last item state
window.TempData.LastItemState = node.State;
// rect
node.Rect = window.GetRect(rect);
using (var dc = node.RenderOpen())
{
dc.DrawBoxModel(node.RuleSet, node.Rect);
}
}
}
} |
Change legal entity to include the CompanyNumber, RegisteredAddress and DateOfIncorporation | namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account
{
public class LegalEntity
{
public long Id { get; set; }
public string Name { get; set; }
}
} | using System;
namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account
{
public class LegalEntity
{
public long Id { get; set; }
public string CompanyNumber { get; set; }
public string Name { get; set; }
public string RegisteredAddress { get; set; }
public DateTime DateOfIncorporation { get; set; }
}
} |
Set a more sensible default for the screen mode. | namespace Akiba.Core
{
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
internal class Configuration
{
public const string ConfigurationName = "configuration.yaml";
public enum ScreenModes : ushort
{
Windowed,
Fullscreen,
Borderless,
};
public ushort FramesPerSecond { get; private set; } = 60;
public ushort RenderingResolutionWidth { get; private set; } = 1920;
public ushort RenderingResolutionHeight { get; private set; } = 1080;
public ScreenModes ScreenMode { get; private set; } = ScreenModes.Fullscreen;
public bool VerticalSynchronization { get; private set; } = false;
public bool AntiAliasing { get; private set; } = false;
public bool HideCursor { get; private set; } = false;
public bool PreventSystemSleep { get; private set; } = true;
public bool DisableMovies { get; private set; } = false;
public Configuration Save()
{
var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamWriter = new StreamWriter(ConfigurationName))
{
serializer.Serialize(streamWriter, this);
}
return this;
}
public static Configuration LoadFromFile()
{
var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamReader = new StreamReader(ConfigurationName))
{
return deserializer.Deserialize<Configuration>(streamReader);
}
}
}
}
| namespace Akiba.Core
{
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
internal class Configuration
{
public const string ConfigurationName = "configuration.yaml";
public enum ScreenModes : ushort
{
Windowed,
Fullscreen,
Borderless,
};
public ushort FramesPerSecond { get; private set; } = 60;
public ushort RenderingResolutionWidth { get; private set; } = 1920;
public ushort RenderingResolutionHeight { get; private set; } = 1080;
public ScreenModes ScreenMode { get; private set; } = ScreenModes.Borderless;
public bool VerticalSynchronization { get; private set; } = false;
public bool AntiAliasing { get; private set; } = false;
public bool HideCursor { get; private set; } = false;
public bool PreventSystemSleep { get; private set; } = true;
public bool DisableMovies { get; private set; } = false;
public Configuration Save()
{
var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamWriter = new StreamWriter(ConfigurationName))
{
serializer.Serialize(streamWriter, this);
}
return this;
}
public static Configuration LoadFromFile()
{
var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamReader = new StreamReader(ConfigurationName))
{
return deserializer.Deserialize<Configuration>(streamReader);
}
}
}
}
|
Fix FxCop warning CA1018 (attributes should have AttributeUsage) | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
// Custom attribute to indicating a TypeDef is a discardable attribute.
public class DiscardableAttribute : Attribute
{
public DiscardableAttribute() { }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
// Custom attribute to indicating a TypeDef is a discardable attribute.
[AttributeUsage(AttributeTargets.All)]
public class DiscardableAttribute : Attribute
{
public DiscardableAttribute() { }
}
}
|
Add some changes to UI to make spacing equal for components | using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
class AdaptionPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues;
Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow));
Add(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues));
Add(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues));
Add(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues));
Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow));
}
}
}
| using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
class AdaptionPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues;
var container = new Table(6, 1, true);
container.Attach(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow), 0, 1, 0, 1);
container.Attach(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues), 0, 1, 1, 3);
container.Attach(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues), 0, 1, 3, 4);
container.Attach(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues), 0, 1, 4, 5);
container.Attach(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow), 0, 1, 5, 6);
Add(container);
}
}
}
|
Move test component to bottom of class | // 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.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
}
}
| // 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.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
|
Add quick check for attached domain | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ERMine.Core.Modeling
{
public class Attribute : IEntityRelationship
{
public string Label { get; set; }
public string DataType { get; set; }
public Domain Domain { get; set; }
public bool IsNullable { get; set; }
public bool IsSparse { get; set; }
public bool IsImmutable { get; set; }
public KeyType Key { get; set; }
public bool IsPartOfPrimaryKey
{
get { return Key == KeyType.Primary; }
set { Key = value ? KeyType.Primary : KeyType.None; }
}
public bool IsPartOfPartialKey
{
get { return Key == KeyType.Partial; }
set { Key = value ? KeyType.Partial : KeyType.None; }
}
public bool IsMultiValued { get; set; }
public bool IsDerived { get; set; }
public string DerivedFormula { get; set; }
public bool IsDefault { get; set; }
public string DefaultFormula { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ERMine.Core.Modeling
{
public class Attribute : IEntityRelationship
{
public string Label { get; set; }
public string DataType { get; set; }
public Domain Domain { get; set; }
public bool IsConstrainedDomain
{
get { return Domain != null; }
}
public bool IsNullable { get; set; }
public bool IsSparse { get; set; }
public bool IsImmutable { get; set; }
public KeyType Key { get; set; }
public bool IsPartOfPrimaryKey
{
get { return Key == KeyType.Primary; }
set { Key = value ? KeyType.Primary : KeyType.None; }
}
public bool IsPartOfPartialKey
{
get { return Key == KeyType.Partial; }
set { Key = value ? KeyType.Partial : KeyType.None; }
}
public bool IsMultiValued { get; set; }
public bool IsDerived { get; set; }
public string DerivedFormula { get; set; }
public bool IsDefault { get; set; }
public string DefaultFormula { get; set; }
}
}
|
Use the Query property of the Uri | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bex.Extensions
{
internal static class UriExtensions
{
internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri)
{
var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;
var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase);
if (queryIndex == -1)
{
return Enumerable.Empty<KeyValuePair<string, string>>();
}
var query = uriString.Substring(queryIndex + 1);
return query.Split('&')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split('='))
.Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bex.Extensions
{
internal static class UriExtensions
{
internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri)
{
if (string.IsNullOrEmpty(uri.Query))
{
return Enumerable.Empty<KeyValuePair<string, string>>();
}
var query = uri.Query.TrimStart('?');
return query.Split('&')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split('='))
.Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null));
}
}
}
|
Add GPG Keys API preview header | namespace Octokit
{
public static class AcceptHeaders
{
public const string StableVersion = "application/vnd.github.v3";
public const string StableVersionHtml = "application/vnd.github.html";
public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8";
public const string LicensesApiPreview = "application/vnd.github.drax-preview+json";
public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json";
public const string StarCreationTimestamps = "application/vnd.github.v3.star+json";
public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json";
public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha";
public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json";
public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json";
public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json";
}
}
| using System.Diagnostics.CodeAnalysis;
namespace Octokit
{
public static class AcceptHeaders
{
public const string StableVersion = "application/vnd.github.v3";
public const string StableVersionHtml = "application/vnd.github.html";
public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8";
public const string LicensesApiPreview = "application/vnd.github.drax-preview+json";
public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json";
public const string StarCreationTimestamps = "application/vnd.github.v3.star+json";
public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json";
public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha";
public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json";
public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json";
public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json";
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gpg")]
public const string GpgKeysPreview = "application/vnd.github.cryptographer-preview+sha";
}
}
|
Add button to access latency comparer from game | // 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.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Framework.Screens;
using osu.Game.Localisation;
using osu.Game.Screens;
using osu.Game.Screens.Import;
namespace osu.Game.Overlays.Settings.Sections.DebugSettings
{
public class GeneralSettings : SettingsSubsection
{
protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader;
[BackgroundDependencyLoader(true)]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = DebugSettingsStrings.ShowLogOverlay,
Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = DebugSettingsStrings.BypassFrontToBackPass,
Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass)
}
};
Add(new SettingsButton
{
Text = DebugSettingsStrings.ImportFiles,
Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen()))
});
}
}
}
| // 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.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Framework.Screens;
using osu.Game.Localisation;
using osu.Game.Screens;
using osu.Game.Screens.Import;
namespace osu.Game.Overlays.Settings.Sections.DebugSettings
{
public class GeneralSettings : SettingsSubsection
{
protected override LocalisableString Header => DebugSettingsStrings.GeneralHeader;
[BackgroundDependencyLoader(true)]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig, IPerformFromScreenRunner performer)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = DebugSettingsStrings.ShowLogOverlay,
Current = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = DebugSettingsStrings.BypassFrontToBackPass,
Current = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass)
},
new SettingsButton
{
Text = DebugSettingsStrings.ImportFiles,
Action = () => performer?.PerformFromScreen(menu => menu.Push(new FileImportScreen()))
},
new SettingsButton
{
Text = @"Run latency comparer",
Action = () => performer?.PerformFromScreen(menu => menu.Push(new LatencyComparerScreen()))
}
};
}
}
}
|
Add "plan" to StripSubscriptionUpdateOptions so we can change plans. | using System;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Stripe
{
public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions
{
[JsonProperty("prorate")]
public bool? Prorate { get; set; }
}
} | using System;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Stripe
{
public class StripeSubscriptionUpdateOptions : StripeSubscriptionCreateOptions
{
[JsonProperty("prorate")]
public bool? Prorate { get; set; }
[JsonProperty("plan")]
public string PlanId { get; set; }
}
} |
Remove debugging line. Sorry RockyTV! | using System;
using System.IO;
namespace DarkMultiPlayerServer
{
public class LogExpire
{
private static string logDirectory
{
get
{
return Path.Combine(Server.universeDirectory, DarkLog.LogFolder);
}
}
public static void ExpireLogs()
{
if (!Directory.Exists(logDirectory))
{
//Screenshot directory is missing so there will be no screenshots to delete.
return;
}
string[] logFiles = Directory.GetFiles(logDirectory);
foreach (string logFile in logFiles)
{
Console.WriteLine("LogFile: " + logFile);
//Check if the expireScreenshots setting is enabled
if (Settings.settingsStore.expireLogs > 0)
{
//If the file is older than a day, delete it
if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now)
{
DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!");
try
{
File.Delete(logFile);
}
catch (Exception e)
{
DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message);
}
}
}
}
}
}
} | using System;
using System.IO;
namespace DarkMultiPlayerServer
{
public class LogExpire
{
private static string logDirectory
{
get
{
return Path.Combine(Server.universeDirectory, DarkLog.LogFolder);
}
}
public static void ExpireLogs()
{
if (!Directory.Exists(logDirectory))
{
//Screenshot directory is missing so there will be no screenshots to delete.
return;
}
string[] logFiles = Directory.GetFiles(logDirectory);
foreach (string logFile in logFiles)
{
//Check if the expireScreenshots setting is enabled
if (Settings.settingsStore.expireLogs > 0)
{
//If the file is older than a day, delete it
if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now)
{
DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!");
try
{
File.Delete(logFile);
}
catch (Exception e)
{
DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message);
}
}
}
}
}
}
} |
Switch to using LocalApplicationData folder | // 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.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Serialization;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) };
var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString();
var workingFolder = Path.Combine(Path.GetTempPath(), hashedName);
return workingFolder;
}
}
}
| // 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.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Serialization;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var checksums = new[] { Checksum.Create(solution.FilePath), Checksum.Create(solution.Workspace.Kind) };
var hashedName = Checksum.Create(WellKnownSynchronizationKind.Null, checksums).ToString();
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
var workingFolder = Path.Combine(appDataFolder, "Roslyn", hashedName);
return workingFolder;
}
}
}
|
Allow call to action banner to be optional | using System.Collections.Generic;
using StockportContentApi.ContentfulModels;
using StockportContentApi.Model;
namespace StockportContentApi.ContentfulFactories
{
public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage>
{
private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory;
private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory;
private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory;
public CommsContentfulFactory(
IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory,
IContentfulFactory<ContentfulEvent, Event> eventFactory,
IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory)
{
_callToActionFactory = callToActionFactory;
_eventFactory = eventFactory;
_basicLinkFactory = basicLinkFactory;
}
public CommsHomepage ToModel(ContentfulCommsHomepage model)
{
var callToActionBanner = _callToActionFactory.ToModel(model.CallToActionBanner);
var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent);
var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks);
return new CommsHomepage(
model.Title,
model.LatestNewsHeader,
model.TwitterFeedHeader,
model.InstagramFeedTitle,
model.InstagramLink,
model.FacebookFeedTitle,
basicLinks,
displayEvent,
callToActionBanner
);
}
}
}
| using System.Collections.Generic;
using StockportContentApi.ContentfulModels;
using StockportContentApi.Model;
namespace StockportContentApi.ContentfulFactories
{
public class CommsContentfulFactory : IContentfulFactory<ContentfulCommsHomepage, CommsHomepage>
{
private readonly IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> _callToActionFactory;
private readonly IContentfulFactory<ContentfulEvent, Event> _eventFactory;
private readonly IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> _basicLinkFactory;
public CommsContentfulFactory(
IContentfulFactory<ContentfulCallToActionBanner, CallToActionBanner> callToActionFactory,
IContentfulFactory<ContentfulEvent, Event> eventFactory,
IContentfulFactory<IEnumerable<ContentfulBasicLink>, IEnumerable<BasicLink>> basicLinkFactory)
{
_callToActionFactory = callToActionFactory;
_eventFactory = eventFactory;
_basicLinkFactory = basicLinkFactory;
}
public CommsHomepage ToModel(ContentfulCommsHomepage model)
{
var callToActionBanner = model.CallToActionBanner != null
? _callToActionFactory.ToModel(model.CallToActionBanner)
: null;
var displayEvent = _eventFactory.ToModel(model.WhatsOnInStockportEvent);
var basicLinks = _basicLinkFactory.ToModel(model.UsefullLinks);
return new CommsHomepage(
model.Title,
model.LatestNewsHeader,
model.TwitterFeedHeader,
model.InstagramFeedTitle,
model.InstagramLink,
model.FacebookFeedTitle,
basicLinks,
displayEvent,
callToActionBanner
);
}
}
}
|
Update assembly version to 2.0.0 | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jason Boyd")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: InternalsVisibleTo("Treenumerable.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0")]
[assembly: AssemblyFileVersion("1.2.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jason Boyd")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Jason Boyd 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: InternalsVisibleTo("Treenumerable.Tests")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")]
|
Use correct path to MSBuild Roslyn folder on Mono | using System;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.Utilities;
namespace OmniSharp.MSBuild.Discovery.Providers
{
internal class MonoInstanceProvider : MSBuildInstanceProvider
{
public MonoInstanceProvider(ILoggerFactory loggerFactory)
: base(loggerFactory)
{
}
public override ImmutableArray<MSBuildInstance> GetInstances()
{
if (!PlatformHelper.IsMono)
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var path = PlatformHelper.GetMonoMSBuildDirPath();
if (path == null)
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var toolsPath = Path.Combine(path, "15.0", "bin");
if (!Directory.Exists(toolsPath))
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase);
var localMSBuildPath = FindLocalMSBuildDirectory();
if (localMSBuildPath != null)
{
var localRoslynPath = Path.Combine(localMSBuildPath, "Roslyn");
propertyOverrides.Add("CscToolPath", localRoslynPath);
propertyOverrides.Add("CscToolExe", "csc.exe");
}
return ImmutableArray.Create(
new MSBuildInstance(
"Mono",
toolsPath,
new Version(15, 0),
DiscoveryType.Mono,
propertyOverrides.ToImmutable()));
}
}
}
| using System;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.Utilities;
namespace OmniSharp.MSBuild.Discovery.Providers
{
internal class MonoInstanceProvider : MSBuildInstanceProvider
{
public MonoInstanceProvider(ILoggerFactory loggerFactory)
: base(loggerFactory)
{
}
public override ImmutableArray<MSBuildInstance> GetInstances()
{
if (!PlatformHelper.IsMono)
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var path = PlatformHelper.GetMonoMSBuildDirPath();
if (path == null)
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var toolsPath = Path.Combine(path, "15.0", "bin");
if (!Directory.Exists(toolsPath))
{
return ImmutableArray<MSBuildInstance>.Empty;
}
var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase);
var localMSBuildPath = FindLocalMSBuildDirectory();
if (localMSBuildPath != null)
{
var localRoslynPath = Path.Combine(localMSBuildPath, "15.0", "Bin", "Roslyn");
propertyOverrides.Add("CscToolPath", localRoslynPath);
propertyOverrides.Add("CscToolExe", "csc.exe");
}
return ImmutableArray.Create(
new MSBuildInstance(
"Mono",
toolsPath,
new Version(15, 0),
DiscoveryType.Mono,
propertyOverrides.ToImmutable()));
}
}
}
|
Update the systemclock to use UtcNow. This is because some of code use Month, Year properties of DateTimeOffset | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace Microsoft.Its.Domain
{
/// <summary>
/// Provides access to system time.
/// </summary>
[DebuggerStepThrough]
public class SystemClock : IClock
{
public static readonly SystemClock Instance = new SystemClock();
private SystemClock()
{
}
/// <summary>
/// Gets the current time via <see cref="DateTimeOffset.Now" />.
/// </summary>
public DateTimeOffset Now()
{
return DateTimeOffset.Now;
}
public override string ToString()
{
return GetType() + ": " + Now().ToString("O");
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace Microsoft.Its.Domain
{
/// <summary>
/// Provides access to system time.
/// </summary>
[DebuggerStepThrough]
public class SystemClock : IClock
{
public static readonly SystemClock Instance = new SystemClock();
private SystemClock()
{
}
/// <summary>
/// Gets the current time via <see cref="DateTimeOffset.Now" />.
/// </summary>
public DateTimeOffset Now()
{
return DateTimeOffset.UtcNow;
}
public override string ToString()
{
return GetType() + ": " + Now().ToString("O");
}
}
}
|
Revert "Gary changed wording per content request" | @model string
@{
ViewData["Title"] = "Thank you";
ViewData["og:title"] = "Thank you";
Layout = "../Shared/_Layout.cshtml";
}
<div class="grid-container-full-width">
<div class="grid-container grid-100">
<div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100">
<section aria-label="Thank you message" class="grid-100 mobile-grid-100">
<div class="l-content-container l-article-container">
<h1>Thank you for contacting us</h1>
<p>We will aim to respond to your enquiry within 10 working days.</p>
<stock-button href="@Model">Return to previous page</stock-button>
</div>
</section>
</div>
</div>
</div>
| @model string
@{
ViewData["Title"] = "Thank you";
ViewData["og:title"] = "Thank you";
Layout = "../Shared/_Layout.cshtml";
}
<div class="grid-container-full-width">
<div class="grid-container grid-100">
<div class="l-body-section-filled l-short-content mobile-grid-100 tablet-grid-100 grid-100">
<section aria-label="Thank you message" class="grid-100 mobile-grid-100">
<div class="l-content-container l-article-container">
<h1>Thank you for contacting us</h1>
<p>We will endeavour to respond to your enquiry within 10 working days.</p>
<stock-button href="@Model">Return To Previous Page</stock-button>
</div>
</section>
</div>
</div>
</div>
|
Change Sensor level to 100 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using SendGrid;
using TapBoxCommon.Models;
using Microsoft.Azure;
namespace TapBoxWebjob
{
class MailSender
{
public static void SendMailToOwner(Device NotifierDevice, int SensorValue)
{
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo(NotifierDevice.OwnerMailAddress);
myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost");
myMessage.Subject = "Notification from your Tapbox";
Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}");
if (SensorValue < 20)
{
Console.WriteLine("Your Mailbox is Empty");
return;
}
else if (SensorValue < 300)
{
Console.WriteLine("You have some Mail");
myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName;
}
else if (SensorValue > 300)
{
Console.WriteLine("You have A Lot of Mail");
myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName;
}
var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key");
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using SendGrid;
using TapBoxCommon.Models;
using Microsoft.Azure;
namespace TapBoxWebjob
{
class MailSender
{
public static void SendMailToOwner(Device NotifierDevice, int SensorValue)
{
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo(NotifierDevice.OwnerMailAddress);
myMessage.From = new MailAddress("sjost@hsr.ch", "Samuel Jost");
myMessage.Subject = "Notification from your Tapbox";
Console.WriteLine($"Device: {NotifierDevice.DeviceName} - Sensor Value: {SensorValue}");
if (SensorValue < 100)
{
Console.WriteLine("Your Mailbox is Empty");
return;
}
else if (SensorValue < 300)
{
Console.WriteLine("You have some Mail");
myMessage.Text = "You have some Mail in your device "+NotifierDevice.DeviceName;
}
else if (SensorValue > 300)
{
Console.WriteLine("You have A Lot of Mail");
myMessage.Text = "You have a lot of Mail in your device " + NotifierDevice.DeviceName;
}
var apiKey = CloudConfigurationManager.GetSetting("SendGrid.API_Key");
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage);
}
}
}
|
Add missing comment block. bugid: 812 | using System;
namespace Csla
{
internal class BrowsableAttribute : Attribute
{
public BrowsableAttribute(bool flag)
{ }
}
internal class DisplayAttribute : Attribute
{
public string Name { get; set; }
public bool AutoGenerateField { get; set; }
public DisplayAttribute(bool AutoGenerateField = false, string Name = "")
{
this.AutoGenerateField = AutoGenerateField;
this.Name = Name;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="PortedAttributes.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Dummy implementations of .NET attributes missing in WP7.</summary>
//-----------------------------------------------------------------------
using System;
namespace Csla
{
internal class BrowsableAttribute : Attribute
{
public BrowsableAttribute(bool flag)
{ }
}
internal class DisplayAttribute : Attribute
{
public string Name { get; set; }
public bool AutoGenerateField { get; set; }
public DisplayAttribute(bool AutoGenerateField = false, string Name = "")
{
this.AutoGenerateField = AutoGenerateField;
this.Name = Name;
}
}
}
|
Fix bug: Ensure CacheTimeout is actually set when extending cache. | using System;
using FeatureSwitcher.AwsConfiguration.Behaviours;
namespace FeatureSwitcher.AwsConfiguration.Models
{
internal class BehaviourCacheItem
{
public IBehaviour Behaviour { get; }
public DateTime CacheTimeout { get; }
public bool IsExpired => this.CacheTimeout < DateTime.UtcNow;
public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime)
{
Behaviour = behaviour;
CacheTimeout = DateTime.UtcNow.Add(cacheTime);
}
public void ExtendCache()
{
CacheTimeout.Add(TimeSpan.FromMinutes(1));
}
}
}
| using System;
using FeatureSwitcher.AwsConfiguration.Behaviours;
namespace FeatureSwitcher.AwsConfiguration.Models
{
internal class BehaviourCacheItem
{
public IBehaviour Behaviour { get; }
public DateTime CacheTimeout { get; private set; }
public bool IsExpired => this.CacheTimeout < DateTime.UtcNow;
public BehaviourCacheItem(IBehaviour behaviour, TimeSpan cacheTime)
{
Behaviour = behaviour;
CacheTimeout = DateTime.UtcNow.Add(cacheTime);
}
public void ExtendCache()
{
CacheTimeout = CacheTimeout.Add(TimeSpan.FromMinutes(1));
}
}
}
|
Remove code that unconditionally enable https redirects and authorization | using TruckRouter.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
app.UseAuthorization();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
| using TruckRouter.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
app.UseAuthorization();
}
app.MapControllers();
app.Run();
|
Add logging in case of null response from Syncthing | using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SyncTrayzor.Syncthing.ApiClient
{
public class SyncthingHttpClientHandler : WebRequestHandler
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public SyncthingHttpClientHandler()
{
// We expect Syncthing to return invalid certs
this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode)
logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
else
logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());
return response;
}
}
}
| using NLog;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SyncTrayzor.Syncthing.ApiClient
{
public class SyncthingHttpClientHandler : WebRequestHandler
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public SyncthingHttpClientHandler()
{
// We expect Syncthing to return invalid certs
this.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
// We're getting null bodies from somewhere: try and figure out where
var responseString = await response.Content.ReadAsStringAsync();
if (responseString == null)
logger.Warn($"Null response received from {request.RequestUri}. {response}. Content (again): {response.Content.ReadAsStringAsync()}");
if (response.IsSuccessStatusCode)
logger.Trace(() => response.Content.ReadAsStringAsync().Result.Trim());
else
logger.Warn("Non-successful status code. {0} {1}", response, (await response.Content.ReadAsStringAsync()).Trim());
return response;
}
}
}
|
Document why null is ok here | using System.Runtime.Remoting.Channels;
namespace RedGate.AppHost.Remoting
{
internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider
{
private readonly IClientChannelSinkProvider m_Upstream;
private readonly string m_Url;
internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id)
{
if (upstream == null)
throw new ArgumentNullException("upstream");
if (String.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
m_Upstream = upstream;
m_Url = string.Format("ipc://{0}", id);
}
public IClientChannelSinkProvider Next
{
get { return m_Upstream.Next; }
set { m_Upstream.Next = value; }
}
public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData)
{
return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null;
}
}
} | using System;
using System.Runtime.Remoting.Channels;
namespace RedGate.AppHost.Remoting
{
internal class ClientChannelSinkProviderForParticularServer : IClientChannelSinkProvider
{
private readonly IClientChannelSinkProvider m_Upstream;
private readonly string m_Url;
internal ClientChannelSinkProviderForParticularServer(IClientChannelSinkProvider upstream, string id)
{
if (upstream == null)
throw new ArgumentNullException("upstream");
if (String.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
m_Upstream = upstream;
m_Url = string.Format("ipc://{0}", id);
}
public IClientChannelSinkProvider Next
{
get { return m_Upstream.Next; }
set { m_Upstream.Next = value; }
}
public IClientChannelSink CreateSink(IChannelSender channel, string url, object remoteChannelData)
{
//Returning null indicates that the sink cannot be created as per Microsoft documentation
return url == m_Url ? m_Upstream.CreateSink(channel, url, remoteChannelData) : null;
}
}
} |
Add a display property for cadet rank | using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Common.Models
{
public enum Rank
{
[Display(Name = "PVT")]
E1 = 1,
[Display(Name = "PV2")]
E2 = 2,
[Display(Name = "PFC")]
E3 = 3,
[Display(Name = "SPC")]
E4 = 4,
[Display(Name = "SGT")]
E5 = 5,
[Display(Name = "SSG")]
E6 = 6,
[Display(Name = "SFC")]
E7 = 7,
[Display(Name = "1SG")]
E8 = 8,
Cadet = 9,
[Display(Name = "2LT")]
O1 = 10,
[Display(Name = "1LT")]
O2 = 11,
[Display(Name = "CPT")]
O3 = 12,
[Display(Name = "MAJ")]
O4 = 13,
[Display(Name = "LTC")]
O5 = 14,
[Display(Name = "COL")]
O6 = 15
}
} | using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Common.Models
{
public enum Rank
{
[Display(Name = "PVT")]
E1 = 1,
[Display(Name = "PV2")]
E2 = 2,
[Display(Name = "PFC")]
E3 = 3,
[Display(Name = "SPC")]
E4 = 4,
[Display(Name = "SGT")]
E5 = 5,
[Display(Name = "SSG")]
E6 = 6,
[Display(Name = "SFC")]
E7 = 7,
[Display(Name = "1SG")]
E8 = 8,
[Display(Name = "CDT")]
Cadet = 9,
[Display(Name = "2LT")]
O1 = 10,
[Display(Name = "1LT")]
O2 = 11,
[Display(Name = "CPT")]
O3 = 12,
[Display(Name = "MAJ")]
O4 = 13,
[Display(Name = "LTC")]
O5 = 14,
[Display(Name = "COL")]
O6 = 15
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.