doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
17737e41-b22a-4893-9fcb-f18e50d58091
{ "language": "C#" }
```c# using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } } ``` Set StateId in DataTokens so ShieldDecode works because StateId was in the data when ShieldEncode was called
```c# using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } } ```
a5ad9aef-714d-4c24-bd90-a20a3511b58d
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.99.0.0")] [assembly: AssemblyFileVersion("1.99.0.0")] [assembly: AssemblyInformationalVersion("1.99.0")] ``` Use auto-version for AssemblyFileVersion in develop builds to facilitate installers
```c# using System.Reflection; [assembly: AssemblyCompany("Picoe Software Solutions Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.99.0.0")] [assembly: AssemblyFileVersion("1.99.*")] [assembly: AssemblyInformationalVersion("1.99.0")] ```
f99009d0-79e5-499a-8632-d0449235ecd3
{ "language": "C#" }
```c# using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; namespace PersonalWebApp.Middleware { public class StripWhitespaceMiddleware { private readonly RequestDelegate _next; public StripWhitespaceMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var body = context.Response.Body; using (var intercept = new MemoryStream()) { context.Response.Body = intercept; await _next.Invoke(context); var contentType = context.Response.ContentType ?? ""; if (contentType.StartsWith("text/html")) { intercept.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(intercept)) { var responseBody = await reader.ReadToEndAsync(); var stripped = Regex.Replace(responseBody, @">\s+<", "><"); var bytes = Encoding.UTF8.GetBytes(stripped); await body.WriteAsync(bytes, 0, bytes.Length); } } else { await intercept.CopyToAsync(body); } } } } }``` Fix bug with non-HTML responses
```c# using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; namespace PersonalWebApp.Middleware { public class StripWhitespaceMiddleware { private readonly RequestDelegate _next; public StripWhitespaceMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var body = context.Response.Body; using (var intercept = new MemoryStream()) { context.Response.Body = intercept; await _next.Invoke(context); var contentType = context.Response.ContentType ?? ""; if (contentType.StartsWith("text/html")) { intercept.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(intercept)) { var responseBody = await reader.ReadToEndAsync(); var stripped = Regex.Replace(responseBody, @">\s+<", "><"); var bytes = Encoding.UTF8.GetBytes(stripped); await body.WriteAsync(bytes, 0, bytes.Length); } } else { intercept.Seek(0, SeekOrigin.Begin); await intercept.CopyToAsync(body); } } } } }```
62638e87-fb41-4b82-97d1-1e5a2176444c
{ "language": "C#" }
```c# using System.Web; using System.Web.Mvc; namespace SvNaum.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); } } } ``` Include missing views AddNews and EditNews in project.
```c# using System.Web; using System.Web.Mvc; namespace SvNaum.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } } ```
08b0e08b-146f-429b-bd84-5296f4dfa1fe
{ "language": "C#" }
```c# namespace C42A { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static int Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var f = new global::C42A.CAB42.Windows.Forms.CAB42()) { if (args != null && args.Length > 0) { if (args.Length == 1) { f.OpenFileOnShow = args[0]; } } Application.Run(f); } return 0; } } } ``` Add support for building from the command line.
```c# namespace C42A { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using C42A.CAB42; internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static int Main(string[] args) { if (args.Length > 0 && args[0] == "build") { AllocConsole(); if (args.Length != 2) Console.WriteLine("cab42.exe build PATH"); try { Build(args[1]); } catch (Exception error) { Console.Error.WriteLine(error.ToString()); return 1; } return 0; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var f = new global::C42A.CAB42.Windows.Forms.CAB42()) { if (args != null && args.Length > 0) { if (args.Length == 1) { f.OpenFileOnShow = args[0]; } } Application.Run(f); } return 0; } private static void Build(string file) { var buildProject = ProjectInfo.Open(file); using (var buildContext = new CabwizBuildContext()) { var tasks = buildProject.CreateBuildTasks(); var feedback = new BuildFeedbackBase(Console.Out); buildContext.Build(tasks, feedback); } } [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); } } ```
ddc6ce11-3840-4a0b-a8a3-04a3aee0d088
{ "language": "C#" }
```c# using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { using (Lexer l = new Lexer(@"../../testdata/big.txt")) { Token t; do { t = l.GetNextToken(); Console.WriteLine(TokenHelper.PrintToken(t)); } while (t != Token.EOF); // necessary when testing on windows with visual studio //Console.WriteLine("Press 'enter' to exit ...."); //Console.ReadLine(); } } } } ``` Update Main to print the graph
```c# using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { // using (Lexer l = new Lexer(@"../../testdata/big.txt")) // { // Token t; // do // { // t = l.GetNextToken(); // Console.WriteLine(TokenHelper.PrintToken(t)); // // } while (t != Token.EOF); // // // necessary when testing on windows with visual studio // //Console.WriteLine("Press 'enter' to exit ...."); // //Console.ReadLine(); // } using (Parser p = new Parser(@"../../testdata/test002.txt")) { p.Parse(); p.FlowCfg.GenerateDOTOutput(); using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt")) { file.WriteLine( p.FlowCfg.DOTOutput); } } } } } ```
78a71f4e-4a76-4138-b0a2-25aca94cd963
{ "language": "C#" }
```c# namespace System.Net.Http { using System.Collections.Generic; using System.Diagnostics; using System.Linq; static class HttpHelper { public static string ValidatePath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path == "" || path == "/") return ""; if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path)); return path; } public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers) { var result = handlers.FirstOrDefault(); var last = result; foreach (var handler in handlers.Skip(1)) { last.InnerHandler = handler; last = handler; } return result; } [Conditional("DEBUG")] public static void DumpErrors(HttpResponseMessage message) { if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized) { var dump = (Action)(async () => { var error = await message.Content.ReadAsStringAsync(); Debug.WriteLine(error); }); dump(); } } public static int TryGetContentLength(HttpResponseMessage response) { int result; IEnumerable<string> value; if (response.Headers.TryGetValues("Content-Length", out value) && value.Any() && int.TryParse(value.First(), out result)) { return result; } return 0; } } } ``` Add HttpResponseMessage.EnsureSuccess that include response content in the exception.
```c# namespace System.Net.Http { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; static class HttpHelper { public static string ValidatePath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path == "" || path == "/") return ""; if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path)); return path; } public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers) { var result = handlers.FirstOrDefault(); var last = result; foreach (var handler in handlers.Skip(1)) { last.InnerHandler = handler; last = handler; } return result; } [Conditional("DEBUG")] public static void DumpErrors(HttpResponseMessage message) { if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized) { var dump = (Action)(async () => { var error = await message.Content.ReadAsStringAsync(); Debug.WriteLine(error); }); dump(); } } public static HttpResponseMessage EnsureSuccess(this HttpResponseMessage message) { if (message.IsSuccessStatusCode) return message; throw new HttpRequestException($"Http {message.StatusCode}: {message.Content.ReadAsStringAsync().Result}"); } public static int TryGetContentLength(HttpResponseMessage response) { int result; IEnumerable<string> value; if (response.Headers.TryGetValues("Content-Length", out value) && value.Any() && int.TryParse(value.First(), out result)) { return result; } return 0; } } } ```
2284ac0f-fb57-4bb4-9cd9-686ca3537617
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Data; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.MetaData; using Orchard.ContentManagement.MetaData.Builders; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.Environment.Extensions; namespace LccNetwork.Migrations { [OrchardFeature("fea")] public class NavigationMigrations : DataMigrationImpl { public int Create() { return 1; } public int UpdateFrom1() { return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("SectionMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 3; } } }``` Add a footer navigation widget.
```c# using System; using System.Collections.Generic; using System.Data; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.MetaData; using Orchard.ContentManagement.MetaData.Builders; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.Environment.Extensions; namespace LccNetwork.Migrations { [OrchardFeature("SectionNavigation")] public class NavigationMigrations : DataMigrationImpl { public int Create() { return 1; } public int UpdateFrom1() { return 2; } public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("SectionMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 4; } public int UpdateFrom4() { ContentDefinitionManager.AlterTypeDefinition("FooterMenu", cfg => cfg .WithPart("CommonPart") .WithPart("IdentityPart") .WithPart("WidgetPart") .WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI? .WithSetting("Stereotype", "Widget") ); return 5; } } }```
1f7056c1-5ef1-47c8-9ea0-7f928f432514
{ "language": "C#" }
```c# // Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Reflection; namespace NodaTime.Benchmarks.Framework { /// <summary> /// The results of running a single test. /// </summary> internal class BenchmarkResult { private const long TicksPerPicosecond = 100 * 1000L; private const long TicksPerNanosecond = 100; private readonly MethodInfo method; private readonly int iterations; private readonly Duration duration; internal BenchmarkResult(MethodInfo method, int iterations, Duration duration) { this.method = method; this.iterations = iterations; this.duration = duration; } internal MethodInfo Method { get { return method; } } internal long Iterations { get { return iterations; } } internal Duration Duration { get { return duration; } } internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } } internal long TicksPerCall { get { return Duration.Ticks / iterations; } } internal long PicosecondsPerCall { get { return (Duration.Ticks * TicksPerPicosecond) / iterations; } } internal long NanosecondsPerCall { get { return (Duration.Ticks * TicksPerNanosecond) / iterations; } } } }``` Tweak to use the fact that we now have nanosecond precision in Duration.
```c# // Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Reflection; namespace NodaTime.Benchmarks.Framework { /// <summary> /// The results of running a single test. /// </summary> internal class BenchmarkResult { private const long TicksPerPicosecond = 100 * 1000L; private const long TicksPerNanosecond = 100; private readonly MethodInfo method; private readonly int iterations; private readonly Duration duration; internal BenchmarkResult(MethodInfo method, int iterations, Duration duration) { this.method = method; this.iterations = iterations; this.duration = duration; } internal MethodInfo Method { get { return method; } } internal long Iterations { get { return iterations; } } internal Duration Duration { get { return duration; } } // Use ticks here rather than nanoseconds, as otherwise the multiplication could easily overflow. As an alternative, // we could use decimal arithmetic or BigInteger... internal long CallsPerSecond { get { return iterations * NodaConstants.TicksPerSecond / duration.Ticks; } } internal long NanosecondsPerCall { get { return Duration.ToInt64Nanoseconds() / iterations; } } } }```
edabe05f-eabf-47ea-82ba-cbddc3d6cfc5
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace Nest { [JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))] public interface ITtlField : IFieldMapping { [JsonProperty("enabled")] bool? Enabled { get; set; } [JsonProperty("default")] Time Default { get; set; } } public class TtlField : ITtlField { public bool? Enabled { get; set; } public Time Default { get; set; } } public class TtlFieldDescriptor : DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField { bool? ITtlField.Enabled { get; set; } Time ITtlField.Default { get; set; } public TtlFieldDescriptor Enable(bool enable = true) => Assign(a => a.Enabled = enable); public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl); } }``` Make enable method name consistent on TTL field
```c# using Newtonsoft.Json; namespace Nest { [JsonConverter(typeof(ReadAsTypeJsonConverter<TtlField>))] public interface ITtlField : IFieldMapping { [JsonProperty("enabled")] bool? Enabled { get; set; } [JsonProperty("default")] Time Default { get; set; } } public class TtlField : ITtlField { public bool? Enabled { get; set; } public Time Default { get; set; } } public class TtlFieldDescriptor : DescriptorBase<TtlFieldDescriptor, ITtlField>, ITtlField { bool? ITtlField.Enabled { get; set; } Time ITtlField.Default { get; set; } public TtlFieldDescriptor Enabled(bool enabled = true) => Assign(a => a.Enabled = enabled); public TtlFieldDescriptor Default(Time defaultTtl) => Assign(a => a.Default = defaultTtl); } } ```
01eac545-90e3-4e0f-8d2b-8348a937994b
{ "language": "C#" }
```c# using Xunit; namespace PlayerRank.UnitTests { public class PlayerTests { [Fact] public void CanIncreasePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(100)); Assert.Equal(new Points(100), player.Points); Assert.Equal(100, player.Score); } [Fact] public void CanReducePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(-100)); Assert.Equal(new Points(-100), player.Points); Assert.Equal(-100, player.Score); } } } ``` Change test to use new subtract method
```c# using Xunit; namespace PlayerRank.UnitTests { public class PlayerTests { [Fact] public void CanIncreasePlayersScore() { var player = new PlayerScore("Foo"); player.AddPoints(new Points(100)); Assert.Equal(new Points(100), player.Points); Assert.Equal(100, player.Score); } [Fact] public void CanReducePlayersScore() { var player = new PlayerScore("Foo"); player.SubtractPoints(new Points(100)); Assert.Equal(new Points(-100), player.Points); Assert.Equal(-100, player.Score); } } } ```
e45a93fb-9896-4c3a-b959-5e7e6c448549
{ "language": "C#" }
```c# using System; using System.Reactive.Linq; using static LanguageExt.Prelude; using static LanguageExt.Process; namespace LanguageExt { internal class ActorDispatchNotExist : IActorDispatch { public readonly ProcessId ProcessId; public ActorDispatchNotExist(ProcessId pid) { ProcessId = pid; } private T Raise<T>() => raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null)); public Map<string, ProcessId> GetChildren() => Map.empty<string, ProcessId>(); public IObservable<T> Observe<T>() => Observable.Empty<T>(); public IObservable<T> ObserveState<T>() => Observable.Empty<T>(); public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) => Raise<Unit>(); public Unit TellSystem(SystemMessage message, ProcessId sender) => Raise<Unit>(); public Unit TellUserControl(UserControlMessage message, ProcessId sender) => Raise<Unit>(); public Unit Ask(object message, ProcessId sender) => Raise<Unit>(); public Unit Publish(object message) => Raise<Unit>(); public Unit Kill() => unit; public int GetInboxCount() => 0; public Unit Watch(ProcessId pid) => Raise<Unit>(); public Unit UnWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchUnWatch(ProcessId pid) => Raise<Unit>(); } } ``` Stop unwatch from failing on shutdown
```c# using System; using System.Reactive.Linq; using static LanguageExt.Prelude; using static LanguageExt.Process; namespace LanguageExt { internal class ActorDispatchNotExist : IActorDispatch { public readonly ProcessId ProcessId; public ActorDispatchNotExist(ProcessId pid) { ProcessId = pid; } private T Raise<T>() => raise<T>(new ProcessException($"Doesn't exist ({ProcessId})", Self.Path, Sender.Path, null)); public Map<string, ProcessId> GetChildren() => Map.empty<string, ProcessId>(); public IObservable<T> Observe<T>() => Observable.Empty<T>(); public IObservable<T> ObserveState<T>() => Observable.Empty<T>(); public Unit Tell(object message, ProcessId sender, Message.TagSpec tag) => Raise<Unit>(); public Unit TellSystem(SystemMessage message, ProcessId sender) => Raise<Unit>(); public Unit TellUserControl(UserControlMessage message, ProcessId sender) => Raise<Unit>(); public Unit Ask(object message, ProcessId sender) => Raise<Unit>(); public Unit Publish(object message) => Raise<Unit>(); public Unit Kill() => unit; public int GetInboxCount() => 0; public Unit Watch(ProcessId pid) => Raise<Unit>(); public Unit UnWatch(ProcessId pid) => unit; public Unit DispatchWatch(ProcessId pid) => Raise<Unit>(); public Unit DispatchUnWatch(ProcessId pid) => unit; } } ```
b11e8f6e-8efd-452d-9165-50e03fcd2ead
{ "language": "C#" }
```c# using System.Configuration; namespace Signatory { public static class Settings { public static string Authority = ConfigurationManager.AppSettings["Authority"]; public static string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"]; public static string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"]; } }``` Mark settings as read only
```c# using System.Configuration; namespace Signatory { public static class Settings { public static readonly string Authority = ConfigurationManager.AppSettings["Authority"]; public static readonly string GitHubKey = ConfigurationManager.AppSettings["GitHubKey"]; public static readonly string GitHubSecret = ConfigurationManager.AppSettings["GitHubSecret"]; } }```
498a7d18-8e55-4f75-bac0-71351b86400f
{ "language": "C#" }
```c# using NUnit.Framework; using System; using System.Collections; using Symbooglix; using Microsoft.Boogie; using Microsoft.Basetypes; namespace ExprBuilderTests { [TestFixture()] public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase { protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder() { var simpleBuilder = GetSimpleBuilder(); var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder); return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder); } protected ConstantFoldingExprBuilder GetConstantFoldingBuilder() { return new ConstantFoldingExprBuilder(GetSimpleBuilder()); } } } ``` Remove NUnit attribute accidently left on a class. The attribute is pointless because the class has no tests.
```c# using NUnit.Framework; using System; using System.Collections; using Symbooglix; using Microsoft.Boogie; using Microsoft.Basetypes; namespace ExprBuilderTests { public class ConstantFoldingExprBuilderTests : SimpleExprBuilderTestBase { protected Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder> GetSimpleAndConstantFoldingBuilder() { var simpleBuilder = GetSimpleBuilder(); var constantFoldingBuilder = new ConstantFoldingExprBuilder(simpleBuilder); return new Tuple<SimpleExprBuilder, ConstantFoldingExprBuilder>(simpleBuilder, constantFoldingBuilder); } protected ConstantFoldingExprBuilder GetConstantFoldingBuilder() { return new ConstantFoldingExprBuilder(GetSimpleBuilder()); } } } ```
3cb5ea89-697c-4762-b4f9-4addac3b32d2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Contract.Models { public class FfmpegJobModel { public FfmpegJobModel() { Tasks = new List<FfmpegTaskModel>(); } public Guid JobCorrelationId { get; set; } public TranscodingJobState State { get { if (Tasks.All(x => x.State == TranscodingJobState.Done)) return TranscodingJobState.Done; if (Tasks.Any(j => j.State == TranscodingJobState.Failed)) return TranscodingJobState.Failed; if (Tasks.Any(j => j.State == TranscodingJobState.Paused)) return TranscodingJobState.Paused; if (Tasks.Any(j => j.State == TranscodingJobState.InProgress)) return TranscodingJobState.InProgress; if (Tasks.Any(j => j.State == TranscodingJobState.Queued)) return TranscodingJobState.Queued; return TranscodingJobState.Unknown; } } public DateTimeOffset Created { get; set; } public DateTimeOffset Needed { get; set; } public IEnumerable<FfmpegTaskModel> Tasks { get; set; } } }``` Fix job cancelled showing up as State = Unknown
```c# using System; using System.Collections.Generic; using System.Linq; namespace Contract.Models { public class FfmpegJobModel { public FfmpegJobModel() { Tasks = new List<FfmpegTaskModel>(); } public Guid JobCorrelationId { get; set; } public TranscodingJobState State { get { if (Tasks.All(x => x.State == TranscodingJobState.Done)) return TranscodingJobState.Done; if (Tasks.Any(j => j.State == TranscodingJobState.Failed)) return TranscodingJobState.Failed; if (Tasks.Any(j => j.State == TranscodingJobState.Paused)) return TranscodingJobState.Paused; if (Tasks.Any(j => j.State == TranscodingJobState.InProgress)) return TranscodingJobState.InProgress; if (Tasks.Any(j => j.State == TranscodingJobState.Queued)) return TranscodingJobState.Queued; if (Tasks.Any(j => j.State == TranscodingJobState.Canceled)) return TranscodingJobState.Canceled; return TranscodingJobState.Unknown; } } public DateTimeOffset Created { get; set; } public DateTimeOffset Needed { get; set; } public IEnumerable<FfmpegTaskModel> Tasks { get; set; } } }```
3771ea06-037f-4e90-970f-dc9f07ab1eca
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using VRGIN.Core; using VRGIN.Helpers; namespace HoneySelectVR { internal class HoneyInterpreter : GameInterpreter { public HScene Scene; private IList<IActor> _Actors = new List<IActor>(); protected override void OnLevel(int level) { base.OnLevel(level); Scene = InitScene(GameObject.FindObjectOfType<HScene>()); } protected override void OnUpdate() { base.OnUpdate(); } private HScene InitScene(HScene scene) { _Actors.Clear(); if(scene) { StartCoroutine(DelayedInit()); } return scene; } IEnumerator DelayedInit() { yield return null; yield return null; var charFemaleField = typeof(HScene).GetField("chaFemale", BindingFlags.NonPublic | BindingFlags.Instance); var charMaleField = typeof(HScene).GetField("chaMale", BindingFlags.NonPublic | BindingFlags.Instance); var female = charFemaleField.GetValue(Scene) as CharFemale; var male = charMaleField.GetValue(Scene) as CharMale; if (male) { _Actors.Add(new HoneyActor(male)); } if (female) { _Actors.Add(new HoneyActor(female)); } VRLog.Info("Found {0} chars", _Actors.Count); } public override IEnumerable<IActor> Actors { get { return _Actors; } } } }``` Change the way characters are recognized.
```c# using Manager; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using VRGIN.Core; using VRGIN.Helpers; using System.Linq; namespace HoneySelectVR { internal class HoneyInterpreter : GameInterpreter { public HScene Scene; private IList<HoneyActor> _Actors = new List<HoneyActor>(); protected override void OnLevel(int level) { base.OnLevel(level); Scene = GameObject.FindObjectOfType<HScene>(); StartCoroutine(DelayedInit()); } protected override void OnUpdate() { base.OnUpdate(); } IEnumerator DelayedInit() { var scene = Singleton<Scene>.Instance; if (!scene) VRLog.Error("No scene"); while(scene.IsNowLoading) { yield return null; } foreach(var actor in GameObject.FindObjectsOfType<CharInfo>()) { _Actors.Add(new HoneyActor(actor)); } _Actors = _Actors.OrderBy(a => a.Actor.Sex).ToList(); VRLog.Info("Found {0} chars", _Actors.Count); } public override IEnumerable<IActor> Actors { get { return _Actors.Cast<IActor>(); } } } }```
b414cae8-0bf8-484c-9739-16a6df3c41e0
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // 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-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ``` Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // 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-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ```
bf801e0f-6e67-4af5-ba6b-8b89a9616ece
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace MyTrips.UITests { [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] public void Repl() { app.Repl (); } } }``` Add instructions for using UITest REPL.
```c# using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace MyTrips.UITests { [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } // If you would like to play around with the Xamarin.UITest REPL // uncomment out this method, and run this test with the NUnit test runner. // [Test] // public void Repl() // { // app.Repl (); // } } }```
bb1f885b-cefe-4e5e-aeb5-f1f8aa917c05
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Arkivverket.Arkade.Core { public class ArchiveMetadata { public string ArchiveDescription { get; set; } public string AgreementNumber { get; set; } public List<MetadataEntityInformationUnit> ArchiveCreators { get; } = new List<MetadataEntityInformationUnit>(); public MetadataEntityInformationUnit Transferer { get; set; } public MetadataEntityInformationUnit Producer { get; set; } public List<MetadataEntityInformationUnit> Owners { get; } = new List<MetadataEntityInformationUnit>(); public string Recipient { get; set; } public MetadataSystemInformationUnit System { get; set; } public MetadataSystemInformationUnit ArchiveSystem { get; set; } public List<string> Comments { get; } = new List<string>(); public string History { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public DateTime ExtractionDate { get; set; } public string IncommingSeparator { get; set; } public string OutgoingSeparator { get; set; } } public class MetadataEntityInformationUnit { public string Entity { get; set; } public string ContactPerson { get; set; } public string Telephone { get; set; } public string Email { get; set; } } public class MetadataSystemInformationUnit { public string Name { get; set; } public string Version { get; set; } public string Type { get; set; } public string TypeVersion { get; set; } } } ``` Enable setters and initialize lists from constructor (again)
```c# using System; using System.Collections.Generic; namespace Arkivverket.Arkade.Core { public class ArchiveMetadata { public string ArchiveDescription { get; set; } public string AgreementNumber { get; set; } public List<MetadataEntityInformationUnit> ArchiveCreators { get; set; } public MetadataEntityInformationUnit Transferer { get; set; } public MetadataEntityInformationUnit Producer { get; set; } public List<MetadataEntityInformationUnit> Owners { get; set; } public string Recipient { get; set; } public MetadataSystemInformationUnit System { get; set; } public MetadataSystemInformationUnit ArchiveSystem { get; set; } public List<string> Comments { get; set; } public string History { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public DateTime ExtractionDate { get; set; } public string IncommingSeparator { get; set; } public string OutgoingSeparator { get; set; } public ArchiveMetadata() { ArchiveCreators = new List<MetadataEntityInformationUnit>(); Owners = new List<MetadataEntityInformationUnit>(); Comments = new List<string>(); } } public class MetadataEntityInformationUnit { public string Entity { get; set; } public string ContactPerson { get; set; } public string Telephone { get; set; } public string Email { get; set; } } public class MetadataSystemInformationUnit { public string Name { get; set; } public string Version { get; set; } public string Type { get; set; } public string TypeVersion { get; set; } } } ```
3f80ce30-8ab1-40a6-8bf0-f18f8392724c
{ "language": "C#" }
```c# using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component .For<AppHarborApi>()); container.Register(Component .For<AuthInfo>() .UsingFactoryMethod(x => { var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User); return new AuthInfo { AccessToken = token }; })); container.Register(Component .For<CommandDispatcher>()); } } } ``` Add collection resolver to container
```c# using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Castle.MicroKernel.Resolvers.SpecializedResolvers; namespace AppHarbor { public class AppHarborInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); container.Register(Component .For<AppHarborApi>()); container.Register(Component .For<AuthInfo>() .UsingFactoryMethod(x => { var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User); return new AuthInfo { AccessToken = token }; })); container.Register(Component .For<CommandDispatcher>()); } } } ```
5190fc7f-cd9f-4c5a-a4f7-686e731d37fb
{ "language": "C#" }
```c# using System; using Conreign.Cluster; using Microsoft.WindowsAzure.ServiceRuntime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Host; namespace Conreign.Host.Azure { public class SiloRole : RoleEntryPoint { private AzureSilo _silo; public override void Run() { var env = RoleEnvironment.GetConfigurationSettingValue("Environment"); if (string.IsNullOrEmpty(env)) { throw new InvalidOperationException("Unable to determine environment."); } var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env); var orleansConfiguration = new ClusterConfiguration(); orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId; var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config); _silo = new AzureSilo(); var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString); if (!started) { throw new InvalidOperationException("Silo was not started."); } conreignSilo.Initialize(); _silo.Run(); } public override void OnStop() { _silo.Stop(); base.OnStop(); } } }``` Fix Azure host silo startup
```c# using System; using Conreign.Cluster; using Microsoft.WindowsAzure.ServiceRuntime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Host; namespace Conreign.Host.Azure { public class SiloRole : RoleEntryPoint { private AzureSilo _silo; public override void Run() { var env = RoleEnvironment.GetConfigurationSettingValue("Environment"); if (string.IsNullOrEmpty(env)) { throw new InvalidOperationException("Unable to determine environment."); } var config = ConreignSiloConfiguration.Load(Environment.CurrentDirectory, env); var orleansConfiguration = new ClusterConfiguration(); orleansConfiguration.Globals.DeploymentId = RoleEnvironment.DeploymentId; var conreignSilo = ConreignSilo.Configure(orleansConfiguration, config); _silo = new AzureSilo(); var started = _silo.Start(conreignSilo.OrleansConfiguration, conreignSilo.Configuration.SystemStorageConnectionString); if (!started) { throw new InvalidOperationException("Silo was not started."); } _silo.Run(); } public override void OnStop() { _silo.Stop(); base.OnStop(); } } }```
04c4e46a-2b27-404e-a11f-e18c44c80099
{ "language": "C#" }
```c# #region License /********************************************************************************* * CompactSettingWriter.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System.Text; namespace Sandra.UI.WF.Storage { /// <summary> /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON. /// </summary> internal class CompactSettingWriter : PValueVisitor { private readonly StringBuilder outputBuilder = new StringBuilder(); public string Output() => outputBuilder.ToString(); } } ``` Write PBoolean and PInteger values.
```c# #region License /********************************************************************************* * CompactSettingWriter.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System.Globalization; using System.Text; namespace Sandra.UI.WF.Storage { /// <summary> /// Used by <see cref="AutoSave"/> to convert a <see cref="PMap"/> to its compact representation in JSON. /// </summary> internal class CompactSettingWriter : PValueVisitor { private readonly StringBuilder outputBuilder = new StringBuilder(); public override void VisitBoolean(PBoolean value) => outputBuilder.Append(value.Value ? JsonValue.True : JsonValue.False); public override void VisitInteger(PInteger value) => outputBuilder.Append(value.Value.ToString(CultureInfo.InvariantCulture)); public string Output() => outputBuilder.ToString(); } } ```
1bef9388-b0be-4570-a190-992b5a2cb7f2
{ "language": "C#" }
```c# //----------------------------------------------------------------------- // <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation"> // (c) SonarSource SA and Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Sonar.Common; namespace SonarProjectPropertiesGenerator { public class Program { public static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Expected to be called with exactly 4 arguments:"); Console.WriteLine(" 1) SonarQube Project Key"); Console.WriteLine(" 2) SonarQube Project Name"); Console.WriteLine(" 3) SonarQube Project Version"); Console.WriteLine(" 4) Dump folder path"); return 1; } var dumpFolderPath = args[3]; var projects = ProjectLoader.LoadFrom(dumpFolderPath); var contents = PropertiesWriter.ToString(new ConsoleLogger(), args[0], args[1], args[2], projects); File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII); return 0; } } } ``` Include timestamp in generated logs
```c# //----------------------------------------------------------------------- // <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation"> // (c) SonarSource SA and Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Sonar.Common; namespace SonarProjectPropertiesGenerator { public class Program { public static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Expected to be called with exactly 4 arguments:"); Console.WriteLine(" 1) SonarQube Project Key"); Console.WriteLine(" 2) SonarQube Project Name"); Console.WriteLine(" 3) SonarQube Project Version"); Console.WriteLine(" 4) Dump folder path"); return 1; } var dumpFolderPath = args[3]; var projects = ProjectLoader.LoadFrom(dumpFolderPath); var contents = PropertiesWriter.ToString(new ConsoleLogger(includeTimestamp: true), args[0], args[1], args[2], projects); File.WriteAllText(Path.Combine(dumpFolderPath, "sonar-project.properties"), contents, Encoding.ASCII); return 0; } } } ```
c4193874-8388-49f3-9db7-7237f2c60320
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")] ``` Increase node agent version in preperation for the release
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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.7.0")] [assembly: AssemblyFileVersion("1.0.7.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")] ```
8b7181f4-03d8-4e99-a55a-03cc72149d04
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using AxeSoftware.Quest; namespace EditorControllerTests { [TestClass] public class TemplateTests { [TestMethod] public void TestTemplates() { string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\"); string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\WorldModel\WorldModel\Core"); Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder); foreach (string template in templates.Values) { string tempFile = System.IO.Path.GetTempFileName(); EditorController.CreateNewGameFile(tempFile, template, "Test"); EditorController controller = new EditorController(); string errorsRaised = string.Empty; controller.ShowMessage += (string message) => { errorsRaised += message; }; bool result = controller.Initialise(tempFile, templateFolder); Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); System.IO.File.Delete(tempFile); } } } } ``` Fix unit tests, not sure why file paths have changed?
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using AxeSoftware.Quest; namespace EditorControllerTests { [TestClass] public class TemplateTests { [TestMethod] public void TestTemplates() { string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Substring(6).Replace("/", @"\"); string templateFolder = System.IO.Path.Combine(folder, @"..\..\..\..\WorldModel\WorldModel\Core"); Dictionary<string, string> templates = EditorController.GetAvailableTemplates(templateFolder); foreach (string template in templates.Values) { string tempFile = System.IO.Path.GetTempFileName(); EditorController.CreateNewGameFile(tempFile, template, "Test"); EditorController controller = new EditorController(); string errorsRaised = string.Empty; controller.ShowMessage += (string message) => { errorsRaised += message; }; bool result = controller.Initialise(tempFile, templateFolder); Assert.IsTrue(result, string.Format("Initialisation failed for template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); Assert.AreEqual(0, errorsRaised.Length, string.Format("Error loading game with template '{0}': {1}", System.IO.Path.GetFileName(template), errorsRaised)); System.IO.File.Delete(tempFile); } } } } ```
3a87fce8-b746-439a-8909-be6803f7f0ba
{ "language": "C#" }
```c# using System.IO; using System.Threading.Tasks; namespace TestCaseAutomator.TeamFoundation { /// <summary> /// Represents a TFS source controlled file. /// </summary> public class TfsFile : TfsSourceControlledItem { /// <summary> /// Initializes a new <see cref="TfsFile"/>. /// </summary> /// <param name="fileItem">The source controlled file</param> /// <param name="versionControl">TFS source control</param> public TfsFile(IVersionedItem fileItem, IVersionControl versionControl) : base(fileItem, versionControl) { } /// <summary> /// Downloads a file to a given file path. /// </summary> /// <param name="path">The local path to download to</param> public async Task DownloadToAsync(string path) { var downloadStream = Download(); var directoryPath = Path.GetDirectoryName(path); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); using (var fileStream = File.OpenWrite(path)) await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); } } }``` Put download stream in using statement (doesn't seem to have any effect though).
```c# using System.IO; using System.Threading.Tasks; namespace TestCaseAutomator.TeamFoundation { /// <summary> /// Represents a TFS source controlled file. /// </summary> public class TfsFile : TfsSourceControlledItem { /// <summary> /// Initializes a new <see cref="TfsFile"/>. /// </summary> /// <param name="fileItem">The source controlled file</param> /// <param name="versionControl">TFS source control</param> public TfsFile(IVersionedItem fileItem, IVersionControl versionControl) : base(fileItem, versionControl) { } /// <summary> /// Downloads a file to a given file path. /// </summary> /// <param name="path">The local path to download to</param> public async Task DownloadToAsync(string path) { var directoryPath = Path.GetDirectoryName(path); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); using (var downloadStream = Download()) using (var fileStream = File.OpenWrite(path)) await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); } } }```
a40613be-8edf-4105-8f4b-1cc62d858f7c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MakerFarm.Models { public class MakerfarmDBContext : DbContext { public MakerfarmDBContext() : base("DefaultConnection") { //Database.SetInitializer<MakerfarmDBContext>(new DropCreateDatabaseIfModelChanges<MakerfarmDBContext>()); } public DbSet<PrinterType> PrinterTypes { get; set; } public DbSet<PrintEvent> PrintEvents { get; set; } public DbSet<Print> Prints { get; set; } public DbSet<Material> Materials { get; set; } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<PrintErrorType> PrintErrorTypes { get; set; } public DbSet<Printer> Printers { get; set; } public DbSet<PrinterStatusLog> PrinterStatusLogs { set; get; } } }``` Set the DB Context to rebuild database when a model change is detected. Dangerous times for data =O
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MakerFarm.Models { public class MakerfarmDBContext : DbContext { public MakerfarmDBContext() : base("DefaultConnection") { Database.SetInitializer<MakerfarmDBContext>(new DropCreateDatabaseIfModelChanges<MakerfarmDBContext>()); } public DbSet<PrinterType> PrinterTypes { get; set; } public DbSet<PrintEvent> PrintEvents { get; set; } public DbSet<Print> Prints { get; set; } public DbSet<Material> Materials { get; set; } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<PrintErrorType> PrintErrorTypes { get; set; } public DbSet<Printer> Printers { get; set; } public DbSet<PrinterStatusLog> PrinterStatusLogs { set; get; } } }```
7bc50ada-4454-453d-8ad0-55f6961a9476
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroSequence : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; public TestSceneIntroSequence() { OsuLogo logo; var rateAdjustClock = new StopwatchClock(true); var framedClock = new FramedClock(rateAdjustClock); framedClock.ProcessFrame(); Add(new Container { RelativeSizeAxes = Axes.Both, Clock = framedClock, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, logo = new OsuLogo { Anchor = Anchor.Centre, } } }); AddStep(@"Restart", logo.PlayIntro); AddSliderStep("Playback speed", 0.0, 2.0, 1, v => rateAdjustClock.Rate = v); } } } ``` Change intro test to test full intro screen
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Timing; using osu.Game.Screens; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneIntroSequence : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), typeof(Intro), typeof(StartupScreen), typeof(OsuScreen) }; [Cached] private OsuLogo logo; public TestSceneIntroSequence() { var rateAdjustClock = new StopwatchClock(true); var framedClock = new FramedClock(rateAdjustClock); framedClock.ProcessFrame(); Add(new Container { RelativeSizeAxes = Axes.Both, Clock = framedClock, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, new OsuScreenStack(new Intro()) { RelativeSizeAxes = Axes.Both, }, logo = new OsuLogo { Anchor = Anchor.Centre, }, } }); AddSliderStep("Playback speed", 0.0, 2.0, 1, v => rateAdjustClock.Rate = v); } } } ```
61950a3a-5dd2-43f2-9ddb-8e6dff8b13f6
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace borkedLabs.CrestScribe { public class ScribeQueryWorker { private BlockingCollection<SsoCharacter> _queryQueue; private CancellationToken _cancelToken; public Thread Thread { get; private set; } public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken) { _queryQueue = queryQueue; _cancelToken = cancelToken; Thread = new Thread(_worker); Thread.Name = "scribe query worker"; Thread.IsBackground = true; } public void Start() { Thread.Start(); } private void _worker() { while (!_cancelToken.IsCancellationRequested) { var character = _queryQueue.Take(_cancelToken); if(character != null) { var t = Task.Run(character.Poll); t.Wait(); } } } } } ``` Use cancellationToken properly in task wait.
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace borkedLabs.CrestScribe { public class ScribeQueryWorker { private BlockingCollection<SsoCharacter> _queryQueue; private CancellationToken _cancelToken; public Thread Thread { get; private set; } public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken) { _queryQueue = queryQueue; _cancelToken = cancelToken; Thread = new Thread(_worker); Thread.Name = "scribe query worker"; Thread.IsBackground = true; } public void Start() { Thread.Start(); } private void _worker() { while (!_cancelToken.IsCancellationRequested) { var character = _queryQueue.Take(_cancelToken); if(character != null) { var t = Task.Run(character.Poll); t.Wait(_cancelToken); } } } } } ```
dca1bc36-2206-47b2-8140-cad0abec91a9
{ "language": "C#" }
```c# using CefSharp; using TweetDuck.Core.Controls; using TweetDuck.Core.Utils; namespace TweetDuck.Core.Handling.General{ sealed class LifeSpanHandler : ILifeSpanHandler{ public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl){ switch(targetDisposition){ case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup: case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser){ newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser){} public bool DoClose(IWebBrowser browserControl, IBrowser browser){ return false; } public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser){} } } ``` Enable popup for linking another account
```c# using CefSharp; using TweetDuck.Core.Controls; using TweetDuck.Core.Utils; namespace TweetDuck.Core.Handling.General{ sealed class LifeSpanHandler : ILifeSpanHandler{ private static bool IsPopupAllowed(string url){ return url.StartsWith("https://twitter.com/teams/authorize?"); } public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl){ switch(targetDisposition){ case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl): case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser){ newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser){} public bool DoClose(IWebBrowser browserControl, IBrowser browser){ return false; } public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser){} } } ```
804d0f02-cd25-434d-bb44-f8aa24557d2f
{ "language": "C#" }
```c# using System; using System.Linq; public class Bob { public string Hey(string input) { if (IsSilence(input)) { return "Fine. Be that way!"; } else if (IsShouting(input)) { return "Whoa, chill out!"; } else if (IsQuestion(input)) { return "Sure."; } else { return "Whatever."; } } private bool IsSilence(string input) { return input.Trim().Length == 0; } private bool IsQuestion(string input) { // last character is a question mark, ignoring trailing spaces input = input.Trim(); return input.LastIndexOf('?') == input.Length - 1; } private bool IsShouting(string input) { // has at least 1 character, and all upper case var alphas = input.Where(char.IsLetter); return alphas.Any() && alphas.All(char.IsUpper); } }``` Use EndsWith - nicer than LastIndexOf...
```c# using System.Linq; public class Bob { public string Hey(string input) { if (IsSilence(input)) { return "Fine. Be that way!"; } else if (IsShouting(input)) { return "Whoa, chill out!"; } else if (IsQuestion(input)) { return "Sure."; } else { return "Whatever."; } } private bool IsSilence(string input) { return input.Trim().Length == 0; } private bool IsQuestion(string input) { // last character is a question mark, ignoring trailing spaces return input.Trim().EndsWith("?"); } private bool IsShouting(string input) { // has at least 1 character, and all upper case var alphas = input.Where(char.IsLetter); return alphas.Any() && alphas.All(char.IsUpper); } }```
28970643-6d68-4e8a-87c6-557097a162b6
{ "language": "C#" }
```c# using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPMin { public class SPMinLoggingService : SPDiagnosticsServiceBase { private static string AreaName = "Mavention"; private static SPMinLoggingService _instance; public static SPMinLoggingService Current { get { if (_instance == null) _instance = new SPMinLoggingService(); return _instance; } } private SPMinLoggingService() : base("SPMin Logging Service", SPFarm.Local) { } protected override IEnumerable<SPDiagnosticsArea> ProvideAreas() { List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea> { new SPDiagnosticsArea(AreaName, new List<SPDiagnosticsCategory> { new SPDiagnosticsCategory("SPMin", TraceSeverity.Unexpected, EventSeverity.Error) }) }; return areas; } public static void LogError(string errorMessage, TraceSeverity traceSeverity) { SPDiagnosticsCategory category = Current.Areas[AreaName].Categories["SPMin"]; Current.WriteTrace(0, category, traceSeverity, errorMessage); } } } ``` Update logging service area name
```c# using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPMin { public class SPMinLoggingService : SPDiagnosticsServiceBase { private static string AreaName = "SPMin"; private static SPMinLoggingService _instance; public static SPMinLoggingService Current { get { if (_instance == null) _instance = new SPMinLoggingService(); return _instance; } } private SPMinLoggingService() : base("SPMin Logging Service", SPFarm.Local) { } protected override IEnumerable<SPDiagnosticsArea> ProvideAreas() { List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea> { new SPDiagnosticsArea(AreaName, new List<SPDiagnosticsCategory> { new SPDiagnosticsCategory("SPMin", TraceSeverity.Unexpected, EventSeverity.Error) }) }; return areas; } public static void LogError(string errorMessage, TraceSeverity traceSeverity) { SPDiagnosticsCategory category = Current.Areas[AreaName].Categories["SPMin"]; Current.WriteTrace(0, category, traceSeverity, errorMessage); } } } ```
c4e91a58-add4-4afe-a4bc-d6a67125904f
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("OxyPlot")] [assembly: AssemblyCompany("OxyPlot")] [assembly: AssemblyCopyright("Copyright (c) 2014 OxyPlot contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The version numbers are updated by the build script. See ~/appveyor.yml [assembly: AssemblyVersion("0.0.0")] [assembly: AssemblyInformationalVersion("0.0.0-alpha")] [assembly: AssemblyFileVersion("0.0.0")]``` Fix CA1016: Mark assemblies with AssemblyVersionAttribute
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("OxyPlot")] [assembly: AssemblyCompany("OxyPlot")] [assembly: AssemblyCopyright("Copyright (c) 2014 OxyPlot contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The version numbers are updated by the build script. See ~/appveyor.yml [assembly: AssemblyVersion("0.0.1")] [assembly: AssemblyInformationalVersion("0.0.1-alpha")] [assembly: AssemblyFileVersion("0.0.1")]```
dc641564-f204-466a-9885-26f60091a4b1
{ "language": "C#" }
```c# using System.Collections; using UnityEngine; namespace TrailAdvanced.PointSource { public class ObjectPointSource : AbstractPointSource { public Transform objectToFollow; protected override void Update() { base.Update(); points.AddToBack(objectToFollow.position); } } }``` Add points to front and only add if moved a little bit
```c# using System.Collections; using UnityEngine; namespace TrailAdvanced.PointSource { public class ObjectPointSource : AbstractPointSource { public Transform objectToFollow; private Vector3 _lastPosition; protected override void Start() { base.Start(); _lastPosition = objectToFollow.position; } protected override void Update() { base.Update(); float distance = Vector3.SqrMagnitude(objectToFollow.position - _lastPosition); if (distance > 0.0001f) { points.AddToFront(objectToFollow.position); } _lastPosition = objectToFollow.position; } } } ```
13d2ae0b-4eb3-48cf-8d9c-47a4c3e7dbd2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SourceBrowser.Search.ViewModels { public struct TokenViewModel { public string Id { get; } public string Path { get; } public string Username { get; } public string Repository { get; } public string FullName { get; } public string Name { get { if (FullName == null) return null; var splitName = FullName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); return splitName.Last(); } } public int LineNumber { get; } public TokenViewModel(string username, string repository, string path, string fullName, int lineNumber) { Id = System.IO.Path.Combine(username, repository, fullName); Username = username; Repository = repository; Path = path; FullName = fullName; LineNumber = lineNumber; } } } ``` Handle parenthese in method name.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SourceBrowser.Search.ViewModels { public struct TokenViewModel { public string Id { get; } public string Path { get; } public string Username { get; } public string Repository { get; } public string FullName { get; } public string Name { get { if (FullName == null) return null; string currentName = FullName; var parensIndex = FullName.IndexOf("("); if(parensIndex != -1) { currentName = currentName.Remove(parensIndex, currentName.Length - parensIndex); } var splitName = currentName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); return splitName.Last(); } } public int LineNumber { get; } public TokenViewModel(string username, string repository, string path, string fullName, int lineNumber) { Id = username + "/" + repository + "/" + fullName; Username = username; Repository = repository; Path = path; FullName = fullName; LineNumber = lineNumber; } } } ```
05d77a68-9c80-4795-a93b-80a8264602eb
{ "language": "C#" }
```c# using System; using BenchmarkDotNet.Running; namespace LanguageExt.Benchmarks { class Program { static void Main(string[] args) { var summary1 = BenchmarkRunner.Run<HashMapAddBenchmark>(); Console.Write(summary1); var summary2 = BenchmarkRunner.Run<HashMapRandomReadBenchmark>(); Console.Write(summary2); } } } ``` Change way how benchmarks are discovered/executed
```c# using BenchmarkDotNet.Running; namespace LanguageExt.Benchmarks { class Program { static void Main(string[] args) => BenchmarkSwitcher .FromAssembly(typeof(Program).Assembly) .Run(args); } } ```
214cb70e-0f8a-4ff9-8411-c2bebe35ff83
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Dictator { public class Rule { public string FieldPath { get; set; } public Constraint Constraint { get; set; } public List<object> Parameters { get; set; } public bool IsViolated { get; set; } public string Message { get; set; } public Rule() { Parameters = new List<object>(); Message = string.Format("Field '{0}' violated '{1}' constraint rule.", FieldPath, Constraint); } } } ``` Fix default schema rule message.
```c# using System.Collections.Generic; namespace Dictator { public class Rule { string _message = null; public string FieldPath { get; set; } public Constraint Constraint { get; set; } public List<object> Parameters { get; set; } public bool IsViolated { get; set; } public string Message { get { if (_message == null) { return string.Format("Field '{0}' violated '{1}' constraint rule.", FieldPath, Constraint); } return _message; } set { _message = value; } } public Rule() { Parameters = new List<object>(); } } } ```
5818b3ca-5c50-49fb-9e97-90a767fa8329
{ "language": "C#" }
```c# using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Abc.NCrafts.Quizz.Performance.Questions._021 { public class Answer2 { public static void Run() { var queue = new ConcurrentStack<int>(); // begin var producer = Task.Run(() => { foreach (var value in Enumerable.Range(1, 10000)) { queue.Push(value); } }); var consumer = Task.Run(() => { var spinWait = new SpinWait(); var value = 0; while (value != 10000) { if (!queue.TryPop(out value)) { spinWait.SpinOnce(); continue; } Logger.Log("Value: {0}", value); } }); Task.WaitAll(producer, consumer); // end } } }``` Rename queue to stack to reflect its actual type
```c# using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Abc.NCrafts.Quizz.Performance.Questions._021 { public class Answer2 { public static void Run() { var stack = new ConcurrentStack<int>(); // begin var producer = Task.Run(() => { foreach (var value in Enumerable.Range(1, 10000)) { stack.Push(value); } }); var consumer = Task.Run(() => { var spinWait = new SpinWait(); var value = 0; while (value != 10000) { if (!stack.TryPop(out value)) { spinWait.SpinOnce(); continue; } Logger.Log("Value: {0}", value); } }); Task.WaitAll(producer, consumer); // end } } }```
de0f7085-fbcf-4276-b0ec-2dbc2fa5f8fb
{ "language": "C#" }
```c# namespace Nancy.AttributeRouting { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Bootstrapper; using Nancy.TinyIoc; /// <inheritdoc/> public class AttributeRoutingRegistration : IRegistrations { static AttributeRoutingRegistration() { IEnumerable<MethodBase> methods = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.SafeGetTypes()) .Where(type => !type.IsAbstract && (type.IsPublic || type.IsNestedPublic)) .SelectMany(GetMethodsWithRouteAttribute); foreach (MethodBase method in methods) { AttributeRoutingResolver.Routings.Register(method); } } /// <inheritdoc/> public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<TypeRegistration> TypeRegistrations { get { yield return new TypeRegistration(typeof(IUrlBuilder), typeof(UrlBuilder)); } } private static IEnumerable<MethodBase> GetMethodsWithRouteAttribute(Type type) { IEnumerable<MethodBase> methods = type .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(HasRouteAttribute); return methods; } private static bool HasRouteAttribute(MethodBase method) { return method.GetCustomAttributes<RouteAttribute>().Any(); } } } ``` Modify routing initialization logic to pass test case.
```c# namespace Nancy.AttributeRouting { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Bootstrapper; using Nancy.TinyIoc; /// <inheritdoc/> public class AttributeRoutingRegistration : IRegistrations { static AttributeRoutingRegistration() { IEnumerable<MethodBase> methods = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.SafeGetTypes()) .Where(DoesSupportType) .SelectMany(GetMethodsWithRouteAttribute); foreach (MethodBase method in methods) { AttributeRoutingResolver.Routings.Register(method); } } /// <inheritdoc/> public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } /// <inheritdoc/> public IEnumerable<TypeRegistration> TypeRegistrations { get { yield return new TypeRegistration(typeof(IUrlBuilder), typeof(UrlBuilder)); } } private static IEnumerable<MethodBase> GetMethodsWithRouteAttribute(Type type) { IEnumerable<MethodBase> methods = type .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(HasRouteAttribute); return methods; } private static bool HasRouteAttribute(MethodBase method) { return method.GetCustomAttributes<RouteAttribute>().Any(); } private static bool DoesSupportType(Type type) { if (type.IsInterface) { return true; } else if (!type.IsAbstract && (type.IsPublic || type.IsNestedPublic)) { return true; } else { return false; } } } } ```
2af35c4f-5845-44cd-bff3-776914cfd95c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class SpriteShadow : MonoBehaviour { public Sprite ShadowSprite; public float ShadowDist = 0.1f; public bool UseParentSpr = true; public Transform MyTr { get; private set; } public SpriteRenderer MySpr { get; private set; } public SpriteRenderer ParentSpr { get; private set; } private void Awake() { MyTr = transform; ParentSpr = MyTr.parent.GetComponent<SpriteRenderer>(); MySpr = GetComponent<SpriteRenderer>(); } private void LateUpdate() { Vector2 lightDir = ((Vector2)Water.Instance.LightDir).normalized; MyTr.position = MyTr.parent.position - (Vector3)(lightDir * ShadowDist); if (UseParentSpr) ShadowSprite = ParentSpr.sprite; MySpr.sprite = ShadowSprite; } }``` Fix shadow bug with mines exploding
```c# using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class SpriteShadow : MonoBehaviour { public Sprite ShadowSprite; public float ShadowDist = 0.1f; public bool UseParentSpr = true; public Transform MyTr { get; private set; } public SpriteRenderer MySpr { get; private set; } public SpriteRenderer ParentSpr { get; private set; } private void Awake() { MyTr = transform; ParentSpr = MyTr.parent.GetComponent<SpriteRenderer>(); MySpr = GetComponent<SpriteRenderer>(); } private void LateUpdate() { if (!ParentSpr.enabled) { MySpr.enabled = false; return; } Vector2 lightDir = ((Vector2)Water.Instance.LightDir).normalized; MyTr.position = MyTr.parent.position - (Vector3)(lightDir * ShadowDist); if (UseParentSpr) ShadowSprite = ParentSpr.sprite; MySpr.sprite = ShadowSprite; } }```
de7805cd-58ea-49b7-99c4-c97370dd8ffa
{ "language": "C#" }
```c# namespace Codestellation.Pulsar.Cron { public struct IntegerIndex { public const int NotFound = -1; private readonly int[] _indexArray; public IntegerIndex(SimpleCronField field) { _indexArray = new int[field.Settings.MaxValue + 1]; for (int i = 0; i < _indexArray.Length; i++) { _indexArray[i] = NotFound; } foreach (var value in field.Values) { _indexArray[value] = value; } int next = NotFound; for (int i = _indexArray.Length - 1; i >= 0; i--) { var val = _indexArray[i]; if (val != NotFound) { next = val; } _indexArray[i] = next; } } public int GetValue(int value) { return _indexArray[value]; } } }``` Use sbyte in integer index
```c# namespace Codestellation.Pulsar.Cron { public struct IntegerIndex { public const sbyte NotFound = -1; private readonly sbyte[] _indexArray; public IntegerIndex(SimpleCronField field) { _indexArray = new sbyte[field.Settings.MaxValue + 1]; for (int i = 0; i < _indexArray.Length; i++) { _indexArray[i] = NotFound; } foreach (var value in field.Values) { _indexArray[value] = (sbyte)value; } int next = NotFound; for (int i = _indexArray.Length - 1; i >= 0; i--) { var val = _indexArray[i]; if (val != NotFound) { next = val; } _indexArray[i] = (sbyte)next; } } public int GetValue(int value) { return _indexArray[value]; } } }```
023dfbc8-fc64-419f-8e9c-81e88db61093
{ "language": "C#" }
```c# namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class SubscriptionItemUpdateOptions : SubscriptionItemSharedOptions { /// <summary> /// A set of key/value pairs that you can attach to a subscription object. It can be useful for storing additional information about the subscription in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// Use <c>error_if_incomplete</c> if you want Stripe to return an HTTP 402 status code if /// the invoice caused by the update cannot be paid. Otherwise use <c>allow_incomplete</c>. /// </summary> [JsonProperty("payment_behavior")] public string PaymentBehavior { get; set; } } } ``` Add OffSession on SubscriptionItem update
```c# namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class SubscriptionItemUpdateOptions : SubscriptionItemSharedOptions { /// <summary> /// A set of key/value pairs that you can attach to a subscription object. It can be useful for storing additional information about the subscription in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// Indicates if your customer is on session in case this update causes an invoice to /// be created. /// </summary> [JsonProperty("off_session")] public bool? OffSession { get; set; } /// <summary> /// Use <c>error_if_incomplete</c> if you want Stripe to return an HTTP 402 status code if /// the invoice caused by the update cannot be paid. Otherwise use <c>allow_incomplete</c>. /// </summary> [JsonProperty("payment_behavior")] public string PaymentBehavior { get; set; } } } ```
8817e6a2-6aa5-4018-801e-fb26d634fd1b
{ "language": "C#" }
```c# namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }``` Increment version number to 1.3.5.1
```c# namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.1"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }```
da04bf9f-f677-4944-9d9c-0146d8be23f2
{ "language": "C#" }
```c# @using StackExchange.Opserver.Models @using StackExchange.Profiling @{ Layout = null; } @helper RenderTab(TopTab tab) { if (tab.IsEnabled) { // Optimism! using (MiniProfiler.Current.Step("Render Tab: " + tab.Name)) { var status = tab.GetMonitorStatus?.Invoke() ?? MonitorStatus.Good; var badgeCount = tab.GetBadgeCount?.Invoke(); <li class="@(tab.IsCurrentTab ? "active" : null)"> <a class="@(status.TextClass())" href="@tab.Url" title="@(tab.GetTooltip?.Invoke())"> @tab.Name @if (badgeCount > 0) { <span class="badge" data-name="@tab.Name">@badgeCount.ToComma()</span> } </a> </li> } } } @if (!TopTabs.HideAll) { using (MiniProfiler.Current.Step("TopTabs")) { <ul class="nav navbar-nav navbar-right js-top-tabs"> @foreach (var tab in TopTabs.Tabs.Values) { @RenderTab(tab) } </ul> } } ``` Make tab colors work and stuff
```c# @using StackExchange.Opserver.Models @using StackExchange.Profiling @{ Layout = null; } @helper RenderTab(TopTab tab) { if (tab.IsEnabled) { // Optimism! using (MiniProfiler.Current.Step("Render Tab: " + tab.Name)) { var status = tab.GetMonitorStatus?.Invoke() ?? MonitorStatus.Good; var badgeCount = tab.GetBadgeCount?.Invoke(); <li class="@(tab.IsCurrentTab ? "active" : null)"> <a href="@tab.Url" title="@(tab.GetTooltip?.Invoke())"> <span class="@(status.TextClass())">@tab.Name</span> @if (badgeCount > 0) { <span class="badge" data-name="@tab.Name">@badgeCount.ToComma()</span> } </a> </li> } } } @if (!TopTabs.HideAll) { using (MiniProfiler.Current.Step("TopTabs")) { <ul class="nav navbar-nav navbar-right js-top-tabs"> @foreach (var tab in TopTabs.Tabs.Values) { @RenderTab(tab) } </ul> } } ```
7b3364a0-5cbb-417b-93a4-a2418220c0d8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace MuffinFramework { public abstract class LayerBase<TArgs> : ILayerBase<TArgs> { private readonly object _lockObj = new object(); private readonly List<ILayerBase<TArgs>> _parts = new List<ILayerBase<TArgs>>(); private TArgs _args; public bool IsEnabled { get; private set; } public virtual void Enable(TArgs args) { lock (this._lockObj) { if (this.IsEnabled) throw new InvalidOperationException("LayerBase has already been enabled."); this.IsEnabled = true; } this._args = args; this.Enable(); } protected abstract void Enable(); protected TPart EnablePart<TPart, TProtocol>(TProtocol host) where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var part = new TPart(); part.Enable(host, this._args); this._parts.Add(part); return part; } protected TPart EnablePart<TPart, TProtocol>() where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var host = (TProtocol) (object) this; return this.EnablePart<TPart, TProtocol>(host); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; foreach (var part in this._parts) { part.Dispose(); } } } } ``` Fix EnablePart is not threadsafe
```c# using System; using System.Collections.Generic; namespace MuffinFramework { public abstract class LayerBase<TArgs> : ILayerBase<TArgs> { private readonly object _lockObj = new object(); private readonly List<ILayerBase<TArgs>> _parts = new List<ILayerBase<TArgs>>(); private TArgs _args; public bool IsEnabled { get; private set; } public virtual void Enable(TArgs args) { lock (this._lockObj) { if (this.IsEnabled) throw new InvalidOperationException("LayerBase has already been enabled."); this.IsEnabled = true; } this._args = args; this.Enable(); } protected abstract void Enable(); protected TPart EnablePart<TPart, TProtocol>(TProtocol host) where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var part = new TPart(); part.Enable(host, this._args); lock (this._lockObj) { this._parts.Add(part); } return part; } protected TPart EnablePart<TPart, TProtocol>() where TPart : class, ILayerPart<TProtocol, TArgs>, new() { var host = (TProtocol) (object) this; return this.EnablePart<TPart, TProtocol>(host); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing) return; ILayerBase<TArgs>[] parts; lock (this._lockObj) { parts = this._parts.ToArray(); } foreach (var part in parts) { part.Dispose(); } } } } ```
f536acd1-0f43-4304-b935-6dd3f66a1106
{ "language": "C#" }
```c# using CrossPlatformTintedImage; using CrossPlatformTintedImage.iOS; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image != null && Element != null) { Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage) Element).TintColor.ToUIColor(); } } } }``` Disable tinting option on iOS
```c# using CrossPlatformTintedImage; using CrossPlatformTintedImage.iOS; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly:ExportRendererAttribute(typeof(TintedImage), typeof(TintedImageRenderer))] namespace CrossPlatformTintedImage.iOS { public class TintedImageRenderer : ImageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); SetTint(); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == TintedImage.TintColorProperty.PropertyName) SetTint(); } void SetTint() { if (Control?.Image == null || Element == null) return; if (((TintedImage)Element).TintColor == Color.Transparent) { //Turn off tinting Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.Automatic); Control.TintColor = null; } else { //Apply tint color Control.Image = Control.Image.ImageWithRenderingMode(UIKit.UIImageRenderingMode.AlwaysTemplate); Control.TintColor = ((TintedImage)Element).TintColor.ToUIColor(); } } } }```
de965815-220f-4c7c-83c3-555356ae2831
{ "language": "C#" }
```c# namespace QtWebKit { using Qyoto; using System; using System.Runtime.InteropServices; public class InitQtWebKit { [DllImport("libqtwebkit-sharp", CharSet=CharSet.Ansi)] static extern void Init_qtwebkit(); public static void InitSmoke() { Init_qtwebkit(); } } } ``` Remove the 'lib' prefix for the native lib.
```c# namespace QtWebKit { using Qyoto; using System; using System.Runtime.InteropServices; public class InitQtWebKit { [DllImport("qtwebkit-sharp", CharSet=CharSet.Ansi)] static extern void Init_qtwebkit(); public static void InitSmoke() { Init_qtwebkit(); } } } ```
866d9fe0-a902-4349-a9fe-9a0832087419
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { public LegacyHitExplosion(Drawable sprite) { InternalChild = sprite; Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); } } } ``` Fix skinned taiko hit explosions not being removed on rewind
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { public LegacyHitExplosion(Drawable sprite) { InternalChild = sprite; Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); Expire(true); } } } ```
bfd8c2b9-54f4-46f7-87d3-204c5311937e
{ "language": "C#" }
```c# using EarTrumpet.Extensions; using System; using System.Windows; using System.Windows.Controls; namespace EarTrumpet.UI.Behaviors { public class TextBoxEx { // ClearText: Clear TextBox or the parent ComboBox. public static bool GetClearText(DependencyObject obj) => (bool)obj.GetValue(ClearTextProperty); public static void SetClearText(DependencyObject obj, bool value) => obj.SetValue(ClearTextProperty, value); public static readonly DependencyProperty ClearTextProperty = DependencyProperty.RegisterAttached("ClearText", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, ClearTextChanged)); private static void ClearTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue == true) { var parent = dependencyObject.FindVisualParent<ComboBox>(); if (parent != null) { parent.Text = ""; parent.SelectedItem = null; } else { ((TextBox)dependencyObject).Text = ""; } } } } } ``` Fix (from SearchBox): Hotkeys are cleared constantly
```c# using EarTrumpet.Extensions; using System; using System.Windows; using System.Windows.Controls; namespace EarTrumpet.UI.Behaviors { public class TextBoxEx { // ClearText: Clear TextBox or the parent ComboBox. public static bool GetClearText(DependencyObject obj) => (bool)obj.GetValue(ClearTextProperty); public static void SetClearText(DependencyObject obj, bool value) => obj.SetValue(ClearTextProperty, value); public static readonly DependencyProperty ClearTextProperty = DependencyProperty.RegisterAttached("ClearText", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, ClearTextChanged)); private static void ClearTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue == true) { var parent = dependencyObject.FindVisualParent<ComboBox>(); if (parent != null) { parent.Text = ""; parent.SelectedItem = null; } else { // Ignore !IsLoaded to cleverly allow IsPressed=False to be our trigger but also // don't clear TextBoxes when they are initially created. var textBox = ((TextBox)dependencyObject); if (textBox.IsLoaded) { textBox.Text = ""; } } } } } } ```
9a12ddde-e5a8-450d-8933-96bf62ecd824
{ "language": "C#" }
```c# using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Models.ViewModels.Extensions { public static class ConfigurationExtensions { public static IServiceCollection AddViewModels(this IServiceCollection services) { services.AddSingleton<IViewModelTypeProvider, ViewModelTypeProvider>(); services.AddTransient<IViewModelGenerator, ViewModelGenerator>(); return services; } } }``` Change IViewModelGenerator implementation registration type from Transient to Singleton.
```c# using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Models.ViewModels.Extensions { public static class ConfigurationExtensions { public static IServiceCollection AddViewModels(this IServiceCollection services) { services.AddSingleton<IViewModelTypeProvider, ViewModelTypeProvider>(); services.AddSingleton<IViewModelGenerator, ViewModelGenerator>(); return services; } } }```
4faf54b3-f4bb-4ed6-b808-1453c7e33d4d
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log("⏳ Currently loading components"); foreach (var c in loading_components) Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}"); loading_components.Clear(); } } } } ``` Add count to loading components logging
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components) Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}"); loading_components.Clear(); } } } } ```
fda47bdc-c412-46dc-95b7-f84bc6054855
{ "language": "C#" }
```c# using System.Web.Routing; using SignalR; [assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")] namespace ConsolR.Hosting { public static class Bootstrapper { public static void PreApplicationStart() { var routes = RouteTable.Routes; routes.MapHttpHandler<Handler>("consolr"); routes.MapHttpHandler<Handler>("consolr/validate"); routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}"); } } } ``` Make sure bootstrapper runs pre application start
```c# using System.Web.Routing; using SignalR; [assembly: WebActivator.PreApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")] namespace ConsolR.Hosting { public static class Bootstrapper { public static void PreApplicationStart() { var routes = RouteTable.Routes; routes.MapHttpHandler<Handler>("consolr"); routes.MapHttpHandler<Handler>("consolr/validate"); routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}"); } } } ```
0830d051-f76a-4f82-98f5-70c192a97883
{ "language": "C#" }
```c# namespace SurveyMonkey.RequestSettings { public class CreateCollectorSettings { public enum TypeOption { Weblink, Email } public TypeOption Type { get; set; } public string Name { get; set; } } }``` Implement all properties for collector settings
```c# using System; using SurveyMonkey.Containers; namespace SurveyMonkey.RequestSettings { public class CreateCollectorSettings { public Collector.CollectorType Type { get; set; } public string Name { get; set; } public string ThankYouMessage { get; set; } public string DisqualificationMessage { get; set; } public DateTime? CloseDate { get; set; } public string ClosedPageMessage { get; set; } public string RedirectUrl { get; set; } public bool? DisplaySurveyResults { get; set; } public Collector.EditResponseOption? EditResponseType { get; set; } public Collector.AnonymousOption? AnonymousType { get; set; } public bool? AllowMultipleResponses { get; set; } public string Password { get; set; } public string SenderEmail { get; set; } } }```
3430c6bd-e496-4fff-8bea-37a730134749
{ "language": "C#" }
```c# using System; //Problem 15.* Age after 10 Years //Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years. class AgeAfter10Years { public static int yearsNow; static void Main(string[] args) { Console.Write("Enter birtday year:"); int birthdayYear = int.Parse(Console.ReadLine()); Console.Write("Month:"); int month = int.Parse(Console.ReadLine()); Console.Write("Day"); int day = int.Parse(Console.ReadLine()); DateTime birthday = new DateTime(birthdayYear, month, day); DateTime now = DateTime.Now; Console.WriteLine(CalculateAge(birthday, now)); Console.WriteLine(Add10Years(yearsNow)); } static int CalculateAge(DateTime birthday, DateTime now) { yearsNow = now.Year - birthday.Year; if (birthday.Month > now.Month) { yearsNow--; } if (birthday.Month == now.Month && birthday.Day > now.Day) { yearsNow--; } return yearsNow; } static int Add10Years(int yearsNow) { int yearsAfter10 = yearsNow + 10; return yearsAfter10; } } ``` Make some changes by the solution
```c# using System; //Problem 15.* Age after 10 Years //Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years. class AgeAfter10Years { public static int yearsNow; static void Main(string[] args) { Console.Write("Enter birtday year:"); string[] input = Console.ReadLine().Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries); int month = int.Parse(input[0]); int day = int.Parse(input[1]); int birthdayYear = int.Parse(input[2]); Console.WriteLine(day); if (birthdayYear > DateTime.Now.Year) { Console.WriteLine(0); Console.WriteLine(10); } else { DateTime birthday = new DateTime(birthdayYear, month, day); DateTime now = DateTime.Now; Console.WriteLine(CalculateAge(birthday, now)); Console.WriteLine(Add10Years(yearsNow)); } } static int CalculateAge(DateTime birthday, DateTime now) { yearsNow = now.Year - birthday.Year; if (birthday.Month > now.Month) { yearsNow--; } if (birthday.Month == now.Month && birthday.Day > now.Day) { yearsNow--; } return yearsNow; } static int Add10Years(int yearsNow) { int yearsAfter10 = yearsNow + 10; return yearsAfter10; } } ```
2ee11c98-1254-42a8-8d39-a134a179eed3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Environment { /// <summary> /// Environment interface for Toontown Rewritten. /// </summary> public class TTRWindowsEnvironment : AbstractWindowsEnvironment { private const string ProcessName = "TTREngine"; public static TTRWindowsEnvironment Instance = new TTRWindowsEnvironment(); private TTRWindowsEnvironment() { } public override Process FindProcess() { return FindProcessByName(ProcessName); } } } ``` Fix the singleton instance field.
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Environment { /// <summary> /// Environment interface for Toontown Rewritten. /// </summary> public class TTRWindowsEnvironment : AbstractWindowsEnvironment { private const string ProcessName = "TTREngine"; public static TTRWindowsEnvironment Instance { get; } = new TTRWindowsEnvironment(); private TTRWindowsEnvironment() { } public override Process FindProcess() { return FindProcessByName(ProcessName); } } } ```
539d34ca-ef1f-4f38-a99e-895e9823a087
{ "language": "C#" }
```c# using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.5"; } } ``` Update file version to 2.2.1.6
```c# using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.6"; } } ```
a0b496af-e104-4e95-bcc6-88fee0cda4e3
{ "language": "C#" }
```c# using System.IO; using System.Reflection; using System.Xml.Serialization; namespace IncrementalCompiler { public class Settings { public DebugSymbolFileType DebugSymbolFile; public PrebuiltOutputReuseType PrebuiltOutputReuse; public static Settings Default = new Settings { DebugSymbolFile = DebugSymbolFileType.Mdb, PrebuiltOutputReuse = PrebuiltOutputReuseType.WhenNoChange, }; public static Settings Load() { var fileName = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, ".xml"); if (File.Exists(fileName) == false) return null; using (var stream = new FileStream(fileName, FileMode.Open)) { return Load(stream); } } public static Settings Load(Stream stream) { var deserializer = new XmlSerializer(typeof(Settings)); return (Settings)deserializer.Deserialize(stream); } public static void Save(Stream stream, Settings settings) { var serializer = new XmlSerializer(typeof(Settings)); serializer.Serialize(stream, settings); } } } ``` Use manual xml parsing for fast start-up
```c# using System; using System.IO; using System.Reflection; using System.Xml.Linq; namespace IncrementalCompiler { public class Settings { public DebugSymbolFileType DebugSymbolFile; public PrebuiltOutputReuseType PrebuiltOutputReuse; public static Settings Default = new Settings { DebugSymbolFile = DebugSymbolFileType.Mdb, PrebuiltOutputReuse = PrebuiltOutputReuseType.WhenNoChange, }; public static Settings Load() { var fileName = Path.ChangeExtension(Assembly.GetEntryAssembly().Location, ".xml"); if (File.Exists(fileName) == false) return null; using (var stream = new FileStream(fileName, FileMode.Open)) { return Load(stream); } } public static Settings Load(Stream stream) { // To reduce start-up time, do manual parsing instead of using XmlSerializer var xdoc = XDocument.Load(stream).Element("Settings"); return new Settings { DebugSymbolFile = (DebugSymbolFileType)Enum.Parse(typeof(DebugSymbolFileType), xdoc.Element("DebugSymbolFile").Value), PrebuiltOutputReuse = (PrebuiltOutputReuseType)Enum.Parse(typeof(PrebuiltOutputReuseType), xdoc.Element("PrebuiltOutputReuse").Value), }; } } } ```
8042ff77-a94b-48d1-b635-bf5581e57599
{ "language": "C#" }
```c# using Glimpse.Web; using Microsoft.Framework.Logging; using System; using System.Threading.Tasks; namespace Glimpse.Agent.Web { public class AgentProfiler : IRequestProfiler { private readonly string _requestIdKey = "RequestId"; private readonly IAgentBroker _messageBus; public AgentProfiler(IAgentBroker messageBus, ILoggerFactory loggingFactory) { _messageBus = messageBus; //// TODO: This is a REALLY bad place for this, not sure where else to put it //loggingFactory.AddProvider(new DefaultLoggerProvider(messageBus)); //var test = loggingFactory.Create("test"); //test.Write(LogLevel.Information, 123, new { Test = "test" }, null, (x, y) => { return ""; }); //// TODO: This is a REALLY bad place for this, not sure where else to put it } public async Task Begin(IHttpContext newContext) { var message = new BeginRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } public async Task End(IHttpContext newContext) { var message = new EndRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } } }``` Remove comment no longer needed.
```c# using Glimpse.Web; using Microsoft.Framework.Logging; using System; using System.Threading.Tasks; namespace Glimpse.Agent.Web { public class AgentProfiler : IRequestProfiler { private readonly string _requestIdKey = "RequestId"; private readonly IAgentBroker _messageBus; public AgentProfiler(IAgentBroker messageBus, ILoggerFactory loggingFactory) { _messageBus = messageBus; } public async Task Begin(IHttpContext newContext) { var message = new BeginRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } public async Task End(IHttpContext newContext) { var message = new EndRequestMessage(newContext.Request); // TODO: Full out message more await _messageBus.SendMessage(message); } } }```
7d63fa73-6dfd-42e1-b243-48ad7913a5dd
{ "language": "C#" }
```c# namespace Nancy.Demo.Hosting.Self { using System; using System.Diagnostics; using Nancy.Hosting.Self; class Program { static void Main() { using (var nancyHost = new NancyHost(new Uri("http://localhost:8888/nancy/"), new Uri("http://127.0.0.1:8888/nancy/"), new Uri("http://localhost:8889/nancytoo/"))) { nancyHost.Start(); Console.WriteLine("Nancy now listening - navigating to http://localhost:8888/nancy/. Press enter to stop"); try { Process.Start("http://localhost:8888/nancy/"); } catch (Exception) { } Console.ReadKey(); } Console.WriteLine("Stopped. Good bye!"); } } }``` Change port number 8888 to 8898
```c# namespace Nancy.Demo.Hosting.Self { using System; using System.Diagnostics; using Nancy.Hosting.Self; class Program { static void Main() { using (var nancyHost = new NancyHost(new Uri("http://localhost:8888/nancy/"), new Uri("http://127.0.0.1:8898/nancy/"), new Uri("http://localhost:8889/nancytoo/"))) { nancyHost.Start(); Console.WriteLine("Nancy now listening - navigating to http://localhost:8888/nancy/. Press enter to stop"); try { Process.Start("http://localhost:8888/nancy/"); } catch (Exception) { } Console.ReadKey(); } Console.WriteLine("Stopped. Good bye!"); } } } ```
f0ecacf0-5f4f-4533-87cb-2315137846c3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerfIt { [EventSource(Name = "PerIt!Instrumentation", Guid = "{010380F8-40A7-45C3-B87B-FD4C6CC8700A}")] public class InstrumentationEventSource : EventSource { public static readonly InstrumentationEventSource Instance = new InstrumentationEventSource(); private InstrumentationEventSource() { } [Event(1, Level = EventLevel.Informational)] public void WriteInstrumentationEvent(string categoryName, string instanceName, long timeTakenMilli, string instrumentationContext = null) { this.WriteEvent(1, categoryName, instanceName, timeTakenMilli, instrumentationContext); } } } ``` Remove Guid, fix typo and change to allowed seperator character
```c# using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PerfIt { [EventSource(Name = "PerfIt-Instrumentation")] public class InstrumentationEventSource : EventSource { public static readonly InstrumentationEventSource Instance = new InstrumentationEventSource(); private InstrumentationEventSource() { } [Event(1, Level = EventLevel.Informational)] public void WriteInstrumentationEvent(string categoryName, string instanceName, long timeTakenMilli, string instrumentationContext = null) { this.WriteEvent(1, categoryName, instanceName, timeTakenMilli, instrumentationContext); } } } ```
8b0e56f6-628f-4343-a91a-10ae955f1658
{ "language": "C#" }
```c# @model Tipage.Web.Models.ViewModels.ShiftListViewModel @{ ViewData["Title"] = "Shifts"; } <h2>Shifts</h2> <h3 class="total-tip">@Html.DisplayNameFor(model => model.TotalTips) @Html.DisplayFor(model => model.TotalTips)</h3> <h3 class="total-tip">@Html.DisplayNameFor(model => model.AverageHourlyWage) @Html.DisplayFor(model => model.AverageHourlyWage)</h3> <hr/> <p> <a asp-action="Create">New Shift</a> </p> <table class="table"> <thead> <tr> <th> Date </th> <th> Total Tips </th> </tr> </thead> <tbody> @foreach (var item in Model.Shifts) { <tr> <td> <a asp-action="Details" asp-route-id="@item.Id">@item.Start.ToString("d") (@item.Start.DayOfWeek)</a> </td> <td> @Html.DisplayFor(s => item.TotalTips) </td> </tr> } </tbody> </table>``` Rename "Total Tips" to "Tips"
```c# @model Tipage.Web.Models.ViewModels.ShiftListViewModel @{ ViewData["Title"] = "Shifts"; } <h2>Shifts</h2> <h3 class="total-tip">@Html.DisplayNameFor(model => model.TotalTips) @Html.DisplayFor(model => model.TotalTips)</h3> <h3 class="total-tip">@Html.DisplayNameFor(model => model.AverageHourlyWage) @Html.DisplayFor(model => model.AverageHourlyWage)</h3> <hr/> <p> <a asp-action="Create">New Shift</a> </p> <table class="table"> <thead> <tr> <th> Date </th> <th> Tips </th> </tr> </thead> <tbody> @foreach (var item in Model.Shifts) { <tr> <td> <a asp-action="Details" asp-route-id="@item.Id">@item.Start.ToString("d") (@item.Start.DayOfWeek)</a> </td> <td> @Html.DisplayFor(s => item.TotalTips) </td> </tr> } </tbody> </table>```
ed6b654c-1d3a-4a99-bdd7-fa18464685dc
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Batch : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus { get; set; } [JsonProperty (PropertyName = "object_created")] public string ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public string ObjectUpdated { get; set; } [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner { get; set; } [JsonProperty (PropertyName = "default_carrier_account")] public string DefaultCarrierAccount { get; set; } [JsonProperty (PropertyName = "default_servicelevel_token")] public string DefaultServicelevelToken { get; set; } [JsonProperty (PropertyName = "label_filetype")] public string LabelFiletype { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } [JsonProperty (PropertyName = "batch_shipments")] public object BatchShipments { get; set; } [JsonProperty (PropertyName = "label_url")] public string LabelUrl { get; set; } [JsonProperty (PropertyName = "object_results")] public ObjectResults ObjectResults { get; set; } } } ``` Change LabelUrl property from string to List<String>
```c# using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Batch : ShippoId { [JsonProperty (PropertyName = "object_status")] public string ObjectStatus { get; set; } [JsonProperty (PropertyName = "object_created")] public string ObjectCreated { get; set; } [JsonProperty (PropertyName = "object_updated")] public string ObjectUpdated { get; set; } [JsonProperty (PropertyName = "object_owner")] public string ObjectOwner { get; set; } [JsonProperty (PropertyName = "default_carrier_account")] public string DefaultCarrierAccount { get; set; } [JsonProperty (PropertyName = "default_servicelevel_token")] public string DefaultServicelevelToken { get; set; } [JsonProperty (PropertyName = "label_filetype")] public string LabelFiletype { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } [JsonProperty (PropertyName = "batch_shipments")] public object BatchShipments { get; set; } [JsonProperty (PropertyName = "label_url")] public List<String> LabelUrl { get; set; } [JsonProperty (PropertyName = "object_results")] public ObjectResults ObjectResults { get; set; } } } ```
6b11783a-2d45-4af9-bbd0-bdeb71843b4b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eff.Core { public struct ExceptionLog { public string CallerMemberName; public string CallerFilePath; public int CallerLineNumber; public Exception Exception; } public struct ResultLog { public string CallerMemberName; public string CallerFilePath; public int CallerLineNumber; public object Result; } } ``` Refactor Log objects to class DTOs.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eff.Core { public class ExceptionLog { public string CallerMemberName { get; set; } public string CallerFilePath { get; set; } public int CallerLineNumber { get; set; } public Exception Exception { get; set; } } public class ResultLog { public string CallerMemberName { get; set; } public string CallerFilePath { get; set; } public int CallerLineNumber { get; set; } public object Result { get; set; } } } ```
ba8d4df4-ae63-4bc4-a664-69e90fa39290
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Threading.Tasks; using osu.Framework.Allocation; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which asynchronously loads its children. /// </summary> public class AsyncLoadContainer : Container { /// <summary> /// Called when async loading of children has completed. /// </summary> public Action<AsyncLoadContainer> FinishedLoading; protected override Container<Drawable> Content => content; private readonly Container content = new Container { RelativeSizeAxes = Axes.Both }; private Game game; protected virtual bool ShouldLoadContent => true; [BackgroundDependencyLoader] private void load(Game game) { this.game = game; if (ShouldLoadContent) loadContentAsync(); } protected override void Update() { base.Update(); if (!LoadTriggered && ShouldLoadContent) loadContentAsync(); } private Task loadTask; private void loadContentAsync() { loadTask = content.LoadAsync(game, d => { AddInternal(d); d.FadeInFromZero(150); FinishedLoading?.Invoke(this); }); } protected bool LoadTriggered => loadTask != null; } }``` Remove FadeInFromZero from base class.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Threading.Tasks; using osu.Framework.Allocation; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which asynchronously loads its children. /// </summary> public class AsyncLoadContainer : Container { /// <summary> /// Called when async loading of children has completed. /// </summary> public Action<AsyncLoadContainer> FinishedLoading; protected override Container<Drawable> Content => content; private readonly Container content = new Container { RelativeSizeAxes = Axes.Both }; private Game game; protected virtual bool ShouldLoadContent => true; [BackgroundDependencyLoader] private void load(Game game) { this.game = game; if (ShouldLoadContent) loadContentAsync(); } protected override void Update() { base.Update(); if (!LoadTriggered && ShouldLoadContent) loadContentAsync(); } private Task loadTask; private void loadContentAsync() { loadTask = content.LoadAsync(game, d => { AddInternal(d); FinishedLoading?.Invoke(this); }); } protected bool LoadTriggered => loadTask != null; } }```
d22c9dab-c88d-456a-b0e1-b38727f67512
{ "language": "C#" }
```c# using System; using System.Drawing; namespace TriDevs.TriCraftClassic { class Program { [STAThread] public static void Main(string[] args) { Window window = new Window(1280, 720); window.Run(60.0); } } } ``` Remove STAThread from main function
```c# using System; using System.Drawing; namespace TriDevs.TriCraftClassic { class Program { public static void Main(string[] args) { Window window = new Window(1280, 720); window.Run(60.0); } } } ```
6cba7c3f-3396-4485-8ddf-7c2a8c11dbf5
{ "language": "C#" }
```c# using KenticoInspector.Core.Models; using KenticoInspector.Core.Services.Interfaces; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport<T> : IReport, IWithMetadata<T> where T : new() { protected readonly IReportMetadataService reportMetadataService; public AbstractReport(IReportMetadataService reportMetadataService) { this.reportMetadataService = reportMetadataService; } public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public ReportMetadata<T> Metadata => reportMetadataService.GetReportMetadata<T>(Codename); public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }``` Use field for metadata to prevent reloading every time a term is read
```c# using KenticoInspector.Core.Models; using KenticoInspector.Core.Services.Interfaces; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport<T> : IReport, IWithMetadata<T> where T : new() { private ReportMetadata<T> metadata; protected readonly IReportMetadataService reportMetadataService; public AbstractReport(IReportMetadataService reportMetadataService) { this.reportMetadataService = reportMetadataService; } public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public ReportMetadata<T> Metadata { get { return metadata ?? (metadata = reportMetadataService.GetReportMetadata<T>(Codename)); } } public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }```
b4179464-dfb5-4a68-8e92-78f1a7cca16c
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; namespace osu.Game.Rulesets.Mods { public class ModWindDown : ModTimeRamp { public override string Name => "Wind Down"; public override string Acronym => "WD"; public override string Description => "Sloooow doooown..."; public override IconUsage? Icon => FontAwesome.Solid.ChevronCircleDown; public override double ScoreMultiplier => 1.0; [SettingSource("Initial rate", "The starting speed of the track")] public override BindableNumber<double> InitialRate { get; } = new BindableDouble { MinValue = 1, MaxValue = 1.5, Default = 1, Value = 1, Precision = 0.01, }; [SettingSource("Final rate", "The speed increase to ramp towards")] public override BindableNumber<double> FinalRate { get; } = new BindableDouble { MinValue = 0.5, MaxValue = 0.99, Default = 0.75, Value = 0.75, Precision = 0.01, }; public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(ModWindUp)).ToArray(); } } ``` Make wind down max value 200%
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; namespace osu.Game.Rulesets.Mods { public class ModWindDown : ModTimeRamp { public override string Name => "Wind Down"; public override string Acronym => "WD"; public override string Description => "Sloooow doooown..."; public override IconUsage? Icon => FontAwesome.Solid.ChevronCircleDown; public override double ScoreMultiplier => 1.0; [SettingSource("Initial rate", "The starting speed of the track")] public override BindableNumber<double> InitialRate { get; } = new BindableDouble { MinValue = 1, MaxValue = 2, Default = 1, Value = 1, Precision = 0.01, }; [SettingSource("Final rate", "The speed increase to ramp towards")] public override BindableNumber<double> FinalRate { get; } = new BindableDouble { MinValue = 0.5, MaxValue = 0.99, Default = 0.75, Value = 0.75, Precision = 0.01, }; public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(ModWindUp)).ToArray(); } } ```
b357f489-ca41-4b17-a4a2-9f34af2769f6
{ "language": "C#" }
```c# using System; public static class IntegerExtensions { public static TimeSpan Days(this Int32 integer) { return TimeSpan.FromDays(integer); } public static TimeSpan Hours(this Int32 integer) { return TimeSpan.FromHours(integer); } public static TimeSpan Milliseconds(this Int32 integer) { return TimeSpan.FromMilliseconds(integer); } public static TimeSpan Minutes(this Int32 integer) { return TimeSpan.FromMinutes(integer); } public static TimeSpan Seconds(this Int32 integer) { return TimeSpan.FromSeconds(integer); } } ``` Allow converting integers (UNIX timestamps) to DateTime instances.
```c# using System; public static class IntegerExtensions { private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static TimeSpan Days(this Int32 integer) { return TimeSpan.FromDays(integer); } public static TimeSpan Hours(this Int32 integer) { return TimeSpan.FromHours(integer); } public static TimeSpan Milliseconds(this Int32 integer) { return TimeSpan.FromMilliseconds(integer); } public static TimeSpan Minutes(this Int32 integer) { return TimeSpan.FromMinutes(integer); } public static TimeSpan Seconds(this Int32 integer) { return TimeSpan.FromSeconds(integer); } public static DateTime ToDateTime(this Int64 integer, Boolean useMilliseconds = false) { return useMilliseconds ? UNIX_EPOCH.AddMilliseconds(integer) : UNIX_EPOCH.AddSeconds(integer); } } ```
379c9957-ba57-45cd-8fa7-e1cd1d6682a0
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"F")] F, [Description(@"F")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } } ``` Rename F grade to D
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"D")] F, [Description(@"D")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } } ```
be6b886a-bcda-4936-9e9b-d36d738c20aa
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]``` Correct version, managed by build script
```c# using System.Reflection; [assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyInformationalVersion("0.0.0.*")]```
343a0851-c6c3-40a3-a1d7-00dd028bcceb
{ "language": "C#" }
```c# using System; using System.Text; using NHibernate.Util; namespace NHibernate.Sql { /// <summary> /// An SQL <c>DELETE</c> statement /// </summary> public class Delete { private string tableName; private string[] primaryKeyColumnNames; private string versionColumnName; private string where; public Delete SetTableName(string tableName) { this.tableName = tableName; return this; } public string ToStatementString() { StringBuilder buf = new StringBuilder( tableName.Length + 10 ); buf.Append("delete from ") .Append(tableName) .Append(" where ") .Append( string.Join("=? and ", primaryKeyColumnNames) ) .Append("=?"); if (versionColumnName != null) { buf.Append(" and ") .Append(versionColumnName) .Append("=?"); if(where!=null) { buf.Append(" and ") .Append(where); } } return buf.ToString(); } public Delete SetWhere(string where) { this.where = where; return this; } public Delete SetPrimaryKeyColumnNames(string[] primaryKeyColumnNames) { this.primaryKeyColumnNames = primaryKeyColumnNames; return this; } public Delete SetVersionColumnName(string versionColumnName) { this.versionColumnName = versionColumnName; return this; } } } ``` Fix bug in "where" if-statement
```c# using System; using System.Text; using NHibernate.Util; namespace NHibernate.Sql { /// <summary> /// An SQL <c>DELETE</c> statement /// </summary> public class Delete { private string tableName; private string[] primaryKeyColumnNames; private string versionColumnName; private string where; public Delete SetTableName(string tableName) { this.tableName = tableName; return this; } public string ToStatementString() { StringBuilder buf = new StringBuilder( tableName.Length + 10 ); buf.Append("delete from ") .Append(tableName) .Append(" where ") .Append( string.Join("=? and ", primaryKeyColumnNames) ) .Append("=?"); if(where!=null) { buf.Append(" and ") .Append(where); } if (versionColumnName != null) { buf.Append(" and ") .Append(versionColumnName) .Append("=?"); } return buf.ToString(); } public Delete SetWhere(string where) { this.where = where; return this; } public Delete SetPrimaryKeyColumnNames(params string[] primaryKeyColumnNames) { this.primaryKeyColumnNames = primaryKeyColumnNames; return this; } public Delete SetVersionColumnName(string versionColumnName) { this.versionColumnName = versionColumnName; return this; } } } ```
b0c908df-0c7a-483b-b3c8-167057690988
{ "language": "C#" }
```c# @using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <div> Forum Scorer </div> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li>@user.Name: @user.WeekScore</li> } </ul> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li>@user.Name: @user.PreviousWeekScore</li> } </ul> </body> </html> ``` Add links and more info
```c# @using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <h2>Forum Scorer</h2> <h3>This week's leaderboard (the week ends on Friday)</h3> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.WeekScore</li> } </ul> <h3>Last week's leaderboard</h3> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.PreviousWeekScore</li> } </ul> <h3>Scoring notes</h3> Click on a user's name to see their activity detail on MSDN. Points are give as follows: <ul> <li>20 points for quickly answering a question</li> <li>15 points for answering a question</li> <li>5 points for contributing a helpful post</li> <li>1 for responding to a question (additional responses to the same question don't count)</li> </ul> </body> </html> ```
7412ed43-1965-4420-ae73-780f840e7af2
{ "language": "C#" }
```c# @using Umbraco.Web.UI.NetCore @using Umbraco.Extensions @using Umbraco.Web.PublishedModels @using Umbraco.Cms.Core.Models.PublishedContent @using Microsoft.AspNetCore.Html @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ``` Add the same to the _viewimports file for the dotnet new template
```c# @using Umbraco.Web.UI.NetCore @using Umbraco.Extensions @using Umbraco.Web.PublishedModels @using Umbraco.Cms.Core.Models.PublishedContent @using Microsoft.AspNetCore.Html @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Smidge @inject Smidge.SmidgeHelper SmidgeHelper```
9c057ae9-c123-46bb-8fba-8de8c482c05c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dolstagis.Web.Lifecycle { public class LoginHandler : ILoginHandler { public object GetLogin(IHttpContext context) { return new RedirectResult("/login", Status.SeeOther); } } } ``` Make the login URL configurable.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dolstagis.Web.Lifecycle { public class LoginHandler : ILoginHandler { public string LoginUrl { get; set; } public LoginHandler() { LoginUrl = "~/login"; } public object GetLogin(IHttpContext context) { return new RedirectResult(LoginUrl, Status.SeeOther); } } } ```
6f2c8a54-feb6-4c77-9b3b-b0170ba6b72b
{ "language": "C#" }
```c# using hase.DevLib.Contract.FileSystemQuery; using hase.DevLib.Service.FileSystemQuery; using ProtoBuf; using System; using System.IO.Pipes; namespace hase.DevLib.Service { public class ServiceDispatcher { private static readonly string pipeName = nameof(FileSystemQueryService); private NamedPipeClientStream pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None); public void Run() { Console.WriteLine($"{pipeName} connecting to relay."); pipe.ConnectAsync(5000).Wait(); Console.WriteLine($"{pipeName} connected to relay."); while (true) { ProcessRequest(); } } private void ProcessRequest() { //Console.WriteLine($"Waiting to receive {pipeName} request."); var request = Serializer.DeserializeWithLengthPrefix<FileSystemQueryRequest>(pipe, PrefixStyle.Base128); Console.WriteLine($"Received {pipeName} request: {request}."); var service = new FileSystemQueryService(); FileSystemQueryResponse response = null; try { response = service.Execute(request); } catch (Exception ex) { } Console.WriteLine($"Sending {pipeName} response: {response}."); Serializer.SerializeWithLengthPrefix(pipe, response, PrefixStyle.Base128); //Console.WriteLine($"Sent {pipeName} response."); } } } ``` Add output abbreviation text for named pipe relay client to service dispatcher to match the service proxy.
```c# using hase.DevLib.Contract.FileSystemQuery; using hase.DevLib.Service.FileSystemQuery; using ProtoBuf; using System; using System.IO.Pipes; namespace hase.DevLib.Service { public class ServiceDispatcher { private static readonly string pipeName = nameof(FileSystemQueryService); private NamedPipeClientStream pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None); public void Run() { Console.WriteLine($"nprc:{pipeName} connecting to relay."); pipe.ConnectAsync(5000).Wait(); Console.WriteLine($"nprc:{pipeName} connected to relay."); while (true) { ProcessRequest(); } } private void ProcessRequest() { //Console.WriteLine($"nprc:Waiting to receive {pipeName} request."); var request = Serializer.DeserializeWithLengthPrefix<FileSystemQueryRequest>(pipe, PrefixStyle.Base128); Console.WriteLine($"nprc:Received {pipeName} request: {request}."); var service = new FileSystemQueryService(); FileSystemQueryResponse response = null; try { response = service.Execute(request); } catch (Exception ex) { } Console.WriteLine($"nprc:Sending {pipeName} response: {response}."); Serializer.SerializeWithLengthPrefix(pipe, response, PrefixStyle.Base128); //Console.WriteLine($"nprc:Sent {pipeName} response."); } } } ```
a3af0f61-b414-496c-9005-9dbc56ca23d2
{ "language": "C#" }
```c# using MacroGuards; using MacroSemver; using MacroSln; namespace Verbot { /// <summary> /// A location where the current version can be recorded /// </summary> /// public class VersionLocation { public VersionLocation(VisualStudioProject project) { Guard.NotNull(project, nameof(project)); Project = project; } public VisualStudioProject Project { get; } /// <summary> /// A description of the location /// </summary> /// public string Description { get { return Project.Path; } } /// <summary> /// Get the version recorded at the location /// </summary> /// /// <returns> /// The version recorded at the location, or <c>null</c> if no version is recorded there /// </returns> /// public SemVersion GetVersion() { var versionString = Project.GetProperty("Version"); return !string.IsNullOrWhiteSpace(versionString) ? SemVersion.Parse(versionString) : null; } /// <summary> /// Set the version recorded at the location /// </summary> /// public void SetVersion(SemVersion version) { Guard.NotNull(version, nameof(version)); var assemblyVersion = $"{version.Major}.0.0.0"; var assemblyFileVersion = $"{version.Major}.{version.Minor}.{version.Patch}.0"; Project.SetProperty("Version", version.ToString()); Project.SetProperty("AssemblyFileVersion", assemblyFileVersion); Project.SetProperty("AssemblyVersion", assemblyVersion); Project.Save(); } } } ``` Fix line endings in a file
```c# using MacroGuards; using MacroSemver; using MacroSln; namespace Verbot { /// <summary> /// A location where the current version can be recorded /// </summary> /// public class VersionLocation { public VersionLocation(VisualStudioProject project) { Guard.NotNull(project, nameof(project)); Project = project; } public VisualStudioProject Project { get; } /// <summary> /// A description of the location /// </summary> /// public string Description { get { return Project.Path; } } /// <summary> /// Get the version recorded at the location /// </summary> /// /// <returns> /// The version recorded at the location, or <c>null</c> if no version is recorded there /// </returns> /// public SemVersion GetVersion() { var versionString = Project.GetProperty("Version"); return !string.IsNullOrWhiteSpace(versionString) ? SemVersion.Parse(versionString) : null; } /// <summary> /// Set the version recorded at the location /// </summary> /// public void SetVersion(SemVersion version) { Guard.NotNull(version, nameof(version)); var assemblyVersion = $"{version.Major}.0.0.0"; var assemblyFileVersion = $"{version.Major}.{version.Minor}.{version.Patch}.0"; Project.SetProperty("Version", version.ToString()); Project.SetProperty("AssemblyFileVersion", assemblyFileVersion); Project.SetProperty("AssemblyVersion", assemblyVersion); Project.Save(); } } } ```
f4d420cf-6efb-45a5-9017-5bd25590794c
{ "language": "C#" }
```c# using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Resources; using System.Text; namespace AzureFunctions.ResxConvertor { public class ResxConvertor { public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth) { var sb = new StringBuilder(); sb.AppendLine("// This file is auto generated"); sb.AppendLine(""); sb.AppendLine("export class PortalResources"); sb.AppendLine("{"); foreach (var resxFile in resxFiles) { ResXResourceReader rsxr = new ResXResourceReader(resxFile); foreach (DictionaryEntry d in rsxr) { sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString())); } //Close the reader. rsxr.Close(); } sb.AppendLine("}"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth)) { file.WriteLine(sb.ToString()); } } } } ``` Check if resx file exists
```c# using Newtonsoft.Json.Linq; using System; using System.Collections; using System.IO; using System.Resources; using System.Text; namespace AzureFunctions.ResxConvertor { public class ResxConvertor { public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth) { var sb = new StringBuilder(); sb.AppendLine("// This file is auto generated"); sb.AppendLine(""); sb.AppendLine("export class PortalResources"); sb.AppendLine("{"); foreach (var resxFile in resxFiles) { if (File.Exists(resxFile)) { ResXResourceReader rsxr = new ResXResourceReader(resxFile); foreach (DictionaryEntry d in rsxr) { sb.AppendLine(string.Format(" public static {0}: string = \"{0}\";", d.Key.ToString())); } //Close the reader. rsxr.Close(); } } sb.AppendLine("}"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth)) { file.WriteLine(sb.ToString()); } } } } ```
5f4cdd2f-d5cd-4f4e-97e2-a5b52439c7f1
{ "language": "C#" }
```c# @model EditWebhookViewModel @using BTCPayServer.Client.Models; @{ Layout = "../Shared/_NavLayout.cshtml"; ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Test Webhook", Context.GetStoreData().StoreName); } <div class="row"> <div class="col-lg-8"> <form method="post"> <h4 class="mb-3">@ViewData["PageTitle"]</h4> <ul class="list-group"> @foreach (var evt in new[] { ("Test InvoiceCreated event", WebhookEventType.InvoiceCreated), ("Test InvoiceReceivedPayment event", WebhookEventType.InvoiceReceivedPayment), ("Test InvoiceProcessing event", WebhookEventType.InvoiceProcessing), ("Test InvoiceExpired event", WebhookEventType.InvoiceExpired), ("Test InvoiceSettled event", WebhookEventType.InvoiceSettled), ("Test InvoiceInvalid event", WebhookEventType.InvoiceInvalid) }) { <li class="list-group-item"> <button type="submit" name="Type" class="btn btn-primary" value="@evt.Item2">@evt.Item1</button> </li> } </ul> </form> </div> </div> ``` Update webhook test page design
```c# @model EditWebhookViewModel @using BTCPayServer.Client.Models; @{ Layout = "../Shared/_NavLayout.cshtml"; ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Send a test event to a webhook endpoint", Context.GetStoreData().StoreName); } <div class="row"> <div class="col-lg-8"> <form method="post"> <h4 class="mb-3">@ViewData["PageTitle"]</h4> <div class="form-group"> <label for="Type">Event type</label> <select name="Type" id="Type" class="form-control w-auto"> @foreach (var evt in new[] { WebhookEventType.InvoiceCreated, WebhookEventType.InvoiceReceivedPayment, WebhookEventType.InvoiceProcessing, WebhookEventType.InvoiceExpired, WebhookEventType.InvoiceSettled, WebhookEventType.InvoiceInvalid }) { <option value="@evt"> @evt </option> } </select> </div> <button type="submit" class="btn btn-primary">Send test webhook</button> </form> </div> </div> ```
5d711e19-6d69-4954-811a-52bf0d06e84a
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; using System.Linq; using Buzzbox_Common; using Buzzbox_Common.Encoders; namespace Buzzbox_Stream { class StreamEncode { public bool LoopForever; public bool ShuffleFields; private MtgEncodeFormatEncoder _encoder; private CardCollection _cardCollection; private StreamWriter _stream; public StreamEncode(CardCollection cardCollection, StreamWriter stream) { _encoder = new MtgEncodeFormatEncoder(); _cardCollection = cardCollection; _stream = stream; } public void ThreadEntry() { do { _cardCollection.Cards.Shuffle(); foreach (var card in _cardCollection.Cards) { var outputLine = _encoder.EncodeCard(card) + "\n\n"; if (ShuffleFields) { outputLine = ShuffleCardFields(outputLine); } //actually output _stream.Write(outputLine); } } while (LoopForever); _stream.Close(); } private string ShuffleCardFields(string cardLine) { cardLine = cardLine.TrimEnd('|').TrimStart('|'); List<string> fields = cardLine.Split('|').ToList(); fields.Shuffle(); return $"|{string.Join("|", fields)}|"; } } } ``` Handle closed /proc/self/fd/ in stream encode.
```c# using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using Buzzbox_Common; using Buzzbox_Common.Encoders; namespace Buzzbox_Stream { class StreamEncode { public bool LoopForever; public bool ShuffleFields; private MtgEncodeFormatEncoder _encoder; private CardCollection _cardCollection; private StreamWriter _stream; public StreamEncode(CardCollection cardCollection, StreamWriter stream) { _encoder = new MtgEncodeFormatEncoder(); _cardCollection = cardCollection; _stream = stream; } public void ThreadEntry() { do { _cardCollection.Cards.Shuffle(); foreach (var card in _cardCollection.Cards) { var outputLine = _encoder.EncodeCard(card) + "\n\n"; if (ShuffleFields) { outputLine = ShuffleCardFields(outputLine); } //actually try to output try { _stream.Write(outputLine); } catch (Exception) { //fd was probably closed or otherwise no longer available return; } } } while (LoopForever); _stream.Close(); } private string ShuffleCardFields(string cardLine) { cardLine = cardLine.TrimEnd('|').TrimStart('|'); List<string> fields = cardLine.Split('|').ToList(); fields.Shuffle(); return $"|{string.Join("|", fields)}|"; } } } ```
a4e89ff5-5c80-4311-9bbe-801e956b398e
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Attachment : DomainObject { public Attachment() { PublicGuid = Guid.NewGuid(); } [Required] public virtual byte[] Contents { get; set; } [Required] [StringLength(50)] public virtual string ContentType { get; set; } [StringLength(250)] public virtual string FileName { get; set; } public virtual Guid PublicGuid { get; set; } } public class AttachmentMap : ClassMap<Attachment> { public AttachmentMap() { Id(x => x.Id); Map(x => x.Contents).CustomSqlType("BinaryBlob"); Map(x => x.ContentType); Map(x => x.FileName); Map(x => x.PublicGuid); } } } ``` Update how byte[] is mapped.
```c# using System; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Commencement.Core.Domain { public class Attachment : DomainObject { public Attachment() { PublicGuid = Guid.NewGuid(); } [Required] public virtual byte[] Contents { get; set; } [Required] [StringLength(50)] public virtual string ContentType { get; set; } [StringLength(250)] public virtual string FileName { get; set; } public virtual Guid PublicGuid { get; set; } } public class AttachmentMap : ClassMap<Attachment> { public AttachmentMap() { Id(x => x.Id); Map(x => x.Contents).Length(Int32.MaxValue); Map(x => x.ContentType); Map(x => x.FileName); Map(x => x.PublicGuid); } } } ```
f711fa62-dc96-4267-915d-29be31242282
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using System; using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Screens.Edit.Components { public class TimeInfoContainer : BottomBarContainer { private readonly OsuSpriteText trackTimer; [Resolved] private EditorClock editorClock { get; set; } public TimeInfoContainer() { Children = new Drawable[] { trackTimer = new OsuSpriteText { Origin = Anchor.BottomLeft, RelativePositionAxes = Axes.Y, Font = OsuFont.GetFont(size: 22, fixedWidth: true), Y = 0.5f, } }; } protected override void Update() { base.Update(); trackTimer.Text = TimeSpan.FromMilliseconds(editorClock.CurrentTime).ToString(@"mm\:ss\:fff"); } } } ``` Fix editor not showing sign when time goes negative
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using System; using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Screens.Edit.Components { public class TimeInfoContainer : BottomBarContainer { private readonly OsuSpriteText trackTimer; [Resolved] private EditorClock editorClock { get; set; } public TimeInfoContainer() { Children = new Drawable[] { trackTimer = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, // intentionally fudged centre to avoid movement of the number portion when // going negative. X = -35, Font = OsuFont.GetFont(size: 25, fixedWidth: true), } }; } protected override void Update() { base.Update(); var timespan = TimeSpan.FromMilliseconds(editorClock.CurrentTime); trackTimer.Text = $"{(timespan < TimeSpan.Zero ? "-" : string.Empty)}{timespan:mm\\:ss\\:fff}"; } } } ```
42569069-3383-4065-bb62-1d7c60364c74
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Microsoft.EntityFrameworkCore.Storage; namespace osu.Game.Database { public class DatabaseWriteUsage : IDisposable { public readonly OsuDbContext Context; private readonly IDbContextTransaction transaction; private readonly Action<DatabaseWriteUsage> usageCompleted; public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted) { Context = context; transaction = Context.BeginTransaction(); usageCompleted = onCompleted; } public bool PerformedWrite { get; private set; } private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; PerformedWrite |= Context.SaveChanges(transaction) > 0; usageCompleted?.Invoke(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~DatabaseWriteUsage() { Dispose(false); } } } ``` Add proper transaction rollback logic on exception
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Microsoft.EntityFrameworkCore.Storage; namespace osu.Game.Database { public class DatabaseWriteUsage : IDisposable { public readonly OsuDbContext Context; private readonly IDbContextTransaction transaction; private readonly Action<DatabaseWriteUsage> usageCompleted; public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted) { Context = context; transaction = Context.BeginTransaction(); usageCompleted = onCompleted; } public bool PerformedWrite { get; private set; } private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; try { PerformedWrite |= Context.SaveChanges(transaction) > 0; } catch (Exception e) { transaction?.Rollback(); throw; } finally { usageCompleted?.Invoke(this); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~DatabaseWriteUsage() { Dispose(false); } } } ```
660cbf46-a2a6-4ec4-b536-51cd676dbb89
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; using RestSharp; namespace Rollbar { public class RollbarPayload { public RollbarPayload(string accessToken, RollbarData data) { if (string.IsNullOrWhiteSpace(accessToken)) { throw new ArgumentNullException("accessToken"); } if (data == null) { throw new ArgumentNullException("data"); } AccessToken = accessToken; RollbarData = data; } public void Send() { var http = new RestClient("https://api.rollbar.com"); var request = new RestRequest("/api/1/item/", Method.POST); request.AddParameter("application/json", JsonConvert.SerializeObject(this), ParameterType.RequestBody); http.Execute(request); } [JsonProperty("access_token", Required = Required.Always)] public string AccessToken { get; private set; } [JsonProperty("data", Required = Required.Always)] public RollbarData RollbarData { get; private set; } } } ``` Replace Send with ToJson so the library is independent from how you send it
```c# using System; using Newtonsoft.Json; namespace Rollbar { public class RollbarPayload { public RollbarPayload(string accessToken, RollbarData data) { if (string.IsNullOrWhiteSpace(accessToken)) { throw new ArgumentNullException("accessToken"); } if (data == null) { throw new ArgumentNullException("data"); } AccessToken = accessToken; RollbarData = data; } public string ToJson() { return JsonConvert.SerializeObject(this); } [JsonProperty("access_token", Required = Required.Always)] public string AccessToken { get; private set; } [JsonProperty("data", Required = Required.Always)] public RollbarData RollbarData { get; private set; } } } ```
7f731d9f-e844-4b46-b5d6-b17af88557b8
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Text; using ReClassNET.Util; namespace ReClassNET.MemorySearcher.Comparer { public class StringMemoryComparer : IMemoryComparer { public SearchCompareType CompareType => SearchCompareType.Equal; public bool CaseSensitive { get; } public Encoding Encoding { get; } public string Value { get; } public int ValueSize => Value.Length * Encoding.GetSimpleByteCountPerChar(); public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive) { Value = value; Encoding = encoding; CaseSensitive = caseSensitive; } public bool Compare(byte[] data, int index, out SearchResult result) { result = null; var value = Encoding.GetString(data, index, Value.Length); if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) { return false; } result = new StringSearchResult(value, Encoding); return true; } public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result) { #if DEBUG Debug.Assert(previous is StringSearchResult); #endif return Compare(data, index, out result); } } } ``` Reduce number of function calls.
```c# using System; using System.Diagnostics; using System.Text; using ReClassNET.Util; namespace ReClassNET.MemorySearcher.Comparer { public class StringMemoryComparer : IMemoryComparer { public SearchCompareType CompareType => SearchCompareType.Equal; public bool CaseSensitive { get; } public Encoding Encoding { get; } public string Value { get; } public int ValueSize { get; } public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive) { Value = value; Encoding = encoding; CaseSensitive = caseSensitive; ValueSize = Value.Length * Encoding.GetSimpleByteCountPerChar(); } public bool Compare(byte[] data, int index, out SearchResult result) { result = null; var value = Encoding.GetString(data, index, Value.Length); if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) { return false; } result = new StringSearchResult(value, Encoding); return true; } public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result) { #if DEBUG Debug.Assert(previous is StringSearchResult); #endif return Compare(data, index, out result); } } } ```
a80aba14-cc40-4025-9865-6d35616e9275
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class UsageController : MonoBehaviour { private Rigidbody2D rb2d; private UsableObjectCS collidingWith = null; private bool startedUsing = false; private bool stoppedUsing = false; // Use this for initialization void Start () { rb2d = GetComponent<Rigidbody2D> (); } void Update () { if (!UISystem.Instance.CutSceneDisplaying ()) { startedUsing = Input.GetButtonDown ("Action"); stoppedUsing = Input.GetButtonUp ("Action"); } } void LateUpdate () { if (!UISystem.Instance.CutSceneDisplaying ()) { if (null != collidingWith) { if (startedUsing) { collidingWith.StartUsing (gameObject); } else if (stoppedUsing) { collidingWith.StopUsing (gameObject); } } } } void OnTriggerEnter2D (Collider2D other) { collidingWith = other.gameObject.GetComponent<UsableObjectCS> (); if (null != collidingWith) { Debug.Log ("Colliding with usable object."); } } void OnTriggerExit2D (Collider2D other) { collidingWith = null; } }``` Fix stop using on exit
```c# using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class UsageController : MonoBehaviour { private Rigidbody2D rb2d; private UsableObjectCS collidingWith = null; private bool isUsing = false; private bool startedUsing = false; private bool stoppedUsing = false; // Use this for initialization void Start () { rb2d = GetComponent<Rigidbody2D> (); } void Update () { if (!UISystem.Instance.CutSceneDisplaying ()) { startedUsing = Input.GetButtonDown ("Action"); stoppedUsing = Input.GetButtonUp ("Action"); } } void LateUpdate () { if (!UISystem.Instance.CutSceneDisplaying ()) { if (null != collidingWith) { if (startedUsing) { isUsing = true; collidingWith.StartUsing (gameObject); } else if (stoppedUsing) { isUsing = false; collidingWith.StopUsing (gameObject); } } } } void OnTriggerEnter2D (Collider2D other) { collidingWith = other.gameObject.GetComponent<UsableObjectCS> (); if (null != collidingWith) { Debug.Log ("Colliding with usable object."); } } void OnTriggerExit2D (Collider2D other) { if ( isUsing && null != collidingWith) { collidingWith.StopUsing (gameObject); } collidingWith = null; } }```
4fc7524b-b2f1-479b-bec8-4397fdeefbfc
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Http.Features; namespace Microsoft.AspNet.Http.Extensions { public static class ResponseExtensions { public static void Clear(this HttpResponse response) { if (response.HasStarted) { throw new InvalidOperationException("The response cannot be cleared, it has already started sending."); } response.StatusCode = 200; response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null; response.Headers.Clear(); if (response.Body.CanSeek) { response.Body.SetLength(0); } } } } ``` Fix namespace for Clear extension.
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Http.Features; namespace Microsoft.AspNet.Http { public static class ResponseExtensions { public static void Clear(this HttpResponse response) { if (response.HasStarted) { throw new InvalidOperationException("The response cannot be cleared, it has already started sending."); } response.StatusCode = 200; response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null; response.Headers.Clear(); if (response.Body.CanSeek) { response.Body.SetLength(0); } } } } ```
3825e5d4-a3f0-43bf-8c93-7037721e0f46
{ "language": "C#" }
```c# #region using using Irony.Compiler; using System.Collections; using ScriptNET.Runtime; using System; #endregion namespace ScriptNET.Ast { /// <summary> /// ForEachStatement /// </summary> internal class ScriptForEachStatement : ScriptStatement { private Token name; private ScriptExpr expr; private ScriptStatement statement; public ScriptForEachStatement(AstNodeArgs args) : base(args) { name = (Token)ChildNodes[1]; expr = (ScriptExpr)ChildNodes[3]; statement = (ScriptStatement)ChildNodes[4]; } public override void Evaluate(IScriptContext context) { expr.Evaluate(context); IEnumerable enumeration = context.Result as IEnumerable; IEnumerator enumerator = null; if (enumeration != null) { enumerator = enumeration.GetEnumerator(); } else { IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]); if (bind != null) enumerator = bind.Invoke(context, null) as IEnumerator; } if (enumerator == null) throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString()); enumerator.Reset(); while(enumerator.MoveNext()) { context.SetItem(name.Text, enumerator.Current); statement.Evaluate(context); if (context.IsBreak() || context.IsReturn()) { context.SetBreak(false); break; } if (context.IsContinue()) { context.SetContinue(false); } } } } } ``` Remove unnecessary enumerator.Reset() from foreach() handling -- causes problems with IEnumerable created from LINQ
```c# #region using using Irony.Compiler; using System.Collections; using ScriptNET.Runtime; using System; #endregion namespace ScriptNET.Ast { /// <summary> /// ForEachStatement /// </summary> internal class ScriptForEachStatement : ScriptStatement { private Token name; private ScriptExpr expr; private ScriptStatement statement; public ScriptForEachStatement(AstNodeArgs args) : base(args) { name = (Token)ChildNodes[1]; expr = (ScriptExpr)ChildNodes[3]; statement = (ScriptStatement)ChildNodes[4]; } public override void Evaluate(IScriptContext context) { expr.Evaluate(context); IEnumerable enumeration = context.Result as IEnumerable; IEnumerator enumerator = null; if (enumeration != null) { enumerator = enumeration.GetEnumerator(); } else { IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]); if (bind != null) enumerator = bind.Invoke(context, null) as IEnumerator; } if (enumerator == null) throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString()); // enumerator.Reset(); while(enumerator.MoveNext()) { context.SetItem(name.Text, enumerator.Current); statement.Evaluate(context); if (context.IsBreak() || context.IsReturn()) { context.SetBreak(false); break; } if (context.IsContinue()) { context.SetContinue(false); } } } } } ```
41744ace-f229-42bd-b3bd-ce2f06b3959a
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static void PrintHelp(TextWriter? writer = null) { var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); writer ??= Console.Error; writer.Write( $@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory. Options: -h|-?|--help Print this help text. --list-props Print a list of DotVVM properties inside the assembly. "); } public static int Main(string[] args) { #if NETCOREAPP3_1_OR_GREATER var r = Microsoft.Extensions.DependencyModel.DependencyContext.Default.RuntimeLibraries .Where(l => l.Name.Contains("DotVVM")).ToArray(); var c = Microsoft.Extensions.DependencyModel.DependencyContext.Default.CompileLibraries .Where(l => l.Name.Contains("DotVVM")).ToArray(); foreach(var context in System.Runtime.Loader.AssemblyLoadContext.All) { context.Resolving += (c, n) => { return null; }; } #endif if (!CompilerArgs.TryParse(args, out var parsed)) { PrintHelp(Console.Error); return 1; } if (parsed.IsHelp) { PrintHelp(Console.Out); return 0; } var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName); var success = executor.ExecuteCompile(parsed); return success ? 0 : 1; } } } ``` Remove some forgotten debugging code
```c# using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static void PrintHelp(TextWriter? writer = null) { var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]); writer ??= Console.Error; writer.Write( $@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory. Options: -h|-?|--help Print this help text. --list-props Print a list of DotVVM properties inside the assembly. "); } public static int Main(string[] args) { if (!CompilerArgs.TryParse(args, out var parsed)) { PrintHelp(Console.Error); return 1; } if (parsed.IsHelp) { PrintHelp(Console.Out); return 0; } var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName); var success = executor.ExecuteCompile(parsed); return success ? 0 : 1; } } } ```
471fd016-d403-4402-9827-d6e49e5f1671
{ "language": "C#" }
```c# using NuGet.OutputWindowConsole; using NuGetConsole; namespace NuGet.Dialog.PackageManagerUI { internal class SmartOutputConsoleProvider : IOutputConsoleProvider { private readonly IOutputConsoleProvider _baseProvider; private bool _isFirstTime = true; public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) { _baseProvider = baseProvider; } public IConsole CreateOutputConsole(bool requirePowerShellHost) { IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost); if (_isFirstTime) { // the first time the console is accessed after dialog is opened, we clear the console. console.Clear(); } else { _isFirstTime = false; } return console; } } }``` Fix the wrong conditional statement.
```c# using NuGet.OutputWindowConsole; using NuGetConsole; namespace NuGet.Dialog.PackageManagerUI { internal class SmartOutputConsoleProvider : IOutputConsoleProvider { private readonly IOutputConsoleProvider _baseProvider; private bool _isFirstTime = true; public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) { _baseProvider = baseProvider; } public IConsole CreateOutputConsole(bool requirePowerShellHost) { IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost); if (_isFirstTime) { // the first time the console is accessed after dialog is opened, we clear the console. console.Clear(); _isFirstTime = false; } return console; } } }```
f963d42a-b0e8-490a-af40-f00bcbd4bd9d
{ "language": "C#" }
```c# @section Title {Homepage} @section Description{Chess Variants Training is a website where you can improve at chess variants.} Homepage of Chess Variants Training. ``` Put actual content on home page
```c# @section Title {Homepage} @section Description{Chess Variants Training is a website where you can improve at chess variants.} <h1>Chess Variants Training</h1> <p>Welcome to Chess Variants Training! Here you can improve at chess variants. We support these variants: Antichess, Atomic chess, King of the Hill, Three-check, Horde chess and Racing Kings.</p> <h3>@Html.ActionLink("Puzzles", "Index", "Puzzle")</h3> <p>You can improve your tactics by doing tactics puzzles, created by the users of Chess Variants Training.</p> <h3>@Html.ActionLink("Timed training", "Index", "TimedTraining")</h3> <p>Improve your speed! You get a position and you have to find the winning move (or for antichess, the forced capture) as quickly as possible. How many positions can you do in one minute?</p> <h3>@Html.ActionLink("Endgames", "Index", "Endgames")</h3> <p>For atomic and antichess, we also have endgame training! You get a won endgame position and have to do the right moves to win it. Can you do this before the 50-move rule makes the game a draw?</p> <h3>@Html.ActionLink("Register", "Register", "User")</h3> <p>If you sign up for an account, your puzzle rating and timed training statistics will be stored, you can comment on puzzles and you can add puzzles yourself!</p> <h3>Contact</h3> <p>If you have a question, suggestion or bug report, don't hesitate to contact us and drop a line to <code>chessvariantstraining(at)gmail(dot)com</code></p> <p>We wish you a lot of fun here on Chess Variants Training!</p>```
28250ebf-0db5-4740-8e1e-92eff3926437
{ "language": "C#" }
```c# @model PackageListViewModel @{ ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm; ViewBag.Tab = "Packages"; } <div class="search"> @if (!String.IsNullOrEmpty(Model.SearchTerm)) { <h1>Search for <i>@Model.SearchTerm</i> returned @Model.TotalCount @if (Model.TotalCount == 1) { <text>package</text> } else { <text>packages</text> }</h1> } else { <h1>@if (Model.TotalCount == 1) { <text>There is @Model.TotalCount package</text> } else { <text>There are @Model.TotalCount packages</text> }</h1> } @if (@Model.LastResultIndex > 0) { <h2>Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.</h2> } </div> <span class="sorted-by">Sorted by Recent Installs</span> <ul id="searchResults"> @foreach (var package in Model.Items) { <li> @Html.Partial("_ListPackage", package) </li> } </ul> @ViewHelpers.PreviousNextPager(Model.Pager) ``` Change the sort text based on if there's a term or not
```c# @model PackageListViewModel @{ ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm; ViewBag.SortText = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "recent installs" : "relevance"; ViewBag.Tab = "Packages"; } <div class="search"> @if (!String.IsNullOrEmpty(Model.SearchTerm)) { <h1>Search for <i>@Model.SearchTerm</i> returned @Model.TotalCount @if (Model.TotalCount == 1) { <text>package</text> } else { <text>packages</text> }</h1> } else { <h1>@if (Model.TotalCount == 1) { <text>There is @Model.TotalCount package</text> } else { <text>There are @Model.TotalCount packages</text> }</h1> } @if (@Model.LastResultIndex > 0) { <h2>Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.</h2> } </div> <span class="sorted-by">sorted by @ViewBag.SortText</span> <ul id="searchResults"> @foreach (var package in Model.Items) { <li> @Html.Partial("_ListPackage", package) </li> } </ul> @ViewHelpers.PreviousNextPager(Model.Pager) ```
74b65375-d102-4400-8070-ea34507d25df
{ "language": "C#" }
```c# using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }``` Replace app name for special cases in team city check
```c# using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }```
e31f55c5-4912-473b-b667-a992112b9a80
{ "language": "C#" }
```c# using System; using Flame.Compiler; using LLVMSharp; using static LLVMSharp.LLVM; namespace Flame.LLVM.Codegen { /// <summary> /// A code block implementation that returns a value from a method. /// </summary> public sealed class ReturnBlock : CodeBlock { public ReturnBlock( LLVMCodeGenerator CodeGenerator, CodeBlock ReturnValue) { this.codeGen = CodeGenerator; this.retVal = ReturnValue; } private LLVMCodeGenerator codeGen; private CodeBlock retVal; /// <inheritdoc/> public override ICodeGenerator CodeGenerator => codeGen; /// <inheritdoc/> public override IType Type => PrimitiveTypes.Void; /// <inheritdoc/> public override BlockCodegen Emit(BasicBlockBuilder BasicBlock) { var retValCodegen = retVal.Emit(BasicBlock); BasicBlock = retValCodegen.BasicBlock; if (retVal.Type == PrimitiveTypes.Void) { var retVoid = BuildRetVoid(BasicBlock.Builder); return new BlockCodegen(BasicBlock, retVoid); } else { var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value); return new BlockCodegen(BasicBlock, ret); } } } } ``` Fix a bug in the 'ret void' implementation
```c# using System; using Flame.Compiler; using LLVMSharp; using static LLVMSharp.LLVM; namespace Flame.LLVM.Codegen { /// <summary> /// A code block implementation that returns a value from a method. /// </summary> public sealed class ReturnBlock : CodeBlock { public ReturnBlock( LLVMCodeGenerator CodeGenerator, CodeBlock ReturnValue) { this.codeGen = CodeGenerator; this.retVal = ReturnValue; } private LLVMCodeGenerator codeGen; private CodeBlock retVal; /// <inheritdoc/> public override ICodeGenerator CodeGenerator => codeGen; /// <inheritdoc/> public override IType Type => PrimitiveTypes.Void; private BlockCodegen EmitRetVoid(BasicBlockBuilder BasicBlock) { var retVoid = BuildRetVoid(BasicBlock.Builder); return new BlockCodegen(BasicBlock); } /// <inheritdoc/> public override BlockCodegen Emit(BasicBlockBuilder BasicBlock) { if (retVal == null) { return EmitRetVoid(BasicBlock); } var retValCodegen = retVal.Emit(BasicBlock); BasicBlock = retValCodegen.BasicBlock; if (retVal.Type == PrimitiveTypes.Void) { return EmitRetVoid(BasicBlock); } else { var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value); return new BlockCodegen(BasicBlock, ret); } } } } ```
95c5f5cb-f907-4886-8e7f-6e3184a3ba82
{ "language": "C#" }
```c# using System; namespace ShadowsOfShadows.Items { public abstract class Item { protected String Name { get; set; } protected String StatsString { get; set; } public Item(String name, String stats) { Name = name; StatsString = stats; } public override String ToString() { String result = Name + "\n" + "Statistics:\n" + StatsString; return result; } public abstract AllowedItem Allowed { get; } public virtual bool IsLike(Item item) { return false; } } } ``` Make ToString() short and provide Details()
```c# using System; namespace ShadowsOfShadows.Items { public abstract class Item { protected string Name { get; set; } protected string StatsString { get; set; } public Item(string name, string stats) { Name = name; StatsString = stats; } public override string ToString() => Name; public string Details() { string result = Name + "\n" + "Statistics:\n" + StatsString; return result; } public abstract AllowedItem Allowed { get; } public virtual bool IsLike(Item item) { return false; } } }```
7c08468b-d6a0-4726-abad-76332f478821
{ "language": "C#" }
```c# #region Using using System; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="DateTime" />. /// </summary> public static partial class DateTimeEx { /// <summary> /// Calculates the difference between the year of the current and the given date time. /// </summary> /// <param name="dateTime">The date time value.</param> /// <returns>The difference between the year of the current and the given date time.</returns> public static Int32 Age( this DateTime dateTime ) { if ( DateTime.Today.Month < dateTime.Month || DateTime.Today.Month == dateTime.Month && DateTime.Today.Day < dateTime.Day ) return DateTime.Today.Year - dateTime.Year - 1; return DateTime.Today.Year - dateTime.Year; } } }``` Fix bug causing incorrect results when dateTime was >= dateTime.Now + 363d
```c# #region Using using System; #endregion namespace PortableExtensions { /// <summary> /// Class containing some extension methods for <see cref="DateTime" />. /// </summary> public static partial class DateTimeEx { /// <summary> /// Calculates the difference between the year of the current and the given date time. /// </summary> /// <remarks> /// <paramref name="now"/> can be samller than <paramref name="dateTime"/>, which results in negative results. /// </remarks> /// <param name="dateTime">The date time value.</param> /// <param name="now">The 'current' date used to caluculate the age, or null tu use <see cref="DateTime.Now" />.</param> /// <returns>The difference between the year of the current and the given date time.</returns> public static Int32 Age(this DateTime dateTime, DateTime? now = null) { var currentDate = now ?? DateTime.Now; if (dateTime.Year == currentDate.Year) return 0; var age = currentDate.Year - dateTime.Year; if (dateTime > currentDate && (currentDate.Month > dateTime.Month || currentDate.Day > dateTime.Day)) age ++; else if ( (currentDate.Month < dateTime.Month || (currentDate.Month == dateTime.Month && currentDate.Day < dateTime.Day))) age--; return age; } } }```
166761d7-d083-433a-8a21-8c375918fdfe
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public static class Collection { public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Add(item); } } public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Remove(item); } } public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Add(item); } } public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Remove(item); } } public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys) where U : TKey { foreach (U key in keys) { dictionary.Remove(key); } } public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items) { foreach (T item in items) { queue.Enqueue(item); } } } } ``` Add the GetEnumeratorOfCopy extension method.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public static class Collection { public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Add(item); } } public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items) { foreach (T item in items) { collection.Remove(item); } } public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Add(item); } } public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items) where U : T { foreach (U item in items) { collection.Remove(item); } } public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys) where U : TKey { foreach (U key in keys) { dictionary.Remove(key); } } public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items) { foreach (T item in items) { queue.Enqueue(item); } } // This method is useful if you intend to modify a collection while/after iterating over it. public static IEnumerable<T> GetEnumeratorOfCopy<T>(this IEnumerable<T> collection) { var array = collection.ToArray(); foreach (var item in array) { yield return item; } } } } ```
019519f6-3a53-41d7-b8ab-451054fa0858
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }``` Fix exception not recording topic name.
```c# using System; using System.Collections.Concurrent; using System.Linq; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultPartitionSelector : IPartitionSelector { private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>(); public Partition Select(Topic topic, string key) { if (topic == null) throw new ArgumentNullException("topic"); if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic.Name)); //use round robing var partitions = topic.Partitions; if (key == null) { return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) => { var index = partitions.FindIndex(0, p => p.Equals(i)); if (index == -1) return partitions.First(); if (++index >= partitions.Count) return partitions.First(); return partitions[index]; }); } //use key hash var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count; var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId); if (partition == null) throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}", partitionId, string.Join(",", partitions.Select(x => x.PartitionId)))); return partition; } } }```
550cac2d-6fb0-4444-afd0-f7f505498b62
{ "language": "C#" }
```c# using System; using ServiceStack; using ServiceStack.Logging; namespace DiscourseAutoApprove.ServiceInterface { public interface IServiceStackAccountClient { UserServiceResponse GetUserSubscription(string emailAddress); } public class ServiceStackAccountClient : IServiceStackAccountClient { private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient)); private readonly string serviceUrl; public ServiceStackAccountClient(string url) { serviceUrl = url; } public UserServiceResponse GetUserSubscription(string emailAddress) { UserServiceResponse result = null; try { result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl() .FromJson<UserServiceResponse>(); } catch (Exception e) { Log.Error(e.Message); } return result; } } public class UserServiceResponse { public DateTime? Expiry { get; set; } } } ``` Throw when error form account service.
```c# using System; using ServiceStack; using ServiceStack.Logging; namespace DiscourseAutoApprove.ServiceInterface { public interface IServiceStackAccountClient { UserServiceResponse GetUserSubscription(string emailAddress); } public class ServiceStackAccountClient : IServiceStackAccountClient { private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient)); private readonly string serviceUrl; public ServiceStackAccountClient(string url) { serviceUrl = url; } public UserServiceResponse GetUserSubscription(string emailAddress) { UserServiceResponse result = null; try { result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl() .FromJson<UserServiceResponse>(); } catch (Exception e) { Log.Error(e.Message); throw; } return result; } } public class UserServiceResponse { public DateTime? Expiry { get; set; } } } ```
25c35b35-a6ec-4d00-9d51-a683b9c47012
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using Angora; namespace Producer { class Program { const int numberOfMessages = 1_000_000; static async Task Main() { var factory = new ConnectionFactory { HostName = "rabbit" }; var connection = await factory.CreateConnection("Producer"); var channel = await connection.CreateChannel(); await channel.Queue.Declare("test", false, true, false, false, null); Console.WriteLine("Producer started. Press any key to send messages."); Console.ReadKey(); for (int i = 0; i < numberOfMessages; i++) { var properties = new MessageProperties() { ContentType = "message", AppId = "123", Timestamp = DateTime.UtcNow, Headers = new Dictionary<string, object> { {"MessageId", i} } }; await channel.Basic.Publish("", "test", true, properties, System.Text.Encoding.UTF8.GetBytes("Message Payload")); } await channel.Close(); await connection.Close(); } } }``` Add number to message payload
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using Angora; namespace Producer { class Program { const int numberOfMessages = 1_000_000; static async Task Main() { var factory = new ConnectionFactory { HostName = "rabbit" }; var connection = await factory.CreateConnection("Producer"); var channel = await connection.CreateChannel(); await channel.Queue.Declare("test", false, true, false, false, null); Console.WriteLine("Producer started. Press any key to send messages."); Console.ReadKey(); for (int i = 0; i < numberOfMessages; i++) { var properties = new MessageProperties() { ContentType = "message", AppId = "123", Timestamp = DateTime.UtcNow, Headers = new Dictionary<string, object> { {"MessageId", i} } }; await channel.Basic.Publish("", "test", true, properties, System.Text.Encoding.UTF8.GetBytes($"Message Payload {i}")); } await channel.Close(); await connection.Close(); } } }```
cbdd5660-67bc-44e5-9541-af3a55c04bf4
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Rulesets.Edit { [Flags] public enum SnapType { NearbyObjects = 0, Grids = 1, All = NearbyObjects | Grids, } } ``` Add "None" snap type to fix flags not working correctly
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Rulesets.Edit { [Flags] public enum SnapType { None = 0, NearbyObjects = 1 << 0, Grids = 1 << 1, All = NearbyObjects | Grids, } } ```