doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
c20c43d4-8f6f-4f9a-8bb0-e38ccf402803
{ "language": "C#" }
```c# using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) { MediaManager.MediaPlayer.VideoView = null; } Player = null; } } } ``` Make MediaManager a static property
```c# using AVKit; namespace MediaManager.Platforms.Ios.Video { public class PlayerViewController : AVPlayerViewController { protected static MediaManagerImplementation MediaManager => CrossMediaManager.Apple; public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (MediaManager.MediaPlayer.VideoView == View.Superview) { MediaManager.MediaPlayer.VideoView = null; } Player = null; } } } ```
89c212e3-5a95-44c7-88e4-8d88b0b3bc26
{ "language": "C#" }
```c# using RimWorld; using Verse; namespace MTW_AncestorSpirits { class ThoughtWorker_NoShrineRoom : ThoughtWorker { private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom"); protected override ThoughtState CurrentStateInternal(Pawn p) { // TODO: There's gotta be a better way of doin' this! if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; } var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (shrine == null) { return ThoughtState.Inactive; } // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one! var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal()); if (room == null) { return ThoughtState.ActiveAtStage(1); } else if (room.Role != shrineRoomDef) { return ThoughtState.ActiveAtStage(1); } else { return ThoughtState.Inactive; } } } } ``` Fix NoShrineRoom logic if shrine is null
```c# using RimWorld; using Verse; namespace MTW_AncestorSpirits { class ThoughtWorker_NoShrineRoom : ThoughtWorker { private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom"); protected override ThoughtState CurrentStateInternal(Pawn p) { // TODO: There's gotta be a better way of doin' this! if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; } var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (shrine == null) { return ThoughtState.ActiveAtStage(1); } // HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one! var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal()); if (room == null) { return ThoughtState.ActiveAtStage(1); } else if (room.Role != shrineRoomDef) { return ThoughtState.ActiveAtStage(1); } else { return ThoughtState.Inactive; } } } } ```
f4154046-5b26-412e-b43c-133f50d9c8a1
{ "language": "C#" }
```c#  using System.Collections.Generic; using System.IO; namespace LINQToTTreeLib.ExecutionCommon { /// <summary> /// Runs an execution request /// </summary> interface IQueryExectuor { /// <summary> /// Run request, and return the results /// </summary> /// <param name="remotePacket"></param> /// <returns></returns> IDictionary<string, ROOTNET.Interface.NTObject> Execute( FileInfo templateFile, DirectoryInfo queryDirectory, IEnumerable<KeyValuePair<string, object>> varsToTransfer); /// <summary> /// Set the execution envrionment. Must be done before the call, should not /// change after the first setting. /// </summary> ExecutionEnvironment Environment { set; } } } ``` Improve comments on the interface.
```c#  using System.Collections.Generic; using System.IO; namespace LINQToTTreeLib.ExecutionCommon { /// <summary> /// Runs an execution request /// </summary> interface IQueryExectuor { /// <summary> /// Run request, and return the results /// </summary> /// <param name="queryDirectory"></param> /// <param name="templateFile">Path to the main runner file</param> /// <param name="varsToTransfer">A list of variables that are used as input to the routine.</param> /// <returns>A list of objects and names pulled from the output root file</returns> IDictionary<string, ROOTNET.Interface.NTObject> Execute( FileInfo templateFile, DirectoryInfo queryDirectory, IEnumerable<KeyValuePair<string, object>> varsToTransfer); /// <summary> /// Set the execution envrionment. Must be done before the call, should not /// change after the first setting. /// </summary> ExecutionEnvironment Environment { set; } } } ```
a0424da5-7c68-4d6c-bc33-ad4b8834daa7
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using WeCantSpell.Tests.Utilities; using Xunit; namespace WeCantSpell.Tests.Integration.CSharp { public class CommentSpellingTests : CSharpTestBase { public static IEnumerable<object[]> can_find_mistakes_in_comments_data { get { yield return new object[] { "aardvark", 660 }; yield return new object[] { "simple", 1186 }; yield return new object[] { "under", 1235 }; } } [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))] public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart) { var expectedEnd = expectedStart + expectedWord.Length; var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord)); var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs"); var diagnostics = await GetDiagnosticsAsync(project, analyzer); diagnostics.Should().ContainSingle() .Subject.Should() .HaveId("SP3112") .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs") .And.HaveMessageContaining(expectedWord); } } } ``` Add a few more tests
```c# using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using WeCantSpell.Tests.Utilities; using Xunit; namespace WeCantSpell.Tests.Integration.CSharp { public class CommentSpellingTests : CSharpTestBase { public static IEnumerable<object[]> can_find_mistakes_in_comments_data { get { yield return new object[] { "aardvark", 660 }; yield return new object[] { "simple", 1186 }; yield return new object[] { "under", 1235 }; yield return new object[] { "inline", 111 }; yield return new object[] { "tag", 320 }; yield return new object[] { "Here", 898 }; yield return new object[] { "Just", 1130 }; } } [Theory, MemberData(nameof(can_find_mistakes_in_comments_data))] public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart) { var expectedEnd = expectedStart + expectedWord.Length; var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord)); var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs"); var diagnostics = await GetDiagnosticsAsync(project, analyzer); diagnostics.Should().ContainSingle() .Subject.Should() .HaveId("SP3112") .And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs") .And.HaveMessageContaining(expectedWord); } } } ```
884a41df-327e-4ad6-aa44-d603c944969a
{ "language": "C#" }
```c# namespace WebScriptHook.Framework.Messages.Outputs { /// <summary> /// Sent by the component to request a channel for itself on the server. /// This tells the server the name of this component, as well as the maximum number of requests /// the component can handle per tick. /// Once the server receives this message, a channel will be created, registered under this component's name. /// Inputs sent by web clients will then be delivered to this component. /// </summary> class ChannelRequest : WebOutput { const char HEADER_CACHE = 'n'; public ChannelRequest(string ComponentName, int InputQueueLimit) : base(HEADER_CACHE, new object[] { ComponentName, InputQueueLimit }, null) { } } } ``` Fix a typo in const name
```c# namespace WebScriptHook.Framework.Messages.Outputs { /// <summary> /// Sent by the component to request a channel for itself on the server. /// This tells the server the name of this component, as well as the maximum number of requests /// the component can handle per tick. /// Once the server receives this message, a channel will be created, registered under this component's name. /// Inputs sent by web clients will then be delivered to this component. /// </summary> class ChannelRequest : WebOutput { const char HEADER_CHANNEL = 'n'; public ChannelRequest(string ComponentName, int InputQueueLimit) : base(HEADER_CHANNEL, new object[] { ComponentName, InputQueueLimit }, null) { } } } ```
a119dac9-030a-4b17-a53d-c7d4b3ec6f18
{ "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.ComponentModel; using Microsoft.AspNetCore.ResponseCaching.Internal; namespace Microsoft.AspNetCore.Builder { public class ResponseCacheOptions { /// <summary> /// The largest cacheable size for the response body in bytes. The default is set to 1 MB. /// </summary> public long MaximumBodySize { get; set; } = 1024 * 1024; /// <summary> /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive. /// </summary> public bool UseCaseSensitivePaths { get; set; } = false; /// <summary> /// For testing purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal ISystemClock SystemClock { get; set; } = new SystemClock(); } } ``` Update default Max Body Size
```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.ComponentModel; using Microsoft.AspNetCore.ResponseCaching.Internal; namespace Microsoft.AspNetCore.Builder { public class ResponseCacheOptions { /// <summary> /// The largest cacheable size for the response body in bytes. The default is set to 64 MB. /// </summary> public long MaximumBodySize { get; set; } = 64 * 1024 * 1024; /// <summary> /// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive. /// </summary> public bool UseCaseSensitivePaths { get; set; } = false; /// <summary> /// For testing purposes only. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal ISystemClock SystemClock { get; set; } = new SystemClock(); } } ```
f0ebb53d-7683-42e5-9f97-7082fed10cfb
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media; using Data; using Tera.Game; namespace DamageMeter.UI { /// <summary> /// Logique d'interaction pour HistoryLink.xaml /// </summary> public partial class HistoryLink { public HistoryLink(string link, NpcEntity boss) { InitializeComponent(); Boss.Content = boss.Info.Name; Boss.Tag = link; if (link.StartsWith("!")) { Boss.Foreground = Brushes.Red; Boss.ToolTip = link; return; } Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source; } private void Click_Link(object sender, MouseButtonEventArgs e) { if (Boss.Tag.ToString().StartsWith("http://")) Process.Start("explorer.exe", Boss.Tag.ToString()); } private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var w = Window.GetWindow(this); try { w?.DragMove(); } catch { Console.WriteLine(@"Exception move"); } } } }``` Fix encounter url not opening
```c# using System; using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media; using Data; using Tera.Game; namespace DamageMeter.UI { /// <summary> /// Logique d'interaction pour HistoryLink.xaml /// </summary> public partial class HistoryLink { public HistoryLink(string link, NpcEntity boss) { InitializeComponent(); Boss.Content = boss.Info.Name; Boss.Tag = link; if (link.StartsWith("!")) { Boss.Foreground = Brushes.Red; Boss.ToolTip = link; return; } Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source; } private void Click_Link(object sender, MouseButtonEventArgs e) { if (Boss.Tag.ToString().StartsWith("http://")) Process.Start("explorer.exe", "\""+Boss.Tag+"\""); } private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var w = Window.GetWindow(this); try { w?.DragMove(); } catch { Console.WriteLine(@"Exception move"); } } } }```
6b04695f-a330-40b8-9f88-8fb3cd63aa93
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; using System.Threading.Tasks; // ReSharper disable AccessToDisposedClosure namespace VGAudio.Cli { internal static class Batch { public static bool BatchConvert(Options options) { if (options.Job != JobType.Batch) return false; SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; string[] files = ContainerTypes.ExtensionList .SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption)) .ToArray(); using (var progress = new ProgressBar()) { progress.SetTotal(files.Length); Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 }, inPath => { string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\'); string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName); var jobFiles = new JobFiles(); jobFiles.InFiles.Add(new AudioFile(inPath)); jobFiles.OutFiles.Add(new AudioFile(outPath)); try { progress.LogMessage(Path.GetFileName(inPath)); Convert.ConvertFile(options, jobFiles, false); } catch (Exception ex) { progress.LogMessage($"Error converting {Path.GetFileName(inPath)}"); progress.LogMessage(ex.ToString()); } progress.ReportAdd(1); }); } return true; } } } ``` Fix single core batch processing
```c# using System; using System.IO; using System.Linq; using System.Threading.Tasks; // ReSharper disable AccessToDisposedClosure namespace VGAudio.Cli { internal static class Batch { public static bool BatchConvert(Options options) { if (options.Job != JobType.Batch) return false; SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; string[] files = ContainerTypes.ExtensionList .SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption)) .ToArray(); using (var progress = new ProgressBar()) { progress.SetTotal(files.Length); Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(Environment.ProcessorCount - 1, 1) }, inPath => { string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\'); string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName); var jobFiles = new JobFiles(); jobFiles.InFiles.Add(new AudioFile(inPath)); jobFiles.OutFiles.Add(new AudioFile(outPath)); try { progress.LogMessage(Path.GetFileName(inPath)); Convert.ConvertFile(options, jobFiles, false); } catch (Exception ex) { progress.LogMessage($"Error converting {Path.GetFileName(inPath)}"); progress.LogMessage(ex.ToString()); } progress.ReportAdd(1); }); } return true; } } } ```
e7aa3618-30e3-49aa-a11a-c160d9ea7100
{ "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 BenchmarkDotNet.Attributes; using osu.Game.Online.API; using osu.Game.Rulesets.Osu; namespace osu.Game.Benchmarks { public class BenchmarkRuleset : BenchmarkTest { private OsuRuleset ruleset; private APIMod apiModDoubleTime; private APIMod apiModDifficultyAdjust; public override void SetUp() { base.SetUp(); ruleset = new OsuRuleset(); apiModDoubleTime = new APIMod { Acronym = "DT" }; apiModDifficultyAdjust = new APIMod { Acronym = "DA" }; } [Benchmark] public void BenchmarkToModDoubleTime() { apiModDoubleTime.ToMod(ruleset); } [Benchmark] public void BenchmarkToModDifficultyAdjust() { apiModDifficultyAdjust.ToMod(ruleset); } [Benchmark] public void BenchmarkGetAllMods() { ruleset.GetAllMods(); } } } ``` Fix enumerable not being consumed
```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 BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; using osu.Game.Online.API; using osu.Game.Rulesets.Osu; namespace osu.Game.Benchmarks { public class BenchmarkRuleset : BenchmarkTest { private OsuRuleset ruleset; private APIMod apiModDoubleTime; private APIMod apiModDifficultyAdjust; public override void SetUp() { base.SetUp(); ruleset = new OsuRuleset(); apiModDoubleTime = new APIMod { Acronym = "DT" }; apiModDifficultyAdjust = new APIMod { Acronym = "DA" }; } [Benchmark] public void BenchmarkToModDoubleTime() { apiModDoubleTime.ToMod(ruleset); } [Benchmark] public void BenchmarkToModDifficultyAdjust() { apiModDifficultyAdjust.ToMod(ruleset); } [Benchmark] public void BenchmarkGetAllMods() { ruleset.GetAllMods().Consume(new Consumer()); } } } ```
b4109255-4f86-4658-8ce1-cb310b0915f4
{ "language": "C#" }
```c# using System.IO; namespace DevTyr.Gullap.Model { public static class MetaContentExtensions { public static string GetTargetFileName(this MetaContent content, SitePaths paths) { var isPage = content.Page != null; string userDefinedFileName = content.GetOverriddenFileName(); string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName; string targetDirectory; if (isPage) { targetDirectory = Path.GetDirectoryName(targetFileName.Replace(paths.PagesPath, paths.OutputPath)); } else { targetDirectory = Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath, Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName))); } var targetPath = Path.Combine(targetDirectory, targetFileName); return targetPath; } } } ``` Fix target file name generation
```c# using System.IO; namespace DevTyr.Gullap.Model { public static class MetaContentExtensions { public static string GetTargetFileName(this MetaContent content, SitePaths paths) { var isPage = content.Page != null; string userDefinedFileName = content.GetOverriddenFileName(); string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName; string targetDirectory; if (isPage) { targetDirectory = Path.GetDirectoryName(content.FileName.Replace(paths.PagesPath, paths.OutputPath)); } else { targetDirectory = Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath, Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName))); } var targetPath = Path.Combine(targetDirectory, targetFileName); return targetPath; } } } ```
1c86295c-c031-49a4-8e8c-e7b1c34207b8
{ "language": "C#" }
```c# using Glimpse.Agent.Web; using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet; using Microsoft.Framework.DependencyInjection; namespace Glimpse.Agent.AspNet.Sample { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddGlimpse() .RunningAgent() .ForWeb() .Configure<GlimpseAgentWebOptions>(options => { //options.IgnoredStatusCodes.Add(200); }) .WithRemoteStreamAgent(); //.WithRemoteHttpAgent(); } public void Configure(IApplicationBuilder app) { app.UseGlimpse(); app.UseWelcomePage(); } } } ``` Add example of using fixed provider
```c# using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using Glimpse.Agent.Web; using Glimpse.Agent.Web.Framework; using Glimpse.Agent.Web.Options; using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet; using Microsoft.Framework.DependencyInjection; namespace Glimpse.Agent.AspNet.Sample { public class Startup { public void ConfigureServices(IServiceCollection services) { /* Example of how to use fixed provider TODO: This should be cleanned up with help of extenion methods services.AddSingleton<IIgnoredRequestProvider>(x => { var activator = x.GetService<ITypeActivator>(); var urlPolicy = activator.CreateInstances<IIgnoredRequestPolicy>(new [] { typeof(UriIgnoredRequestPolicy).GetTypeInfo(), typeof(ContentTypeIgnoredRequestPolicy).GetTypeInfo() }); var provider = new FixedIgnoredRequestProvider(urlPolicy); return provider; }); */ services.AddGlimpse() .RunningAgent() .ForWeb() .Configure<GlimpseAgentWebOptions>(options => { //options.IgnoredStatusCodes.Add(200); }) .WithRemoteStreamAgent(); //.WithRemoteHttpAgent(); } public void Configure(IApplicationBuilder app) { app.UseGlimpse(); app.UseWelcomePage(); } } } ```
ab436394-95cf-4c5d-b76a-ae6209b3a947
{ "language": "C#" }
```c# @{ Layout = "~/Views/Shared/_LayoutPublic.cshtml"; } @section metaPage { <meta property="og:type" content="website"> <meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/content/images/logo-og.jpg")"> } @RenderBody()``` Fix og:image path for home page
```c# @{ Layout = "~/Views/Shared/_LayoutPublic.cshtml"; } @section metaPage { <meta property="og:type" content="website"> <meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/images/logo-og.jpg")"> } @RenderBody()```
cacf0de9-4324-44c4-bda4-aaa1c2a17027
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Windows.Forms; namespace SqlDiffFramework { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }``` Reorganize forms into project subfolder
```c# using System; using System.Collections.Generic; using System.Windows.Forms; using SqlDiffFramework.Forms; namespace SqlDiffFramework { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }```
2e6f46e4-880d-4897-8c90-7f910d053969
{ "language": "C#" }
```c# namespace WeatherDataFunctionApp { using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; public static class WeatherDataService { private static readonly HttpClient WeatherDataHttpClient = new HttpClient(); private static readonly string ApiUrl; static WeatherDataService() { string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"]; ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}"; } [FunctionName("WeatherDataService")] public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "WeatherDataService/Current/{location}")]HttpRequestMessage req, string location, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location); if (responseMessage.IsSuccessStatusCode) return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result); log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}"); return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error."); } private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location) { return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location)); } } } ``` Read querystring instead of using route patterns
```c# namespace WeatherDataFunctionApp { using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; public static class WeatherDataService { private static readonly HttpClient WeatherDataHttpClient = new HttpClient(); private static readonly string ApiUrl; static WeatherDataService() { string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"]; ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}"; } [FunctionName("WeatherDataService")] public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); var queryNameValuePairs = req.GetQueryNameValuePairs(); var location = queryNameValuePairs.Where(pair => pair.Key.Equals("location", StringComparison.InvariantCultureIgnoreCase)).Select(queryParam => queryParam.Value).FirstOrDefault(); HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location); if (responseMessage.IsSuccessStatusCode) return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result); log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}"); return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error."); } private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location) { return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location)); } } } ```
9fbd65f2-3465-4773-bf9a-f0e7914ae67e
{ "language": "C#" }
```c# using Microsoft.Web.Administration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace Launcher { public class ExecutionMetadata { [JsonProperty("start_command")] public string DetectedStartCommand { get; set; } [JsonProperty("start_command_args")] public string[] StartCommandArgs { get; set; } } class Program { static int Main(string[] args) { if (args.Length < 3) { Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}", String.Join(" ", args)); return 1; } ExecutionMetadata executionMetadata = null; try { executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]); } catch (Exception ex) { Console.Error.WriteLine( "Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]); return 1; } var startInfo = new ProcessStartInfo { UseShellExecute = false, FileName = executionMetadata.DetectedStartCommand, Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs), }; var process = Process.Start(startInfo); process.WaitForExit(); return process.ExitCode; } } } ``` Add informational logging to launcher
```c# using Microsoft.Web.Administration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace Launcher { public class ExecutionMetadata { [JsonProperty("start_command")] public string DetectedStartCommand { get; set; } [JsonProperty("start_command_args")] public string[] StartCommandArgs { get; set; } } class Program { static int Main(string[] args) { if (args.Length < 3) { Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}", String.Join(" ", args)); return 1; } ExecutionMetadata executionMetadata = null; try { executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]); } catch (Exception ex) { Console.Error.WriteLine( "Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]); return 1; } var startInfo = new ProcessStartInfo { UseShellExecute = false, FileName = executionMetadata.DetectedStartCommand, Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs), }; Console.Out.WriteLine("Run {0} :with: {1}", startInfo.FileName, startInfo.Arguments); var process = Process.Start(startInfo); process.WaitForExit(); return process.ExitCode; } } } ```
e669720e-23ca-404e-a129-02d043618485
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CreviceApp.Threading { // http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm public class SingleThreadScheduler : TaskScheduler, IDisposable { private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>(); private readonly Thread thread; public SingleThreadScheduler() : this(ThreadPriority.Normal) { } public SingleThreadScheduler(ThreadPriority priority) { this.thread = new Thread(new ThreadStart(Main)); this.thread.Priority = priority; this.thread.Start(); } private void Main() { Verbose.Print("SingleThreadScheduler was started; Thread ID: 0x{0:X}", Thread.CurrentThread.ManagedThreadId); foreach (var t in tasks.GetConsumingEnumerable()) { TryExecuteTask(t); } } protected override IEnumerable<Task> GetScheduledTasks() { return tasks.ToArray(); } protected override void QueueTask(Task task) { tasks.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } public void Dispose() { GC.SuppressFinalize(this); tasks.CompleteAdding(); } ~SingleThreadScheduler() { Dispose(); } } } ``` Refactor verbose log of SingleThreadScheduler.
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CreviceApp.Threading { // http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm public class SingleThreadScheduler : TaskScheduler, IDisposable { private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>(); private readonly Thread thread; public SingleThreadScheduler() : this(ThreadPriority.Normal) { } public SingleThreadScheduler(ThreadPriority priority) { this.thread = new Thread(new ThreadStart(Main)); this.thread.Priority = priority; this.thread.Start(); } private void Main() { Verbose.Print("SingleThreadScheduler(ThreadID: 0x{0:X}) was started.", Thread.CurrentThread.ManagedThreadId); foreach (var t in tasks.GetConsumingEnumerable()) { TryExecuteTask(t); } } protected override IEnumerable<Task> GetScheduledTasks() { return tasks.ToArray(); } protected override void QueueTask(Task task) { tasks.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } public void Dispose() { GC.SuppressFinalize(this); tasks.CompleteAdding(); } ~SingleThreadScheduler() { Dispose(); } } } ```
df574036-09aa-45f2-ad19-c830ce5a8611
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using ecologylab.serialization; using ecologylab.attributes; namespace ecologylabFundamentalTestCases.Polymorphic { /** * * <configuration> <pref_double name="index_thumb_dist" value="200"/> </configuration> * */ public class Configuration : ElementState { [simpl_nowrap] [simpl_scope("testScope")] //[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })] [simpl_map] public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>(); #region GetterSetters public Dictionary<String, Pref> Preferences { get { return prefs; } set { prefs = value; } } #endregion internal void fillDictionary() { PrefDouble prefDouble = new PrefDouble(); prefDouble.Name = "index_thumb_dist"; prefDouble.Value = 200; Pref pref = new Pref(); pref.Name = "test_name"; prefs.Add(prefDouble.Name, prefDouble); prefs.Add(pref.Name, pref); } } } ``` Test case includes string with quotes.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using ecologylab.serialization; using ecologylab.attributes; namespace ecologylabFundamentalTestCases.Polymorphic { /** * * <configuration> <pref_double name="index_thumb_dist" value="200"/> </configuration> * */ public class Configuration : ElementState { [simpl_nowrap] [simpl_scope("testScope")] //[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })] [simpl_map] public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>(); #region GetterSetters public Dictionary<String, Pref> Preferences { get { return prefs; } set { prefs = value; } } #endregion internal void fillDictionary() { PrefDouble prefDouble = new PrefDouble(); prefDouble.Name = "index_thumb_dist \"now with a double quote\" and a 'single quote' "; prefDouble.Value = 200; Pref pref = new Pref(); pref.Name = "test_name"; prefs.Add(prefDouble.Name, prefDouble); prefs.Add(pref.Name, pref); } } } ```
5a76aa2a-c2ba-4e14-8211-628056fb4cec
{ "language": "C#" }
```c# using System; using osu.Framework.Configuration; using osu.Framework.Graphics.UserInterface; namespace osu.Game.Overlays.Options { public class CheckBoxOption : BasicCheckBox { private Bindable<bool> bindable; public Bindable<bool> Bindable { set { if (bindable != null) bindable.ValueChanged -= bindableValueChanged; bindable = value; if (bindable != null) { bool state = State == CheckBoxState.Checked; if (state != bindable.Value) State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked; bindable.ValueChanged += bindableValueChanged; } } } private void bindableValueChanged(object sender, EventArgs e) { State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked; } protected override void Dispose(bool isDisposing) { if (bindable != null) bindable.ValueChanged -= bindableValueChanged; base.Dispose(isDisposing); } protected override void OnChecked() { if (bindable != null) bindable.Value = true; base.OnChecked(); } protected override void OnUnchecked() { if (bindable != null) bindable.Value = false; base.OnChecked(); } } }``` Fix checkbox not updating correctly.
```c# using System; using osu.Framework.Configuration; using osu.Framework.Graphics.UserInterface; namespace osu.Game.Overlays.Options { public class CheckBoxOption : BasicCheckBox { private Bindable<bool> bindable; public Bindable<bool> Bindable { set { if (bindable != null) bindable.ValueChanged -= bindableValueChanged; bindable = value; if (bindable != null) { bool state = State == CheckBoxState.Checked; if (state != bindable.Value) State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked; bindable.ValueChanged += bindableValueChanged; } } } private void bindableValueChanged(object sender, EventArgs e) { State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked; } protected override void Dispose(bool isDisposing) { if (bindable != null) bindable.ValueChanged -= bindableValueChanged; base.Dispose(isDisposing); } protected override void OnChecked() { if (bindable != null) bindable.Value = true; base.OnChecked(); } protected override void OnUnchecked() { if (bindable != null) bindable.Value = false; base.OnUnchecked(); } } } ```
50590221-c272-4ccd-aad3-f94051283547
{ "language": "C#" }
```c# using System; using System.Threading; using NUnit.Framework; namespace Atata.WebDriverExtras.Tests { [TestFixture] [Parallelizable(ParallelScope.None)] public class SafeWaitTests { private SafeWait<object> wait; [SetUp] public void SetUp() { wait = new SafeWait<object>(new object()) { Timeout = TimeSpan.FromSeconds(.3), PollingInterval = TimeSpan.FromSeconds(.05) }; } [Test] public void SafeWait_Success_Immediate() { using (StopwatchAsserter.Within(0, .01)) wait.Until(_ => { return true; }); } [Test] public void SafeWait_Timeout() { using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } [Test] public void SafeWait_PollingInterval() { using (StopwatchAsserter.Within(.3, .2)) wait.Until(_ => { Thread.Sleep(TimeSpan.FromSeconds(.1)); return false; }); } [Test] public void SafeWait_PollingInterval_GreaterThanTimeout() { wait.PollingInterval = TimeSpan.FromSeconds(1); using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } } } ``` Increase toleranceSeconds in SafeWait_PollingInterval_GreaterThanTimeout test
```c# using System; using System.Threading; using NUnit.Framework; namespace Atata.WebDriverExtras.Tests { [TestFixture] [Parallelizable(ParallelScope.None)] public class SafeWaitTests { private SafeWait<object> wait; [SetUp] public void SetUp() { wait = new SafeWait<object>(new object()) { Timeout = TimeSpan.FromSeconds(.3), PollingInterval = TimeSpan.FromSeconds(.05) }; } [Test] public void SafeWait_Success_Immediate() { using (StopwatchAsserter.Within(0, .01)) wait.Until(_ => { return true; }); } [Test] public void SafeWait_Timeout() { using (StopwatchAsserter.Within(.3, .015)) wait.Until(_ => { return false; }); } [Test] public void SafeWait_PollingInterval() { using (StopwatchAsserter.Within(.3, .2)) wait.Until(_ => { Thread.Sleep(TimeSpan.FromSeconds(.1)); return false; }); } [Test] public void SafeWait_PollingInterval_GreaterThanTimeout() { wait.PollingInterval = TimeSpan.FromSeconds(1); using (StopwatchAsserter.Within(.3, .02)) wait.Until(_ => { return false; }); } } } ```
315d3e0c-54b3-4c20-b822-020eab180861
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Paymetheus { /// <summary> /// Interaction logic for Send.xaml /// </summary> public partial class Send : Page { public Send() { InitializeComponent(); } private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || ch == '.')); } } } ``` Use locale's decimal separator instead of hardcoding period.
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Paymetheus { /// <summary> /// Interaction logic for Send.xaml /// </summary> public partial class Send : Page { string decimalSep = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; public Send() { InitializeComponent(); } private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || decimalSep.Contains(ch))); } } } ```
29d1ab20-f492-4899-8896-8dc6f2a49baf
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]``` Set WinApiNet assembly as CLS-compliant
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Reflection; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] // Assembly is CLS-compliant [assembly: CLSCompliant(true)]```
a7d81395-f6b1-4d18-a186-ffeffe0a1534
{ "language": "C#" }
```c# using Silk.Data.SQL.Expressions; using Silk.Data.SQL.Queries; using System.Threading.Tasks; namespace Silk.Data.SQL.ORM.Operations { public abstract class DataOperation { /// <summary> /// Gets a value indicating if the operation can be executed as part of a batch operation. /// </summary> public abstract bool CanBeBatched { get; } /// <summary> /// Gets the SQL query needed to run the DataOperation. /// </summary> /// <returns></returns> public abstract QueryExpression GetQuery(); /// <summary> /// Process the result QueryResult set to the correct result set. /// </summary> public abstract void ProcessResult(QueryResult queryResult); /// <summary> /// Process the result QueryResult set to the correct result set. /// </summary> public abstract Task ProcessResultAsync(QueryResult queryResult); } public abstract class DataOperationWithResult<T> : DataOperation { /// <summary> /// Gets the result of the data operation. /// </summary> public abstract T Result { get; } } } ``` Add an API for getting the result of an operation without knowing it's type.
```c# using Silk.Data.SQL.Expressions; using Silk.Data.SQL.Queries; using System.Threading.Tasks; namespace Silk.Data.SQL.ORM.Operations { public abstract class DataOperation { /// <summary> /// Gets a value indicating if the operation can be executed as part of a batch operation. /// </summary> public abstract bool CanBeBatched { get; } /// <summary> /// Gets the SQL query needed to run the DataOperation. /// </summary> /// <returns></returns> public abstract QueryExpression GetQuery(); /// <summary> /// Process the result QueryResult set to the correct result set. /// </summary> public abstract void ProcessResult(QueryResult queryResult); /// <summary> /// Process the result QueryResult set to the correct result set. /// </summary> public abstract Task ProcessResultAsync(QueryResult queryResult); } public abstract class DataOperationWithResult : DataOperation { /// <summary> /// Gets the result of the data operation without a known static type. /// </summary> public abstract object UntypedResult { get; } } public abstract class DataOperationWithResult<T> : DataOperationWithResult { /// <summary> /// Gets the result of the data operation. /// </summary> public abstract T Result { get; } public override object UntypedResult => Result; } } ```
723cbb1d-cf60-4797-9bad-1ff7af2b8cff
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace SimpleReport.Model.Replacers { /// <summary> /// Used to replace xml code and remove styling from rtf text /// </summary> public class ValueReplacer : IValueReplacer { public string Replace(string inputstring) { var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring; value = XmlTextEncoder.Encode(value); return value; } private static bool IsRtf(string text) { return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal); } private static string RtfToText(string text) { try { var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text}; text = rtBox.Text; } catch (Exception ex) { // do nothing, just return faulty rtf } return text; } } } ``` Remove xml encoding in reports.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace SimpleReport.Model.Replacers { /// <summary> /// Used to replace xml code and remove styling from rtf text /// </summary> public class ValueReplacer : IValueReplacer { public string Replace(string inputstring) { var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring; return value; } private static bool IsRtf(string text) { return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal); } private static string RtfToText(string text) { try { var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text}; text = rtBox.Text; } catch (Exception ex) { // do nothing, just return faulty rtf } return text; } } } ```
b31f89f9-b638-4acb-9fd6-2999b129c29c
{ "language": "C#" }
```c# using System; using System.Web; using System.Web.Hosting; using System.Configuration; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { PackagePhysicalPath = packagePath; } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ``` Check if the specified path is a physical or a virtual path
```c# using System; using System.Web; using System.Web.Hosting; using System.Configuration; using System.IO; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { if (Path.IsPathRooted(packagePath)) { PackagePhysicalPath = packagePath; } else { PackagePhysicalPath = HostingEnvironment.MapPath(packagePath); } } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } } ```
ecd67b71-aa5f-43fb-ae53-39e57bd6b165
{ "language": "C#" }
```c# using static System.Console; namespace ConsoleApp { class Program { private static void Main() { var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; var schemaName = "dbo"; var tableName = "Book"; var columnsProvider = new ColumnsProvider(connectionString); var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } } ``` Read parameters from command line arguments
```c# using static System.Console; namespace ConsoleApp { class Program { private static void Main(string[] args) { if (args.Length != 3) { WriteLine("Usage: schema2fm.exe connectionstring schema table"); return; } var connectionString = args[0];//@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"; var schemaName = args[1];//"dbo"; var tableName = args[2];//"Book"; var columnsProvider = new ColumnsProvider(connectionString); var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(Out); } } } ```
460701b5-6793-49d9-bb45-8dda97cb6758
{ "language": "C#" }
```c# #region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName); var installModel = new InstallModel(); Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext); moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer; moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName; moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password; ModuleInfo.Save(moduleInfo); // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } } ``` Update the Empty module template.
```c# #region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } } ```
30c46e43-f3c1-4680-bdc6-1f47122cbb56
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DigitalOcean.Structs { public class Droplet { public int id { get; set; } public string name { get; set; } public int image_id { get; set; } public int size_id { get; set; } public int region_id { get; set; } public bool backups_active { get; set; } public string ip_address { get; set; } public object private_ip_address { get; set; } public bool locked { get; set; } public string status { get; set; } public string created_at { get; set; } } public class Droplets { public string status { get; set; } public List<Droplet> droplets { get; set; } } } ``` Make way for the extended information which can be requested using the Show Droplet request.
```c# using System.Collections.Generic; namespace DigitalOcean.Structs { public class Droplet { public int id { get; set; } public int image_id { get; set; } public string name { get; set; } public int region_id { get; set; } public int size_id { get; set; } public bool backups_active { get; set; } public List<object> backups { get; set; } //extended public List<object> snapshots { get; set; } //extended public string ip_address { get; set; } public object private_ip_address { get; set; } public bool locked { get; set; } public string status { get; set; } public string created_at { get; set; } } public class Droplets { public string status { get; set; } public List<Droplet> droplets { get; set; } } }```
6e0b4e56-1785-424a-baa5-86acaeb2bf4e
{ "language": "C#" }
```c# using MyDocs.Common; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Logic = MyDocs.Common.Model.Logic; namespace JsonNetDal { public class SubDocument { public string Title { get; set; } public string File { get; set; } public List<string> Photos { get; set; } public SubDocument() { } public SubDocument(string title, string file, IEnumerable<string> photos) { Title = title; File = file; Photos = photos.ToList(); } public static SubDocument FromLogic(Logic.SubDocument subDocument) { return new SubDocument(subDocument.Title, subDocument.File.GetUri().AbsoluteUri, subDocument.Photos.Select(p => p.File.GetUri().AbsoluteUri)); } public async Task<Logic.SubDocument> ToLogic() { var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(File)); var photoTasks = Photos .Select(p => new Uri(p)) .Select(StorageFile.GetFileFromApplicationUriAsync) .Select(x => x.AsTask()); var photos = await Task.WhenAll(photoTasks); return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p))); } } } ``` Use Uri's for subdocument file and photos
```c# using MyDocs.Common; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Logic = MyDocs.Common.Model.Logic; namespace JsonNetDal { public class SubDocument { public string Title { get; set; } public Uri File { get; set; } public List<Uri> Photos { get; set; } public SubDocument() { } public SubDocument(string title, Uri file, IEnumerable<Uri> photos) { Title = title; File = file; Photos = photos.ToList(); } public static SubDocument FromLogic(Logic.SubDocument subDocument) { return new SubDocument(subDocument.Title, subDocument.File.GetUri(), subDocument.Photos.Select(p => p.File.GetUri())); } public async Task<Logic.SubDocument> ToLogic() { var file = await StorageFile.GetFileFromApplicationUriAsync(File); var photoTasks = Photos .Select(StorageFile.GetFileFromApplicationUriAsync) .Select(x => x.AsTask()); var photos = await Task.WhenAll(photoTasks); return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p))); } } } ```
775b65c6-082b-45aa-b8ab-739ad973bb7e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; namespace Cronus.Core.Eventing { /// <summary> /// Represents an in memory event messaging destribution /// </summary> public class InMemoryEventBus : AbstractEventBus { /// <summary> /// Publishes the given event to all registered event handlers /// </summary> /// <param name="event">An event instance</param> public override bool Publish(IEvent @event) { onPublishEvent(@event); foreach (var handleMethod in handlers[@event.GetType()]) { var result = handleMethod(@event); if (result == false) return result; } onEventPublished(@event); return true; } public override Task<bool> PublishAsync(IEvent @event) { return Threading.RunAsync(() => Publish(@event)); } } } ``` Fix major bug when getting event handlers
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Cronus.Core.Eventing { /// <summary> /// Represents an in memory event messaging destribution /// </summary> public class InMemoryEventBus : AbstractEventBus { /// <summary> /// Publishes the given event to all registered event handlers /// </summary> /// <param name="event">An event instance</param> public override bool Publish(IEvent @event) { onPublishEvent(@event); List<Func<IEvent, bool>> eventHandlers; if (handlers.TryGetValue(@event.GetType(), out eventHandlers)) { foreach (var handleMethod in eventHandlers) { var result = handleMethod(@event); if (result == false) return result; } } onEventPublished(@event); return true; } public override Task<bool> PublishAsync(IEvent @event) { return Threading.RunAsync(() => Publish(@event)); } } }```
31fe9ce9-a158-4f64-a4ce-446c816da57c
{ "language": "C#" }
```c# using Gigobyte.Daterpillar.Arguments; using Gigobyte.Daterpillar.Commands; using System; namespace Gigobyte.Daterpillar { public class Program { internal static void Main(string[] args) { InitializeWindow(); start: var options = new Options(); if (args.Length > 0) { CommandLine.Parser.Default.ParseArguments(args, options, onVerbCommand: (verb, arg) => { ICommand command = new CommandFactory().CrateInstance(verb); try { _exitCode = command.Execute(arg); } catch (Exception ex) { _exitCode = ExitCode.UnhandledException; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); } }); } else { Console.WriteLine(options.GetHelp()); args = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' }); goto start; } Environment.Exit(_exitCode); } #region Private Members private static int _exitCode; private static void InitializeWindow() { Console.Title = $"{nameof(Daterpillar)} CLI"; } #endregion Private Members } }``` Remove goto statements from command line program
```c# using Gigobyte.Daterpillar.Arguments; using Gigobyte.Daterpillar.Commands; using System; namespace Gigobyte.Daterpillar { public class Program { internal static void Main(string[] args) { InitializeWindow(); do { var commandLineOptions = new Options(); if (args.Length > 0) { CommandLine.Parser.Default.ParseArguments(args, commandLineOptions, onVerbCommand: (verb, arg) => { ICommand command = new CommandFactory().CrateInstance(verb); try { _exitCode = command.Execute(arg); } catch (Exception ex) { _exitCode = ExitCode.UnhandledException; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); } finally { Console.ResetColor(); } }); break; } else { Console.WriteLine(commandLineOptions.GetHelp()); args = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' }); } } while (true); Environment.Exit(_exitCode); } #region Private Members private static int _exitCode; private static void InitializeWindow() { Console.Title = $"{nameof(Daterpillar)} CLI"; } #endregion Private Members } }```
8e30d633-6228-4901-81e8-8db656cd295c
{ "language": "C#" }
```c# #if NET45 using System; using Microsoft.Owin.Hosting; namespace MvcSample { public class Program { const string baseUrl = "http://localhost:9001/"; public static void Main() { using (WebApp.Start<Startup>(new StartOptions(baseUrl))) { Console.WriteLine("Listening at {0}", baseUrl); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } } } #endif``` Print hello world for k10 project.
```c# using System; #if NET45 using Microsoft.Owin.Hosting; #endif namespace MvcSample { public class Program { const string baseUrl = "http://localhost:9001/"; public static void Main() { #if NET45 using (WebApp.Start<Startup>(new StartOptions(baseUrl))) { Console.WriteLine("Listening at {0}", baseUrl); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } #else Console.WriteLine("Hello World"); #endif } } }```
119de941-4ed0-4fdf-8200-d4856c00237c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.WebJobs; namespace TaskWebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { using (var host = new JobHost()) { host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow }); } } } } ``` Add classes for prime numbers
```c# using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.WebJobs; namespace TaskWebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { using (var host = new JobHost()) { host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow }); } } } public static class PrimeNumbers { public static IEnumerable<long> GetPrimeNumbers(long minValue, long maxValue) => new[] { new { primes = new List<long>(), min = Math.Max(minValue, 2), max = Math.Max(maxValue, 0), root_max = maxValue >= 0 ? (long)Math.Sqrt(maxValue) : 0, } } .SelectMany(_ => Enumerable2.Range2(2, Math.Min(_.root_max, _.min - 1)) .Concat(Enumerable2.Range2(_.min, _.max)) .Select(i => new { _.primes, i, root_i = (long)Math.Sqrt(i) })) .Where(_ => _.primes .TakeWhile(p => p <= _.root_i) .All(p => _.i % p != 0)) .Do(_ => _.primes.Add(_.i)) .Select(_ => _.i) .SkipWhile(i => i < minValue); } public static class Enumerable2 { public static IEnumerable<long> Range2(long minValue, long maxValue) { for (var i = minValue; i <= maxValue; i++) { yield return i; } } public static IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); foreach (var item in source) { action(item); yield return item; } } } } ```
07ba4e26-718f-4014-a46d-c6cef6dc8d21
{ "language": "C#" }
```c# /* ---------------------------------------------------------------------- Numenta Platform for Intelligent Computing (NuPIC) Copyright (C) 2015, Numenta, Inc. Unless you have an agreement with Numenta, Inc., for a separate license for this software code, the following terms and conditions apply: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses. http://numenta.org/licenses/ ---------------------------------------------------------------------- */ using UnityEngine; using System.Collections; public class CarCollisions : MonoBehaviour { void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "Boundary") { Application.LoadLevel(Application.loadedLevel); } else if (collision.gameObject.tag == "Finish") { Application.LoadLevel(Application.loadedLevel + 1); } } } ``` Add resets when reloading level
```c# /* ---------------------------------------------------------------------- Numenta Platform for Intelligent Computing (NuPIC) Copyright (C) 2015, Numenta, Inc. Unless you have an agreement with Numenta, Inc., for a separate license for this software code, the following terms and conditions apply: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses. http://numenta.org/licenses/ ---------------------------------------------------------------------- */ using UnityEngine; using System.Collections; public class CarCollisions : MonoBehaviour { void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "Boundary") { API.instance.Reset(); Application.LoadLevel(Application.loadedLevel); } else if (collision.gameObject.tag == "Finish") { API.instance.Reset(); Application.LoadLevel(Application.loadedLevel + 1); } } } ```
d12fc465-9bab-4c54-9a8d-c54848e0e31d
{ "language": "C#" }
```c# using NBi.Core.ResultSet; using System; using System.Globalization; using System.Linq; namespace NBi.Core.Scalar.Comparer { public class ToleranceFactory { public static Tolerance Instantiate(IColumnDefinition columnDefinition) { if (columnDefinition.Role != ColumnRole.Value) throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition"); return Instantiate(columnDefinition.Type, columnDefinition.Tolerance); } public static Tolerance Instantiate(ColumnType type, string value) { if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) return null; Tolerance tolerance=null; switch (type) { case ColumnType.Text: tolerance = new TextToleranceFactory().Instantiate(value); break; case ColumnType.Numeric: tolerance = new NumericToleranceFactory().Instantiate(value); break; case ColumnType.DateTime: tolerance = new DateTimeToleranceFactory().Instantiate(value); break; case ColumnType.Boolean: break; default: break; } return tolerance; } public static Tolerance None(ColumnType type) { Tolerance tolerance = null; switch (type) { case ColumnType.Text: tolerance = TextSingleMethodTolerance.None; break; case ColumnType.Numeric: tolerance = NumericAbsoluteTolerance.None; break; case ColumnType.DateTime: tolerance = DateTimeTolerance.None; break; case ColumnType.Boolean: break; default: break; } return tolerance; } } } ``` Fix huge bug related to instantiation of tolerance
```c# using NBi.Core.ResultSet; using System; using System.Globalization; using System.Linq; namespace NBi.Core.Scalar.Comparer { public class ToleranceFactory { public static Tolerance Instantiate(IColumnDefinition columnDefinition) { if (string.IsNullOrEmpty(columnDefinition.Tolerance) || string.IsNullOrWhiteSpace(columnDefinition.Tolerance)) return null; if (columnDefinition.Role != ColumnRole.Value) throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition"); return Instantiate(columnDefinition.Type, columnDefinition.Tolerance); } public static Tolerance Instantiate(ColumnType type, string value) { Tolerance tolerance=null; switch (type) { case ColumnType.Text: tolerance = new TextToleranceFactory().Instantiate(value); break; case ColumnType.Numeric: tolerance = new NumericToleranceFactory().Instantiate(value); break; case ColumnType.DateTime: tolerance = new DateTimeToleranceFactory().Instantiate(value); break; case ColumnType.Boolean: break; default: break; } return tolerance; } public static Tolerance None(ColumnType type) { Tolerance tolerance = null; switch (type) { case ColumnType.Text: tolerance = TextSingleMethodTolerance.None; break; case ColumnType.Numeric: tolerance = NumericAbsoluteTolerance.None; break; case ColumnType.DateTime: tolerance = DateTimeTolerance.None; break; case ColumnType.Boolean: break; default: break; } return tolerance; } } } ```
81c5eea0-700a-4944-8809-bf675d99c478
{ "language": "C#" }
```c# using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using ActiproSoftware.Text.Implementation; using NQuery.Language.Services.BraceMatching; namespace NQuery.Language.ActiproWpf { public sealed class NQueryLanguage : SyntaxLanguage, IDisposable { private readonly CompositionContainer _compositionContainer; public NQueryLanguage() : this(GetDefaultCatalog()) { } public NQueryLanguage(ComposablePartCatalog catalog) : base("NQuery") { _compositionContainer = new CompositionContainer(catalog); _compositionContainer.SatisfyImportsOnce(this); var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>(); foreach (var serviceProvider in serviceProviders) serviceProvider.RegisterServices(this); } private static ComposablePartCatalog GetDefaultCatalog() { var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly); var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly); return new AggregateCatalog(servicesAssembly, thisAssembly); } public void Dispose() { _compositionContainer.Dispose(); } } }``` Fix Actipro language to construct the correct set of language services
```c# using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using ActiproSoftware.Text.Implementation; using NQuery.Language.Services.BraceMatching; using NQuery.Language.Wpf; namespace NQuery.Language.ActiproWpf { public sealed class NQueryLanguage : SyntaxLanguage, IDisposable { private readonly CompositionContainer _compositionContainer; public NQueryLanguage() : this(GetDefaultCatalog()) { } public NQueryLanguage(ComposablePartCatalog catalog) : base("NQuery") { _compositionContainer = new CompositionContainer(catalog); _compositionContainer.SatisfyImportsOnce(this); var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>(); foreach (var serviceProvider in serviceProviders) serviceProvider.RegisterServices(this); } private static ComposablePartCatalog GetDefaultCatalog() { var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly); var wpfAssembly = new AssemblyCatalog(typeof(INQueryGlyphService).Assembly); var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly); return new AggregateCatalog(servicesAssembly, wpfAssembly, thisAssembly); } public void Dispose() { _compositionContainer.Dispose(); } } }```
63ee139b-f275-404b-a0f8-e72795c570ae
{ "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.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsTextBox : SettingsItem<string> { protected override Drawable CreateControl() => new OsuTextBox { Margin = new MarginPadding { Top = 5 }, RelativeSizeAxes = Axes.X, }; } } ``` Make settings textboxes commit on focus lost
```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.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsTextBox : SettingsItem<string> { protected override Drawable CreateControl() => new OsuTextBox { Margin = new MarginPadding { Top = 5 }, RelativeSizeAxes = Axes.X, CommitOnFocusLost = true, }; } } ```
db1be16d-f116-492b-b0b2-be4e9350495f
{ "language": "C#" }
```c# namespace NuGetPe { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "http://www.nuget.org/api/v2/"; public static readonly string V2LegacyFeedUrl = "https://nuget.org/api/v2/"; public static readonly string PluginFeedUrl = "http://www.myget.org/F/npe/"; public const string V2LegacyNuGetPublishFeed = "https://nuget.org"; public const string NuGetPublishFeed = "https://www.nuget.org"; } }``` Update nuget url to https
```c# namespace NuGetPe { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://www.nuget.org/api/v2/"; public static readonly string V2LegacyFeedUrl = "https://nuget.org/api/v2/"; public static readonly string PluginFeedUrl = "http://www.myget.org/F/npe/"; public const string V2LegacyNuGetPublishFeed = "https://nuget.org"; public const string NuGetPublishFeed = "https://www.nuget.org"; } }```
0ffe243d-0a92-4e45-a559-6f63a30abcd5
{ "language": "C#" }
```c# /* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.LogEvents; using System; using System.Threading.Tasks; namespace NuLog.Targets { public class ConsoleTarget : LayoutTargetBase { public override void Write(LogEvent logEvent) { var message = Layout.Format(logEvent); Console.Write(message); } } }``` Remove reference to unused "Tasks".
```c# /* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.LogEvents; using System; namespace NuLog.Targets { public class ConsoleTarget : LayoutTargetBase { public override void Write(LogEvent logEvent) { var message = Layout.Format(logEvent); Console.Write(message); } } }```
fd617caa-9c6a-42f0-a9e9-a0a5c9dc7437
{ "language": "C#" }
```c# // <copyright file="QtCreatorBuilder.cs" company="Mark Final"> // Opus package // </copyright> // <summary>QtCreator package</summary> // <author>Mark Final</author> [assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))] // Automatically generated by Opus v0.20 namespace QtCreatorBuilder { public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder { public static string GetProFilePath(Opus.Core.DependencyNode node) { //string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake"); string proFileDirectory = node.GetModuleBuildDirectory(); string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target)); Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath); return proFilePath; } public static string GetQtConfiguration(Opus.Core.Target target) { if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized) { throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations"); } string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release"; return QtCreatorConfiguration; } } } ``` Simplify the .pro file names
```c# // <copyright file="QtCreatorBuilder.cs" company="Mark Final"> // Opus package // </copyright> // <summary>QtCreator package</summary> // <author>Mark Final</author> [assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))] // Automatically generated by Opus v0.20 namespace QtCreatorBuilder { public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder { public static string GetProFilePath(Opus.Core.DependencyNode node) { //string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake"); string proFileDirectory = node.GetModuleBuildDirectory(); //string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target)); string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}.pro", node.ModuleName)); Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath); return proFilePath; } public static string GetQtConfiguration(Opus.Core.Target target) { if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized) { throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations"); } string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release"; return QtCreatorConfiguration; } } } ```
3838911a-b07b-4ff9-ae2d-d3bf656702cb
{ "language": "C#" }
```c# using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Zk.Models; using Zk.Services; using Zk.Repositories; namespace Zk { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<ZkContext>() .As<IZkContext>() .InstancePerRequest(); builder.RegisterType<Repository>(); builder.RegisterType<AuthenticationService>(); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated); builder.RegisterType<PasswordRecoveryService>(); builder.RegisterType<CalendarService>(); builder.RegisterType<FarmingActionService>(); builder.RegisterType<CropProvider>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }``` Add instanceperrequest lifetime scope to all services
```c# using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Zk.Models; using Zk.Services; using Zk.Repositories; namespace Zk { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<ZkContext>() .As<IZkContext>() .InstancePerRequest(); builder.RegisterType<Repository>() .InstancePerRequest(); builder.RegisterType<AuthenticationService>() .InstancePerRequest(); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated); builder.RegisterType<PasswordRecoveryService>() .InstancePerRequest(); builder.RegisterType<CalendarService>() .InstancePerRequest(); builder.RegisterType<FarmingActionService>() .InstancePerRequest(); builder.RegisterType<CropProvider>() .InstancePerRequest();; var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }```
3aa7e860-e7da-4583-a9b5-0d17d38d0540
{ "language": "C#" }
```c# using System; namespace DAQ.Environment { public class PHBonesawFileSystem : DAQ.Environment.FileSystem { public PHBonesawFileSystem() { Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box\\CaF MOT\\MOTData\\MOTMasterData\\"); Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts"); Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll"); Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\"); Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\"); Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs"); DataSearchPaths.Add(Paths["scanMasterDataPath"]); SortDataByDate = false; } } } ``` Change CaF file system paths
```c# using System; namespace DAQ.Environment { public class PHBonesawFileSystem : DAQ.Environment.FileSystem { public PHBonesawFileSystem() { Paths.Add("MOTMasterDataPath", "C:\\Users\\cafmot\\Box Sync\\CaF MOT\\MOTData\\MOTMasterData\\"); Paths.Add("scriptListPath", "C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts"); Paths.Add("daqDLLPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\bin\\CaF\\daq.dll"); Paths.Add("MOTMasterExePath", "C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\"); Paths.Add("ExternalFilesPath", "C:\\Users\\cafmot\\Documents\\Temp Camera Images\\"); Paths.Add("HardwareClassPath", "C:\\ControlPrograms\\EDMSuite\\DAQ\\MoleculeMOTHardware.cs"); DataSearchPaths.Add(Paths["scanMasterDataPath"]); SortDataByDate = false; } } } ```
6bf594d7-8b9d-438f-8cda-549851e5240c
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared] internal class ProjectTypeLookupService : IProjectTypeLookupService { public string GetProjectType(Workspace workspace, ProjectId projectId) { if (workspace == null || projectId == null) { return string.Empty; } var vsWorkspace = workspace as VisualStudioWorkspace; var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject; if (aggregatableProject == null) { return string.Empty; } if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType))) { return projectType; } return projectType ?? string.Empty; } } } ``` Fix incorrect assumption that a workspace is a Visual Studio workspace
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared] internal class ProjectTypeLookupService : IProjectTypeLookupService { public string GetProjectType(Workspace workspace, ProjectId projectId) { if (!(workspace is VisualStudioWorkspace vsWorkspace) || projectId == null) { return string.Empty; } var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject; if (aggregatableProject == null) { return string.Empty; } if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType))) { return projectType; } return projectType ?? string.Empty; } } } ```
9885fac5-d62d-4881-ac5a-948360eaab42
{ "language": "C#" }
```c# @model dynamic @using Umbraco.Web.Templates @if (Model.value != null) { var url = Model.value.image; if(Model.editor.config != null && Model.editor.config.size != null){ url += "?width=" + Model.editor.config.size.width; url += "&height=" + Model.editor.config.size.height; if(Model.value.focalPoint != null){ url += "&center=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left; url += "&mode=crop"; } } <img src="@url" alt="@Model.value.caption"> if (Model.value.caption != null) { <p class="caption">@Model.value.caption</p> } } ``` Fix for U4-10821, render alt text attribute from grid image editor, or empty string if null (for screen readers)
```c# @model dynamic @using Umbraco.Web.Templates @if (Model.value != null) { var url = Model.value.image; if(Model.editor.config != null && Model.editor.config.size != null){ url += "?width=" + Model.editor.config.size.width; url += "&height=" + Model.editor.config.size.height; if(Model.value.focalPoint != null){ url += "&center=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left; url += "&mode=crop"; } } var altText = Model.value.altText ?? String.Empty; <img src="@url" alt="@altText"> if (Model.value.caption != null) { <p class="caption">@Model.value.caption</p> } } ```
f427c8db-e224-4f08-9a7d-448b9ab61b29
{ "language": "C#" }
```c# using System; using Sancho.DOM.XamarinForms; using Sancho.XAMLParser; using TabletDesigner.Helpers; using Xamarin.Forms; namespace TabletDesigner { public interface ILogAccess { void Clear(); string Log { get; } } public partial class TabletDesignerPage : ContentPage { ILogAccess logAccess; public TabletDesignerPage() { InitializeComponent(); logAccess = DependencyService.Get<ILogAccess>(); } protected override void OnAppearing() { base.OnAppearing(); editor.Text = Settings.Xaml; } void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { try { Settings.Xaml = editor.Text; logAccess.Clear(); var parser = new Parser(); var rootNode = parser.Parse(e.NewTextValue); rootNode = new ContentNodeProcessor().Process(rootNode); rootNode = new ExpandedPropertiesProcessor().Process(rootNode); var view = new XamlDOMCreator().CreateNode(rootNode) as View; Root.Content = view; LoggerOutput.Text = logAccess.Log; LoggerOutput.TextColor = Color.White; } catch (Exception ex) { LoggerOutput.Text = ex.ToString(); LoggerOutput.TextColor = Color.FromHex("#FF3030"); } } } } ``` Handle content pages as well
```c# using System; using Sancho.DOM.XamarinForms; using Sancho.XAMLParser; using TabletDesigner.Helpers; using Xamarin.Forms; namespace TabletDesigner { public interface ILogAccess { void Clear(); string Log { get; } } public partial class TabletDesignerPage : ContentPage { ILogAccess logAccess; public TabletDesignerPage() { InitializeComponent(); logAccess = DependencyService.Get<ILogAccess>(); } protected override void OnAppearing() { base.OnAppearing(); editor.Text = Settings.Xaml; } void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { try { Settings.Xaml = editor.Text; logAccess.Clear(); var parser = new Parser(); var rootNode = parser.Parse(e.NewTextValue); rootNode = new ContentNodeProcessor().Process(rootNode); rootNode = new ExpandedPropertiesProcessor().Process(rootNode); var dom = new XamlDOMCreator().CreateNode(rootNode); if (dom is View) Root.Content = (View)dom; else if (dom is ContentPage) Root.Content = ((ContentPage)dom).Content; LoggerOutput.Text = logAccess.Log; LoggerOutput.TextColor = Color.White; } catch (Exception ex) { LoggerOutput.Text = ex.ToString(); LoggerOutput.TextColor = Color.FromHex("#FF3030"); } } } } ```
b25b05ac-e813-431c-b1c2-a2ea4d5b94f4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Ast.Transforms; using ICSharpCode.NRefactory.CSharp; namespace JSIL { public class DeclarationHoister : ContextTrackingVisitor<object> { public readonly BlockStatement Output; public VariableDeclarationStatement Statement = null; public readonly HashSet<string> HoistedNames = new HashSet<string>(); public DeclarationHoister (DecompilerContext context, BlockStatement output) : base(context) { Output = output; } public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) { if (Statement == null) { Statement = new VariableDeclarationStatement(); Output.Add(Statement); } foreach (var variable in variableDeclarationStatement.Variables) { if (!HoistedNames.Contains(variable.Name)) { Statement.Variables.Add(new VariableInitializer( variable.Name )); HoistedNames.Add(variable.Name); } } var replacement = new BlockStatement(); foreach (var variable in variableDeclarationStatement.Variables) { replacement.Add(new ExpressionStatement(new AssignmentExpression { Left = new IdentifierExpression(variable.Name), Right = variable.Initializer.Clone() })); } if (replacement.Statements.Count == 1) { var firstChild = replacement.FirstChild; firstChild.Remove(); variableDeclarationStatement.ReplaceWith(firstChild); } else if (replacement.Statements.Count > 1) { variableDeclarationStatement.ReplaceWith(replacement); } return null; } } } ``` Fix hoisting of null initializers
```c# using System; using System.Collections.Generic; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Ast.Transforms; using ICSharpCode.NRefactory.CSharp; namespace JSIL { public class DeclarationHoister : ContextTrackingVisitor<object> { public readonly BlockStatement Output; public VariableDeclarationStatement Statement = null; public readonly HashSet<string> HoistedNames = new HashSet<string>(); public DeclarationHoister (DecompilerContext context, BlockStatement output) : base(context) { Output = output; } public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) { if (Statement == null) { Statement = new VariableDeclarationStatement(); Output.Add(Statement); } foreach (var variable in variableDeclarationStatement.Variables) { if (!HoistedNames.Contains(variable.Name)) { Statement.Variables.Add(new VariableInitializer( variable.Name )); HoistedNames.Add(variable.Name); } } var replacement = new BlockStatement(); foreach (var variable in variableDeclarationStatement.Variables) { if (variable.IsNull) continue; if (variable.Initializer.IsNull) continue; replacement.Add(new ExpressionStatement(new AssignmentExpression { Left = new IdentifierExpression(variable.Name), Right = variable.Initializer.Clone() })); } if (replacement.Statements.Count == 1) { var firstChild = replacement.FirstChild; firstChild.Remove(); variableDeclarationStatement.ReplaceWith(firstChild); } else if (replacement.Statements.Count > 1) { variableDeclarationStatement.ReplaceWith(replacement); } else { variableDeclarationStatement.Remove(); } return null; } } } ```
d3516996-c0b7-4d8d-a73f-f3c4ddcd2a88
{ "language": "C#" }
```c# using Avalonia.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avalonia.Data.Core { internal abstract class SettableNode : ExpressionNode { public bool SetTargetValue(object value, BindingPriority priority) { if (ShouldNotSet(value)) { return true; } return SetTargetValueCore(value, priority); } private bool ShouldNotSet(object value) { if (PropertyType == null) { return false; } if (PropertyType.IsValueType) { return LastValue?.Target.Equals(value) ?? false; } return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value); } protected abstract bool SetTargetValueCore(object value, BindingPriority priority); public abstract Type PropertyType { get; } } } ``` Fix codepath where the property is a value type but the weakreference has been collected.
```c# using Avalonia.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avalonia.Data.Core { internal abstract class SettableNode : ExpressionNode { public bool SetTargetValue(object value, BindingPriority priority) { if (ShouldNotSet(value)) { return true; } return SetTargetValueCore(value, priority); } private bool ShouldNotSet(object value) { if (PropertyType == null) { return false; } if (PropertyType.IsValueType) { return LastValue?.Target != null && LastValue.Target.Equals(value); } return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value); } protected abstract bool SetTargetValueCore(object value, BindingPriority priority); public abstract Type PropertyType { get; } } } ```
52e7c497-ba71-47ae-befa-049575db20d4
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; namespace FilterLists.SharedKernel.Logging { public static class HostRunner { public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default) { _ = host ?? throw new ArgumentNullException(nameof(host)); InitializeLogger(host); try { if (runPreHostAsync != null) { Log.Information("Initializing pre-host"); await runPreHostAsync(); } Log.Information("Initializing host"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } private static void InitializeLogger(IHost host) { var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>(); Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration .ReadFrom.Configuration(host.Services.GetRequiredService<IConfiguration>()) .Enrich.WithProperty("Application", hostEnvironment.ApplicationName) .Enrich.WithProperty("Environment", hostEnvironment.EnvironmentName) .WriteTo.Conditional( _ => !hostEnvironment.IsProduction(), sc => sc.Console().WriteTo.Debug()) .WriteTo.Conditional( _ => hostEnvironment.IsProduction(), sc => sc.ApplicationInsights( host.Services.GetRequiredService<TelemetryConfiguration>(), TelemetryConverter.Traces)) .CreateLogger(); } } } ``` Revert "fix(logging): 🐛 try yet another AppInsights config"
```c# using System; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; namespace FilterLists.SharedKernel.Logging { public static class HostRunner { public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default) { _ = host ?? throw new ArgumentNullException(nameof(host)); Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration .WriteTo.Conditional( _ => host.Services.GetService<IHostEnvironment>().IsProduction(), c => c.ApplicationInsights( TelemetryConfiguration.CreateDefault(), TelemetryConverter.Traces)) .CreateLogger(); try { if (runPreHostAsync != null) { Log.Information("Initializing pre-host"); await runPreHostAsync(); } Log.Information("Initializing host"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } } } ```
e135cb8c-b866-4e01-8af1-9fdb320bdcf3
{ "language": "C#" }
```c# using System; using System.Xml; namespace FluentNHibernate.Mapping { public class ImportPart : IMappingPart { private readonly Cache<string, string> attributes = new Cache<string, string>(); private readonly Type importType; public ImportPart(Type importType) { this.importType = importType; } public void SetAttribute(string name, string value) { attributes.Store(name, value); } public void SetAttributes(Attributes attrs) { foreach (var key in attrs.Keys) { SetAttribute(key, attrs[key]); } } public void Write(XmlElement classElement, IMappingVisitor visitor) { var importElement = classElement.AddElement("import") .WithAtt("class", importType.AssemblyQualifiedName); attributes.ForEachPair((name, value) => importElement.WithAtt(name, value)); } public void As(string alternativeName) { SetAttribute("rename", alternativeName); } public int Level { get { return 1; } } public PartPosition Position { get { return PartPosition.First; } } } }``` Fix import tag to have correct namespace
```c# using System; using System.Xml; namespace FluentNHibernate.Mapping { public class ImportPart : IMappingPart { private readonly Cache<string, string> attributes = new Cache<string, string>(); private readonly Type importType; public ImportPart(Type importType) { this.importType = importType; } public void SetAttribute(string name, string value) { attributes.Store(name, value); } public void SetAttributes(Attributes attrs) { foreach (var key in attrs.Keys) { SetAttribute(key, attrs[key]); } } public void Write(XmlElement classElement, IMappingVisitor visitor) { var importElement = classElement.AddElement("import") .WithAtt("class", importType.AssemblyQualifiedName) .WithAtt("xmlns", "urn:nhibernate-mapping-2.2"); attributes.ForEachPair((name, value) => importElement.WithAtt(name, value)); } public void As(string alternativeName) { SetAttribute("rename", alternativeName); } public int Level { get { return 1; } } public PartPosition Position { get { return PartPosition.First; } } } }```
aba9ffc7-753d-4a77-b024-635d899e681f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Microsoft.Xaml.Behaviors; namespace Monitorian.Core.Views.Behaviors { public class FocusElementAction : TriggerAction<DependencyObject> { public UIElement TargetElement { get { return (UIElement)GetValue(TargetElementProperty); } set { SetValue(TargetElementProperty, value); } } public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register( "TargetElement", typeof(UIElement), typeof(FocusElementAction), new PropertyMetadata(null)); protected override void Invoke(object parameter) { if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused) return; TargetElement.Focus(); } } }``` Modify PropertyMetadata for correct overloading
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Microsoft.Xaml.Behaviors; namespace Monitorian.Core.Views.Behaviors { public class FocusElementAction : TriggerAction<DependencyObject> { public UIElement TargetElement { get { return (UIElement)GetValue(TargetElementProperty); } set { SetValue(TargetElementProperty, value); } } public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register( "TargetElement", typeof(UIElement), typeof(FocusElementAction), new PropertyMetadata(default(UIElement))); protected override void Invoke(object parameter) { if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused) return; TargetElement.Focus(); } } }```
890a93b9-e18a-4b19-844e-f1074ece58a4
{ "language": "C#" }
```c# #if !NO_UNITY using System; using UnityEngine; using UnityEngine.Events; namespace FullSerializer { partial class fsConverterRegistrar { public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter; } } namespace FullSerializer.Internal.Converters { // The standard FS reflection converter has started causing Unity to crash when processing // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly // instead. // // We have to support legacy serialization formats so importing works as expected. public class UnityEvent_Converter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false; } public override bool RequestCycleSupport(Type storageType) { return false; } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return result; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { fsResult result = fsResult.Success; serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); return result; } } } #endif``` Disable UnityEvent workaround since it is broken in Full Inspector
```c# #if !NO_UNITY using System; using UnityEngine; using UnityEngine.Events; namespace FullSerializer { partial class fsConverterRegistrar { // Disable the converter for the time being. Unity's JsonUtility API cannot be called from // within a C# ISerializationCallbackReceiver callback. // public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter; } } namespace FullSerializer.Internal.Converters { // The standard FS reflection converter has started causing Unity to crash when processing // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly // instead. // // We have to support legacy serialization formats so importing works as expected. public class UnityEvent_Converter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false; } public override bool RequestCycleSupport(Type storageType) { return false; } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return result; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { fsResult result = fsResult.Success; serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); return result; } } } #endif```
70a5b82e-788b-4e79-b2b6-cda04dba4d55
{ "language": "C#" }
```c# using System.Collections.Generic; using Newtonsoft.Json; using SurveyMonkey.Enums; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class Recipient : IPageableContainer { public long? Id { get; set; } public long? SurveyId { get; set; } internal string Href { get; set; } public string Email { get; set; } public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; } public MessageStatus? MailStatus { get; set; } public Dictionary<string, string> CustomFields { get; set; } public string SurveyLink { get; set; } public string RemoveLink { get; set; } public Dictionary<string, string> ExtraFields { get; set; } } }``` Include first & last names for recipients
```c# using System.Collections.Generic; using Newtonsoft.Json; using SurveyMonkey.Enums; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class Recipient : IPageableContainer { public long? Id { get; set; } public long? SurveyId { get; set; } internal string Href { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; } public MessageStatus? MailStatus { get; set; } public Dictionary<string, string> CustomFields { get; set; } public string SurveyLink { get; set; } public string RemoveLink { get; set; } public Dictionary<string, string> ExtraFields { get; set; } } }```
d2701097-6bc4-41d0-9231-b2bbf9b645af
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.IO; using DspAdpcm.Encode.Adpcm; using DspAdpcm.Encode.Adpcm.Formats; using DspAdpcm.Encode.Pcm; using DspAdpcm.Encode.Pcm.Formats; namespace DspAdpcm.Cli { public static class DspAdpcmCli { public static int Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: dspenc <wavin> <dspout>\n"); return 0; } IPcmStream wave; try { using (var file = new FileStream(args[0], FileMode.Open)) { wave = new Wave(file).AudioStream; } } catch (Exception ex) { Console.WriteLine(ex.Message); return -1; } Stopwatch watch = new Stopwatch(); watch.Start(); IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcm(wave); watch.Stop(); Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n"); Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}"); Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond."); var dsp = new Dsp(adpcm); using (var stream = File.Open(args[1], FileMode.Create)) foreach (var b in dsp.GetFile()) stream.WriteByte(b); return 0; } } } ``` Make brstm instead of dsp. Encode adpcm channels in parallel
```c# using System; using System.Diagnostics; using System.IO; using DspAdpcm.Encode.Adpcm; using DspAdpcm.Encode.Adpcm.Formats; using DspAdpcm.Encode.Pcm; using DspAdpcm.Encode.Pcm.Formats; namespace DspAdpcm.Cli { public static class DspAdpcmCli { public static int Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n"); return 0; } IPcmStream wave; try { using (var file = new FileStream(args[0], FileMode.Open)) { wave = new Wave(file).AudioStream; } } catch (Exception ex) { Console.WriteLine(ex.Message); return -1; } Stopwatch watch = new Stopwatch(); watch.Start(); IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcmParallel(wave); watch.Stop(); Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n"); Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}"); Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond."); var brstm = new Brstm(adpcm); using (var stream = File.Open(args[1], FileMode.Create)) foreach (var b in brstm.GetFile()) stream.WriteByte(b); return 0; } } } ```
28e77423-104f-4da7-b72c-447ab29f7cc4
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; namespace SkypeSharp { /// <summary> /// Class representing a Skype CHAT object /// </summary> public class Chat : SkypeObject { /// <summary> /// List of users in this chat /// </summary> public IEnumerable<User> Users { get { string[] usernames = GetProperty("MEMBERS").Split(' '); return usernames.Select(u => new User(Skype, u)); } } /// <summary> /// List of chatmembers, useful for changing roles /// Skype broke this so it probably doesn't work /// </summary> public IEnumerable<ChatMember> ChatMembers { get { string[] members = GetProperty("MEMBEROBJECTS").Split(' '); return members.Select(m => new ChatMember(Skype, m)); } } public Chat(Skype skype, string id) : base(skype, id, "CHAT") {} /// <summary> /// Send a message to this chat /// </summary> /// <param name="text">Text to send</param> public void Send(string text) { Skype.Send("CHATMESSAGE " + ID + " " + text); } } }``` Add raw message sending, requires xdotool
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SkypeSharp { /// <summary> /// Class representing a Skype CHAT object /// </summary> public class Chat : SkypeObject { /// <summary> /// List of users in this chat /// </summary> public IEnumerable<User> Users { get { string[] usernames = GetProperty("MEMBERS").Split(' '); return usernames.Select(u => new User(Skype, u)); } } /// <summary> /// List of chatmembers, useful for changing roles /// Skype broke this so it probably doesn't work /// </summary> public IEnumerable<ChatMember> ChatMembers { get { string[] members = GetProperty("MEMBEROBJECTS").Split(' '); return members.Select(m => new ChatMember(Skype, m)); } } public Chat(Skype skype, string id) : base(skype, id, "CHAT") {} /// <summary> /// Send a message to this chat /// </summary> /// <param name="text">Text to send</param> public void Send(string text) { Skype.Send("CHATMESSAGE " + ID + " " + text); } /// <summary> /// Uses xdotool to attempt to send skype a message /// </summary> /// <param name="text"></param> public void SendRaw(string text) { Skype.Send("OPEN CHAT " + ID); Process p = new Process(); p.StartInfo.FileName = "/usr/bin/xdotool"; p.StartInfo.Arguments = String.Format("search --name skype type \"{0}\"", text.Replace("\"", "\\\"")); p.Start(); p.WaitForExit(); p.StartInfo.Arguments = "search --name skype key ctrl+shift+Return"; p.Start(); p.WaitForExit(); } } }```
61d0b1fe-bd46-4255-89d2-856794dfb911
{ "language": "C#" }
```c# using System; namespace SeleniumExtension.SauceLabs { public class SauceDriverKeys { public static string SAUCELABS_USERNAME { get { var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME", EnvironmentVariableTarget.User); if(string.IsNullOrEmpty(userName)) throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME"); return userName; } } public static string SAUCELABS_ACCESSKEY { get { var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY", EnvironmentVariableTarget.User); if (string.IsNullOrEmpty(userName)) throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY"); return userName; } } } } ``` Change the target to get working on build server
```c# using System; namespace SeleniumExtension.SauceLabs { public class SauceDriverKeys { public static string SAUCELABS_USERNAME { get { var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME"); if(string.IsNullOrEmpty(userName)) throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME"); return userName; } } public static string SAUCELABS_ACCESSKEY { get { var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY"); if (string.IsNullOrEmpty(userName)) throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY"); return userName; } } } } ```
13f3c15b-ed5a-4196-9c76-2d6043d4a6fe
{ "language": "C#" }
```c# namespace Metrics.Integrations.Linters { using System; using System.IO; using System.Text; // TODO: Improve logging. public class LogManager : IDisposable { public StringBuilder LogWriter { get; } private bool saved = false; public LogManager() { LogWriter = new StringBuilder(); } public void Log(string format, params object[] args) { LogWriter.AppendLine(string.Format(format, args)); } public void Trace(string message, params object[] args) { Log("TRACE: " + message + " {0}", string.Join(" ", args)); } public void Error(string message, params object[] args) { Log("ERROR: " + message + " {0}", string.Join(" ", args)); System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args))); } public void Save(string fileName) { saved = true; File.WriteAllText(fileName, LogWriter.ToString()); } public void Dispose() { if (!saved) { System.Console.Write(LogWriter.ToString()); } } } }``` Write logs to console only in case of error
```c# namespace Metrics.Integrations.Linters { using System; using System.IO; using System.Text; // TODO: Improve logging. public class LogManager : IDisposable { public StringBuilder LogWriter { get; } private bool saved = false; private bool error = false; public LogManager() { LogWriter = new StringBuilder(); } public void Log(string format, params object[] args) { LogWriter.AppendLine(string.Format(format, args)); } public void Trace(string message, params object[] args) { Log("TRACE: " + message + " {0}", string.Join(" ", args)); } public void Error(string message, params object[] args) { error = true; Log("ERROR: " + message + " {0}", string.Join(" ", args)); System.Console.Error.WriteLine(string.Format(message + " {0}", string.Join(" ", args))); } public void Save(string fileName) { saved = true; File.WriteAllText(fileName, LogWriter.ToString()); } public void Dispose() { if (!saved && error) { System.Console.Write(LogWriter.ToString()); } } } }```
e62db394-8b57-4444-8b58-c15f98db2cda
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using KAGTools.Data; using Newtonsoft.Json; namespace KAGTools.Helpers { public static class ApiHelper { private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}"; private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers"; private static readonly HttpClient httpClient; static ApiHelper() { httpClient = new HttpClient(); } public static async Task<ApiPlayerResults> GetPlayer(string username) { return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username)); } public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters) { string filterJson = "?filters=" + JsonConvert.SerializeObject(filters); return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson); } private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class { try { string data = await httpClient.GetStringAsync(requestUri); return data != null ? JsonConvert.DeserializeObject<T>(data) : null; } catch (HttpRequestException e) { MessageBox.Show(e.Message, "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error); } return null; } } } ``` Include request URL in HTTP error message
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows; using KAGTools.Data; using Newtonsoft.Json; namespace KAGTools.Helpers { public static class ApiHelper { private const string UrlPlayer = "https://api.kag2d.com/v1/player/{0}"; private const string UrlServers = "https://api.kag2d.com/v1/game/thd/kag/servers"; private static readonly HttpClient httpClient; static ApiHelper() { httpClient = new HttpClient(); } public static async Task<ApiPlayerResults> GetPlayer(string username) { return await HttpGetApiResult<ApiPlayerResults>(string.Format(UrlPlayer, username)); } public static async Task<ApiServerResults> GetServers(params ApiFilter[] filters) { string filterJson = "?filters=" + JsonConvert.SerializeObject(filters); return await HttpGetApiResult<ApiServerResults>(UrlServers + filterJson); } private static async Task<T> HttpGetApiResult<T>(string requestUri) where T : class { try { string data = await httpClient.GetStringAsync(requestUri); return data != null ? JsonConvert.DeserializeObject<T>(data) : null; } catch (HttpRequestException e) { MessageBox.Show(string.Format("{0}{2}{2}Request URL: {1}", e.Message, requestUri, Environment.NewLine), "HTTP Request Error", MessageBoxButton.OK, MessageBoxImage.Error); } return null; } } } ```
46e6573b-2aa4-4e16-a89d-16270787db72
{ "language": "C#" }
```c# using System; using Gtk; namespace gtksharp_clock { class MainClass { public static void Main(string[] args) { Application.Init(); MainWindow win = new MainWindow(); win.Show(); Application.Run(); } } } ``` Add clock Face and Window classes. Draw a line. Setting FG color is TODO.
```c# using System; using Gtk; // http://www.mono-project.com/docs/gui/gtksharp/widgets/widget-colours/ namespace gtksharp_clock { class MainClass { public static void Main(string[] args) { Application.Init(); ClockWindow win = new ClockWindow (); win.Show(); Application.Run(); } } class ClockWindow : Window { public ClockWindow() : base("ClockWindow") { SetDefaultSize(250, 200); SetPosition(WindowPosition.Center); ClockFace cf = new ClockFace(); Gdk.Color black = new Gdk.Color(); Gdk.Color.Parse("black", ref black); Gdk.Color grey = new Gdk.Color(); Gdk.Color.Parse("grey", ref grey); this.ModifyBg(StateType.Normal, grey); cf.ModifyBg(StateType.Normal, grey); this.ModifyFg(StateType.Normal, black); cf.ModifyFg(StateType.Normal, black); this.DeleteEvent += DeleteWindow; Add(cf); ShowAll(); } static void DeleteWindow(object obj, DeleteEventArgs args) { Application.Quit(); } } class ClockFace : DrawingArea { public ClockFace() : base() { this.SetSizeRequest(600, 600); this.ExposeEvent += OnExposed; } public void OnExposed(object o, ExposeEventArgs args) { Gdk.Color black = new Gdk.Color(); Gdk.Color.Parse("black", ref black); this.ModifyFg(StateType.Normal, black); this.GdkWindow.DrawLine(this.Style.BaseGC(StateType.Normal), 0, 0, 400, 300); } } } ```
98277785-d3bd-4502-a7d2-fb0759cc4e88
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RabidWarren.Collections.Generic { public static class Enumerable { public static Multimap<TKey, TElement> ToMultimap<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { var map = new Multimap<TKey, TElement>(); foreach (var entry in source) { map.Add(keySelector(entry), elementSelector(entry)); } return map; } } } ``` Document and clean up the binding code
```c# // ----------------------------------------------------------------------- // <copyright file="Enumerable.cs" company="Ron Parker"> // Copyright 2014 Ron Parker // </copyright> // <summary> // Provides an extension method for converting IEnumerables to Multimaps. // </summary> // ----------------------------------------------------------------------- namespace RabidWarren.Collections.Generic { using System; using System.Collections.Generic; /// <summary> /// Contains extension methods for <see cref="System.Collections.Generic.IEnumerable{TSource}"/>. /// </summary> public static class Enumerable { /// <summary> /// Converts the source to an <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>. /// </summary> /// <returns>The <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.</returns> /// <param name="source">The source.</param> /// <param name="keySelector">The key selector.</param> /// <param name="valueSelector">The value selector.</param> /// <typeparam name="TSource">The source type.</typeparam> /// <typeparam name="TKey">The key type.</typeparam> /// <typeparam name="TValue">The the value type.</typeparam> public static Multimap<TKey, TValue> ToMultimap<TSource, TKey, TValue>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector) { var map = new Multimap<TKey, TValue>(); foreach (var entry in source) { map.Add(keySelector(entry), valueSelector(entry)); } return map; } } } ```
ab0de76a-a9c1-4114-8421-eae117404d02
{ "language": "C#" }
```c# <!DOCTYPE html> <html ng-app="VoteOn-Poll"> <head> <title>Vote On</title> <meta name="viewport" content="initial-scale=1"> @Styles.Render("~/Bundles/StyleLib/AngularMaterial") @Styles.Render("~/Bundles/StyleLib/FontAwesome") @Styles.Render("~/Bundles/VotingStyle") </head> <body> <div layout="column" flex layout-fill> <toolbar></toolbar> <div ng-view></div> </div> @Scripts.Render("~/Bundles/ScriptLib/JQuery"); @Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR"); @Scripts.Render("~/Bundles/ScriptLib/Angular") @Scripts.Render("~/Bundles/ScriptLib/AngularAnimate") @Scripts.Render("~/Bundles/ScriptLib/AngularAria") @Scripts.Render("~/Bundles/ScriptLib/AngularMaterial") @Scripts.Render("~/Bundles/ScriptLib/AngularMessages") @Scripts.Render("~/Bundles/ScriptLib/AngularRoute") @Scripts.Render("~/Bundles/ScriptLib/AngularCharts") @Scripts.Render("~/Bundles/ScriptLib/AngularSignalR") @Scripts.Render("~/Bundles/ScriptLib/ngStorage") @Scripts.Render("~/Bundles/ScriptLib/moment") @Scripts.Render("~/Bundles/Script") </body> </html>``` Remove semicolons from poll page
```c# <!DOCTYPE html> <html ng-app="VoteOn-Poll"> <head> <title>Vote On</title> <meta name="viewport" content="initial-scale=1"> @Styles.Render("~/Bundles/StyleLib/AngularMaterial") @Styles.Render("~/Bundles/StyleLib/FontAwesome") @Styles.Render("~/Bundles/VotingStyle") </head> <body> <div layout="column" flex layout-fill> <toolbar></toolbar> <div ng-view></div> </div> @Scripts.Render("~/Bundles/ScriptLib/JQuery") @Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR") @Scripts.Render("~/Bundles/ScriptLib/Angular") @Scripts.Render("~/Bundles/ScriptLib/AngularAnimate") @Scripts.Render("~/Bundles/ScriptLib/AngularAria") @Scripts.Render("~/Bundles/ScriptLib/AngularMaterial") @Scripts.Render("~/Bundles/ScriptLib/AngularMessages") @Scripts.Render("~/Bundles/ScriptLib/AngularRoute") @Scripts.Render("~/Bundles/ScriptLib/AngularCharts") @Scripts.Render("~/Bundles/ScriptLib/AngularSignalR") @Scripts.Render("~/Bundles/ScriptLib/ngStorage") @Scripts.Render("~/Bundles/ScriptLib/moment") @Scripts.Render("~/Bundles/Script") </body> </html>```
1da214a5-18c4-45c3-98b2-4d64d2580b73
{ "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.Linq; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModDifficultyAdjust : ModDifficultyAdjust { [SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))] public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable { Precision = 0.05f, MinValue = 0.25f, MaxValue = 4, ReadCurrentFromDifficulty = _ => 1, }; public override string SettingDescription { get { string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N1}"; return string.Join(", ", new[] { base.SettingDescription, scrollSpeed }.Where(s => !string.IsNullOrEmpty(s))); } } protected override void ApplySettings(BeatmapDifficulty difficulty) { base.ApplySettings(difficulty); if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value; } } } ``` Fix taiko difficulty adjust scroll speed being shown with too low precision
```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.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Taiko.Mods { public class TaikoModDifficultyAdjust : ModDifficultyAdjust { [SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))] public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable { Precision = 0.05f, MinValue = 0.25f, MaxValue = 4, ReadCurrentFromDifficulty = _ => 1, }; public override string SettingDescription { get { string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N2}"; return string.Join(", ", new[] { base.SettingDescription, scrollSpeed }.Where(s => !string.IsNullOrEmpty(s))); } } protected override void ApplySettings(BeatmapDifficulty difficulty) { base.ApplySettings(difficulty); if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value; } } } ```
aad0f7fb-1075-4680-b9eb-bad298ad0351
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Timing; using osu.Framework.Configuration; namespace osu.Game.Screens.Play.ReplaySettings { public class PlaybackSettings : ReplayGroup { protected override string Title => @"playback"; public IAdjustableClock AdjustableClock { set; get; } private readonly ReplaySliderBar<double> sliderbar; public PlaybackSettings() { Child = sliderbar = new ReplaySliderBar<double> { LabelText = "Playback speed", Bindable = new BindableDouble { Default = 1, MinValue = 0.5, MaxValue = 2 }, }; } protected override void LoadComplete() { base.LoadComplete(); if (AdjustableClock == null) return; var clockRate = AdjustableClock.Rate; sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier; } } } ``` Add startup value for the slider
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Timing; using osu.Framework.Configuration; namespace osu.Game.Screens.Play.ReplaySettings { public class PlaybackSettings : ReplayGroup { protected override string Title => @"playback"; public IAdjustableClock AdjustableClock { set; get; } private readonly ReplaySliderBar<double> sliderbar; public PlaybackSettings() { Child = sliderbar = new ReplaySliderBar<double> { LabelText = "Playback speed", Bindable = new BindableDouble(1) { Default = 1, MinValue = 0.5, MaxValue = 2 }, }; } protected override void LoadComplete() { base.LoadComplete(); if (AdjustableClock == null) return; var clockRate = AdjustableClock.Rate; sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier; } } } ```
1569a2d5-8d39-499b-b789-f2af6648b10a
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; using Stripe.Infrastructure; namespace Stripe { public class StripeStatusTransitions : StripeEntity { [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("canceled")] public DateTime? Canceled { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("fulfiled")] public DateTime? Fulfilled { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("paid")] public DateTime? Paid { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("returned")] public DateTime? Returned { get; set; } } } ``` Change name of the property for the status transition to match the API too
```c# using System; using Newtonsoft.Json; using Stripe.Infrastructure; namespace Stripe { public class StripeStatusTransitions : StripeEntity { [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("canceled")] public DateTime? Canceled { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("fulfiled")] public DateTime? Fulfiled { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("paid")] public DateTime? Paid { get; set; } [JsonConverter(typeof(StripeDateTimeConverter))] [JsonProperty("returned")] public DateTime? Returned { get; set; } } } ```
306f76e9-00c9-4132-bf10-0e990899723d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Reflection; namespace Acklann.Daterpillar.TextTransformation { public class ScriptBuilderFactory { public ScriptBuilderFactory() { LoadAssemblyTypes(); } public IScriptBuilder CreateInstance(string name) { try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()])); } catch (KeyNotFoundException) { return new NullScriptBuilder(); } } public IScriptBuilder CreateInstance(ConnectionType connectionType) { return CreateInstance(string.Concat(connectionType, _targetInterface)); } #region Private Members private string _targetInterface = nameof(IScriptBuilder).Substring(1); private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>(); private void LoadAssemblyTypes() { Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName)); foreach (var typeInfo in thisAssembly.DefinedTypes) if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo)) { _scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName); } } #endregion Private Members } }``` Add new createInstance overloads to scriptbuilderfactory.cs to support scriptbuildersettings args
```c# using System; using System.Collections.Generic; using System.Reflection; namespace Acklann.Daterpillar.TextTransformation { public class ScriptBuilderFactory { public ScriptBuilderFactory() { LoadAssemblyTypes(); } public IScriptBuilder CreateInstance(string name) { return CreateInstance(name, ScriptBuilderSettings.Default); } public IScriptBuilder CreateInstance(string name, ScriptBuilderSettings settings) { try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()]), settings); } catch (KeyNotFoundException) { return new NullScriptBuilder(); } } public IScriptBuilder CreateInstance(ConnectionType connectionType) { return CreateInstance(string.Concat(connectionType, _targetInterface), ScriptBuilderSettings.Default); } public IScriptBuilder CreateInstance(ConnectionType connectionType, ScriptBuilderSettings settings) { return CreateInstance(string.Concat(connectionType, _targetInterface), settings); } #region Private Members private string _targetInterface = nameof(IScriptBuilder).Substring(1); private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>(); private void LoadAssemblyTypes() { Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName)); foreach (var typeInfo in thisAssembly.DefinedTypes) if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo)) { _scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName); } } #endregion Private Members } }```
17e9ab95-4dc0-4d76-b035-a991b644ffad
{ "language": "C#" }
```c# using System.Threading.Tasks; using System.Web.Http; using CroquetAustralia.Domain.Features.TournamentEntry.Commands; using CroquetAustralia.Domain.Features.TournamentEntry.Events; using CroquetAustralia.Domain.Services.Queues; namespace CroquetAustralia.WebApi.Controllers { [RoutePrefix("tournament-entry")] public class TournamentEntryController : ApiController { private readonly IEventsQueue _eventsQueue; public TournamentEntryController(IEventsQueue eventsQueue) { _eventsQueue = eventsQueue; } [HttpPost] [Route("add-entry")] public async Task AddEntryAsync(SubmitEntry command) { var entrySubmitted = command.ToEntrySubmitted(); await _eventsQueue.AddMessageAsync(entrySubmitted); } [HttpPost] [Route("payment-received")] public async Task PaymentReceivedAsync(ReceivePayment command) { // todo: extension method command.MapTo<EntrySubmitted> var @event = new PaymentReceived(command.EntityId, command.PaymentMethod); await _eventsQueue.AddMessageAsync(@event); } } }``` Fix EOI emails are not sent
```c# using System; using System.Threading.Tasks; using System.Web.Http; using CroquetAustralia.Domain.Features.TournamentEntry; using CroquetAustralia.Domain.Features.TournamentEntry.Commands; using CroquetAustralia.Domain.Features.TournamentEntry.Events; using CroquetAustralia.Domain.Services.Queues; namespace CroquetAustralia.WebApi.Controllers { [RoutePrefix("tournament-entry")] public class TournamentEntryController : ApiController { private readonly IEventsQueue _eventsQueue; public TournamentEntryController(IEventsQueue eventsQueue) { _eventsQueue = eventsQueue; } [HttpPost] [Route("add-entry")] public async Task AddEntryAsync(SubmitEntry command) { // todo: allow javascript to send null if (command.PaymentMethod.HasValue && (int)command.PaymentMethod.Value == -1) { command.PaymentMethod = null; } var entrySubmitted = command.ToEntrySubmitted(); await _eventsQueue.AddMessageAsync(entrySubmitted); } [HttpPost] [Route("payment-received")] public async Task PaymentReceivedAsync(ReceivePayment command) { // todo: extension method command.MapTo<EntrySubmitted> var @event = new PaymentReceived(command.EntityId, command.PaymentMethod); await _eventsQueue.AddMessageAsync(@event); } } }```
e9d56482-2ec4-4d23-aea6-4cb18f61679b
{ "language": "C#" }
```c# using System.Xml.Serialization; namespace DevelopmentInProgress.DipState { public enum DipStateType { [XmlEnum("1")] Standard = 1, [XmlEnum("2")] Auto = 3 } }``` Add a root state type
```c# using System.Xml.Serialization; namespace DevelopmentInProgress.DipState { public enum DipStateType { [XmlEnum("1")] Standard = 1, [XmlEnum("2")] Auto = 2, [XmlEnum("3")] Root = 3 } }```
dff95961-2981-448a-ae81-ebe73f31f61c
{ "language": "C#" }
```c# namespace Sitecore.FakeDb.Serialization.Tests.Deserialize { using System.Linq; using Xunit; [Trait("Deserialize", "Deserializing a tree of items")] public class DeserializeTree : DeserializeTestBase { public DeserializeTree() { this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true) { ParentID = TemplateIDs.TemplateFolder }); } [Fact(DisplayName = "Deserializes templates in tree")] public void DeserializesTemplates() { Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate)); } [Fact(DisplayName = "Deserializes items in tree")] public void DeserializesItems() { var nonTemplateItemCount = this.Db.Database.GetItem(TemplateIDs.TemplateFolder) .Axes.GetDescendants() .Count(x => x.TemplateID != TemplateIDs.Template && x.TemplateID != TemplateIDs.TemplateSection && x.TemplateID != TemplateIDs.TemplateField); Assert.Equal(5, nonTemplateItemCount); } } }``` Fix broken tests getting items from the valid root
```c# namespace Sitecore.FakeDb.Serialization.Tests.Deserialize { using System.Linq; using Xunit; [Trait("Deserialize", "Deserializing a tree of items")] public class DeserializeTree : DeserializeTestBase { public DeserializeTree() { this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true) { ParentID = TemplateIDs.TemplateFolder }); } [Fact(DisplayName = "Deserializes templates in tree")] public void DeserializesTemplates() { Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate)); } [Fact(DisplayName = "Deserializes items in tree")] public void DeserializesItems() { var nonTemplateItemCount = this.Db.Database.GetItem(ItemIDs.TemplateRoot) .Axes.GetDescendants() .Count(x => x.TemplateID != TemplateIDs.Template && x.TemplateID != TemplateIDs.TemplateSection && x.TemplateID != TemplateIDs.TemplateField); Assert.Equal(5, nonTemplateItemCount); } } }```
d4ed9dd8-8e3f-4530-8755-e029618e3832
{ "language": "C#" }
```c# using PluginContracts; using System; using System.Collections.Generic; using Xunit; namespace PluginLoader.Tests { public class Plugins_Tests { [Fact] public void PluginsFoundFromLibsFolder() { // Arrange var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3"; // Act var plugins = Plugins<IPluginV1>.Load(path); // Assert Assert.NotEmpty(plugins); } [Fact] public void PluginsNotFoundFromCurrentFolder() { // Arrange var path = @"."; // Act var plugins = Plugins<IPluginV1>.Load(path); // Assert Assert.Empty(plugins); } } } ``` Change the plugin library load path
```c# using PluginContracts; using System; using System.Collections.Generic; using Xunit; namespace PluginLoader.Tests { public class Plugins_Tests { [Fact] public void PluginsFoundFromLibsFolder() { // Arrange var path = @"..\..\..\..\Libs"; // Act var plugins = Plugins<IPluginV1>.Load(path); // Assert Assert.NotEmpty(plugins); } [Fact] public void PluginsNotFoundFromCurrentFolder() { // Arrange var path = @"."; // Act var plugins = Plugins<IPluginV1>.Load(path); // Assert Assert.Empty(plugins); } } } ```
69ddda0c-53cb-4278-86c3-c2ae8d66f464
{ "language": "C#" }
```c# using System.Web; using System.Web.Mvc; namespace SimpleMvcSitemap { class BaseUrlProvider : IBaseUrlProvider { public string GetBaseUrl(HttpContextBase httpContext) { //http://stackoverflow.com/a/1288383/205859 HttpRequestBase request = httpContext.Request; return string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, UrlHelper.GenerateContentUrl("~", httpContext)); } } }``` Remove trailing slash from base URL
```c# using System.Web; using System.Web.Mvc; namespace SimpleMvcSitemap { class BaseUrlProvider : IBaseUrlProvider { public string GetBaseUrl(HttpContextBase httpContext) { //http://stackoverflow.com/a/1288383/205859 HttpRequestBase request = httpContext.Request; return string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, UrlHelper.GenerateContentUrl("~", httpContext)) .TrimEnd('/'); } } }```
45b37421-8aac-48f9-a20b-12573a4b0cfa
{ "language": "C#" }
```c# using System.Collections.Specialized; using System.Text; using Moq; using NUnit.Framework; namespace LastPass.Test { [TestFixture] class FetcherTest { [Test] public void Login() { var webClient = new Mock<IWebClient>(); webClient .Setup(x => x.UploadValues(It.Is<string>(s => s == "https://lastpass.com/login.php"), It.IsAny<NameValueCollection>())) .Returns(Encoding.UTF8.GetBytes("")) .Verifiable(); new Fetcher("username", "password").Login(webClient.Object); webClient.Verify(); } } } ``` Test Fetcher.Login POSTs with correct values
```c# using System.Collections.Specialized; using System.Linq; using System.Text; using Moq; using NUnit.Framework; namespace LastPass.Test { [TestFixture] class FetcherTest { [Test] public void Login() { const string url = "https://lastpass.com/login.php"; const string username = "username"; const string password = "password"; var expectedValues = new NameValueCollection { {"method", "mobile"}, {"web", "1"}, {"xml", "1"}, {"username", username}, {"hash", "e379d972c3eb59579abe3864d850b5f54911544adfa2daf9fb53c05d30cdc985"}, {"iterations", "1"} }; var webClient = new Mock<IWebClient>(); webClient .Setup(x => x.UploadValues(It.Is<string>(s => s == url), It.Is<NameValueCollection>(v => AreEqual(v, expectedValues)))) .Returns(Encoding.UTF8.GetBytes("")) .Verifiable(); new Fetcher(username, password).Login(webClient.Object); webClient.Verify(); } private static bool AreEqual(NameValueCollection a, NameValueCollection b) { return a.AllKeys.OrderBy(s => s).SequenceEqual(b.AllKeys.OrderBy(s => s)) && a.AllKeys.All(s => a[s] == b[s]); } } } ```
af9e0436-3577-42e8-acec-6b20dc201784
{ "language": "C#" }
```c# namespace simple { using System; using System.IO; using k8s; class PodList { static void Main(string[] args) { var k8sClientConfig = new KubernetesClientConfiguration(); IKubernetes client = new Kubernetes(k8sClientConfig); Console.WriteLine("Starting Request!"); var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default").Result; var list = listTask.Body; foreach (var item in list.Items) { Console.WriteLine(item.Metadata.Name); } if (list.Items.Count == 0) { Console.WriteLine("Empty!"); } } } } ``` Update example for new config file loading.
```c# namespace simple { using System; using System.IO; using k8s; class PodList { static void Main(string[] args) { var k8sClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); IKubernetes client = new Kubernetes(k8sClientConfig); Console.WriteLine("Starting Request!"); var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default").Result; var list = listTask.Body; foreach (var item in list.Items) { Console.WriteLine(item.Metadata.Name); } if (list.Items.Count == 0) { Console.WriteLine("Empty!"); } } } } ```
9d77099e-c2d8-41c0-a12c-1f4eca64216b
{ "language": "C#" }
```c# using System; using NUnit.Framework; using FluentAssertions; using SketchSolve; using System.Linq; namespace SketchSolve.Spec { [TestFixture()] public class Solver { [Test()] public void HorizontalConstraintShouldWork () { var parameters = new Parameter[]{ new Parameter(0), new Parameter(1), new Parameter(2), new Parameter(3) }; var points = new point[]{ new point(){x = parameters[0], y = parameters[1]}, new point(){x = parameters[2], y = parameters[3]}, }; var lines = new line[]{ new line(){p1 = points[0], p2 = points[1]} }; var cons = new constraint[] { new constraint(){ type =ConstraintEnum.horizontal, line1 = lines[0] } }; var r = SketchSolve.Solver.solve(parameters, cons, true); points [0].y.Value.Should ().Be (points[1].y.Value); points [0].x.Value.Should ().NotBe (points[1].x.Value); } } } ``` Use range check for floating point
```c# using System; using NUnit.Framework; using FluentAssertions; using SketchSolve; using System.Linq; namespace SketchSolve.Spec { [TestFixture()] public class Solver { [Test()] public void HorizontalConstraintShouldWork () { var parameters = new Parameter[]{ new Parameter(0), new Parameter(1), new Parameter(2), new Parameter(3) }; var points = new point[]{ new point(){x = parameters[0], y = parameters[1]}, new point(){x = parameters[2], y = parameters[3]}, }; var lines = new line[]{ new line(){p1 = points[0], p2 = points[1]} }; var cons = new constraint[] { new constraint(){ type =ConstraintEnum.horizontal, line1 = lines[0] } }; var r = SketchSolve.Solver.solve(parameters, cons, true); points [0].y.Value.Should ().BeInRange (points[1].y.Value-0.001, points[1].y.Value+0.001); points [0].x.Value.Should ().NotBe (points[1].x.Value); } } } ```
b8254aec-bff3-4dbd-acfa-e3f6d41f2755
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Diagnostics; using System.Linq; using System.Reflection; namespace osu.Framework.Development { public static class DebugUtils { public static bool IsDebugBuild => is_debug_build.Value; private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() => Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled)); } } ``` Add reference to source of debug lookup method
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Diagnostics; using System.Linq; using System.Reflection; namespace osu.Framework.Development { public static class DebugUtils { public static bool IsDebugBuild => is_debug_build.Value; private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() => // https://stackoverflow.com/a/2186634 Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled) ); } } ```
89030ac0-c7a4-47f4-b1a3-19bea44f62b7
{ "language": "C#" }
```c# using CommonMarkSharp.Blocks; using CommonMarkSharp.Inlines; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommonMarkSharp.InlineParsers { public class AnyParser : IParser<InlineString> { public AnyParser(string significantChars) { SignificantChars = string.IsNullOrEmpty(significantChars) ? new HashSet<char>(significantChars) : null; } public HashSet<char> SignificantChars { get; private set; } public string StartsWithChars { get { return null; } } public InlineString Parse(ParserContext context, Subject subject) { if (SignificantChars != null) { var chars = subject.TakeWhile(c => !SignificantChars.Contains(c)); if (chars.Any()) { return new InlineString(chars); } } return new InlineString(subject.Take()); } } } ``` Use string in stead of HashSet - much faster
```c# using CommonMarkSharp.Blocks; using CommonMarkSharp.Inlines; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CommonMarkSharp.InlineParsers { public class AnyParser : IParser<InlineString> { public AnyParser(string significantChars) { SignificantChars = significantChars; } public string SignificantChars { get; private set; } public string StartsWithChars { get { return null; } } public InlineString Parse(ParserContext context, Subject subject) { if (SignificantChars != null) { var chars = subject.TakeWhile(c => !SignificantChars.Contains(c)); if (chars.Any()) { return new InlineString(chars); } } return new InlineString(subject.Take()); } } } ```
9c5f475b-9176-487a-84e2-05dc9ef7badf
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Platform; using osu.Game.Database; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class MemorySettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader; [BackgroundDependencyLoader] private void load(GameHost host, RealmContextFactory realmFactory) { Children = new Drawable[] { new SettingsButton { Text = DebugSettingsStrings.ClearAllCaches, Action = host.Collect }, new SettingsButton { Text = DebugSettingsStrings.CompactRealm, Action = () => { // Blocking operations implicitly causes a Compact(). using (realmFactory.BlockAllOperations()) { } } }, }; } } } ``` Add settings buttons to allow temporarily blocking realm access
```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.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Platform; using osu.Game.Database; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class MemorySettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader; [BackgroundDependencyLoader] private void load(GameHost host, RealmContextFactory realmFactory) { SettingsButton blockAction; SettingsButton unblockAction; Children = new Drawable[] { new SettingsButton { Text = DebugSettingsStrings.ClearAllCaches, Action = host.Collect }, new SettingsButton { Text = DebugSettingsStrings.CompactRealm, Action = () => { // Blocking operations implicitly causes a Compact(). using (realmFactory.BlockAllOperations()) { } } }, blockAction = new SettingsButton { Text = "Block realm", }, unblockAction = new SettingsButton { Text = "Unblock realm", }, }; blockAction.Action = () => { var blocking = realmFactory.BlockAllOperations(); blockAction.Enabled.Value = false; // As a safety measure, unblock after 10 seconds. // This is to handle the case where a dev may block, but then something on the update thread // accesses realm and blocks for eternity. Task.Factory.StartNew(() => { Thread.Sleep(10000); unblock(); }); unblockAction.Action = unblock; void unblock() { blocking?.Dispose(); blocking = null; Scheduler.Add(() => { blockAction.Enabled.Value = true; unblockAction.Action = null; }); } }; } } } ```
82b6d900-6c95-478a-9392-fb83fa6adfef
{ "language": "C#" }
```c# using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } } } ``` Add ignore_case and expand properties to synonym filter
```c# using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } [JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)] public bool? IgnoreCase { get; set; } [JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)] public bool? Expand { get; set; } } } ```
fab993a6-ca2a-40ac-81a7-9b78c165c1f7
{ "language": "C#" }
```c# /* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData; public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } } ``` Fix missing object reference error.
```c# /* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData = new List<HexData>(); public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } } ```
56120e29-9f14-4645-a1eb-09ca9f9b054f
{ "language": "C#" }
```c# using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } } ``` Set IsBusy immediately, so there is no chance to run the command more than once.
```c# using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { IsBusy = true; try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } } ```
e31afad9-d0aa-46d8-b216-308bbe834d18
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is unbounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended var channel = Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }``` Add support for creating a bounded channel in helper
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable, int? maxBufferSize = null) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is bounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended and isn't shown here. var channel = maxBufferSize != null ? Channel.CreateBounded<T>(maxBufferSize.Value) : Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }```
edeaf522-beec-4ba7-97df-ab94c0cdae72
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, IReadOnlyList<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }``` Add scheduling of events to occur later on the timeline
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, Many<Event> events); void AppendLater(DateTime when, Many<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }```
94fc3e9b-b9d7-45fa-93be-0ea4956f9ec8
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.0.6")] [assembly: AssemblyFileVersion("1.7.0.6")]``` Fix assembly version for Shimmer
```c# using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.6")] [assembly: AssemblyFileVersion("1.7.6")] [assembly: AssemblyInformationalVersion("1.7.6")]```
ecebcade-cacf-4e44-869d-e84a8f176697
{ "language": "C#" }
```c# using System.Net; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : Controller { [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }``` Add base class to error controller so that it can find Base SupportUserBanner child action
```c# using System.Net; using System.Web.Mvc; using SFA.DAS.Authentication; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : BaseController { public ErrorController( IAuthenticationService owinWrapper, IMultiVariantTestingService multiVariantTestingService, ICookieStorageService<FlashMessageViewModel> flashMessage) : base(owinWrapper, multiVariantTestingService, flashMessage) { } [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }```
6aecc344-6647-45af-9dec-17e44493b9af
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }``` Enable JS in the browser so the user can authorize the app
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); // GitHub needs JS enabled to un-grey the authorization button _signInWebView.Settings.JavaScriptEnabled = true; var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }```
888b2f24-1467-4409-83d5-43a0addd3123
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } } ``` Add the attribute needed, provided
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public string needed; public string provided; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } } ```
a25a9735-6bf8-47fe-9edd-c14ab8fcc446
{ "language": "C#" }
```c# using System; using UnityEngine; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { static bool _useFacebook; static public string FaceBookRedirectAddress; static bool _useGooglePlay; public static string GooglePlayRedirectAddress; static bool _useKaKao; public static string KakaoRedirectAddress; public OAuth2Setting () { } } } ``` Update Setting Values for OAuth2 setting
```c# using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { private const string SettingAssetName = "CBOAuth2Setting"; private const string SettingsPath = "CloudBread/Resources"; private const string SettingsAssetExtension = ".asset"; // Facebook private bool _useFacebook = false; static public bool UseFacebook { get { return Instance._useFacebook; } set { Instance._useFacebook = value; } } private string _facebookRedirectAddress = ".auth/login/facebook"; static public string FacebookRedirectAddress { get { return Instance._facebookRedirectAddress; } set { Instance._facebookRedirectAddress = value; } } // GoogePlay public bool _useGooglePlay = false; static public bool UseGooglePlay { get { return instance._useGooglePlay; } set { Instance._useGooglePlay = value; } } public string _googleRedirectAddress = "aaaa"; static public string GoogleRedirectAddress { get { return instance._googleRedirectAddress; } set { Instance._googleRedirectAddress = value; } } // KaKao private bool _useKaKao = false; public bool UseKaKao { get { return Instance._useKaKao; } set { Instance._useKaKao = value; } } public static string KakaoRedirectAddress; private static OAuth2Setting instance = null; public static OAuth2Setting Instance { get { if (instance == null) { instance = Resources.Load(SettingAssetName) as OAuth2Setting; if (instance == null) { // If not found, autocreate the asset object. instance = ScriptableObject.CreateInstance<OAuth2Setting>(); #if UNITY_EDITOR string properPath = Path.Combine(Application.dataPath, SettingsPath); if (!Directory.Exists(properPath)) { Directory.CreateDirectory(properPath); } string fullPath = Path.Combine( Path.Combine("Assets", SettingsPath), SettingAssetName + SettingsAssetExtension); AssetDatabase.CreateAsset(instance, fullPath); #endif } } return instance; } } } } ```
3feb2819-bab9-4bd3-bf37-18aa2ca4f552
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } } ``` Fix invalid JSON caused by localized decimal mark
```c# using System; using System.Globalization; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString(CultureInfo.InvariantCulture)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } } ```
977396f7-a44a-4036-804c-86e8eae62931
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } public override string Type { get { return "sc:Collection"; } } } } ``` Add members property to collection
```c# using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } [JsonProperty(Order = 111, PropertyName = "members")] public IIIFPresentationBase[] Members { get; set; } public override string Type { get { return "sc:Collection"; } } } } ```
0647a170-97af-465e-914c-72915305184b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NutPackerLib { public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } } ``` Remove unnecessary using's, add comment
```c# using System; namespace NutPackerLib { /// <summary> /// Original name of something. /// </summary> public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } } ```
97f0ee47-61f2-43ab-a5e7-746a85c4e5b0
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.13.0")] [assembly: AssemblyFileVersion("0.13.0")] ``` Increase project version number to 0.14.0
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.14.0")] [assembly: AssemblyFileVersion("0.14.0")] ```
a6d3dbdf-72bc-4ebe-b9c0-63f9abb4c45e
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.15.0")] [assembly: AssemblyFileVersion("0.15.0")] ``` Increase project version to 0.16.0
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.16.0")] [assembly: AssemblyFileVersion("0.16.0")] ```
493c9167-ac5b-4fcd-9962-2851374efc18
{ "language": "C#" }
```c# using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "PaletteInsightAgent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }``` Add spaces into displayed Palette Insight Agent service name
```c# using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "Palette Insight Agent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }```
dc29b117-a3b2-4008-b588-45269e1eee1d
{ "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) { //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; } } }``` Fix for buildtypeid case mismatch
```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.ToLower().Contains(appName.ToLower()))) { 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; } } }```
9f023ce4-51e6-45af-84e3-3b2737ee63b1
{ "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.Reflection; using System.Resources; using System.Runtime.CompilerServices; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")]``` Add `AssemblyCompany`, `AssemblyCopyright` and `AssemblyProduct` attributes to the assembly.
```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.Reflection; using System.Resources; using System.Runtime.CompilerServices; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft ASP.NET Core")]```
d7b3bb41-553b-4cf2-9d45-173b63ab631b
{ "language": "C#" }
```c# using System; namespace ChamberLib { public static class MathHelper { public static int RoundToInt(this float x) { return (int)Math.Round(x); } public static float ToRadians(this float degrees) { return degrees * 0.01745329251994f; // pi / 180 } public static float ToDegrees( this float radians) { return radians * 57.2957795130823f; // 180 / pi } public static float Clamp(this float value, float min, float max) { return Math.Max(Math.Min(value, max), min); } } } ``` Replace Xna's Clamp method with our own.
```c# using System; namespace ChamberLib { public static class MathHelper { public static int RoundToInt(this float x) { return (int)Math.Round(x); } public static float ToRadians(this float degrees) { return degrees * 0.01745329251994f; // pi / 180 } public static float ToDegrees( this float radians) { return radians * 57.2957795130823f; // 180 / pi } public static float Clamp(this float value, float min, float max) { if (value > max) return max; if (value < min) return min; return value; } } } ```
293a1975-467c-48b0-87f0-049bbda9683b
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2009, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Package overrides to initialize the mod. package Zap { function displayHelp() { Parent::displayHelp(); } function parseArgs() { Parent::parseArgs(); } function onStart() { Parent::onStart(); echo("\n--------- Initializing MOD: Zap ---------"); exec("./server.cs"); } function onExit() { Parent::onExit(); } }; // package Zap activatePackage(Zap); ``` Fix Zap mod dedicated server.
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2009, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Package overrides to initialize the mod. package Zap { function displayHelp() { Parent::displayHelp(); } function parseArgs() { Parent::parseArgs(); } function onStart() { echo("\n--------- Initializing MOD: Zap ---------"); exec("./server.cs"); Parent::onStart(); } function onExit() { Parent::onExit(); } }; // package Zap activatePackage(Zap); ```
87ae38f5-4e63-43e6-9f02-3a778da96242
{ "language": "C#" }
```c# using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; namespace AppHarbor.Tests { public class AutoCommandDataAttribute : AutoDataAttribute { public AutoCommandDataAttribute() : base(new Fixture().Customize(new AutoMoqCustomization())) { } } } ``` Use DomainCustomization rather than AutoMoqCustomization directly
```c# using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; namespace AppHarbor.Tests { public class AutoCommandDataAttribute : AutoDataAttribute { public AutoCommandDataAttribute() : base(new Fixture().Customize(new DomainCustomization())) { } } } ```
f2d0448d-6994-49fc-ae3d-b35e06d1aad4
{ "language": "C#" }
```c# namespace Gu.Wpf.UiAutomation { using System.Windows.Automation; public class Thumb : UiElement { public Thumb(AutomationElement automationElement) : base(automationElement) { } public TransformPattern TransformPattern => this.AutomationElement.TransformPattern(); /// <summary> /// Moves the slider horizontally. /// </summary> /// <param name="distance">+ for right, - for left.</param> public void SlideHorizontally(int distance) { Mouse.DragHorizontally(MouseButton.Left, this.Bounds.Center(), distance); } /// <summary> /// Moves the slider vertically. /// </summary> /// <param name="distance">+ for down, - for up.</param> public void SlideVertically(int distance) { Mouse.DragVertically(MouseButton.Left, this.Bounds.Center(), distance); } } } ``` Fix SliderTest.SlideHorizontally on Win 10
```c# namespace Gu.Wpf.UiAutomation { using System.Windows; using System.Windows.Automation; public class Thumb : UiElement { private const int DragSpeed = 500; public Thumb(AutomationElement automationElement) : base(automationElement) { } public TransformPattern TransformPattern => this.AutomationElement.TransformPattern(); /// <summary> /// Moves the slider horizontally. /// </summary> /// <param name="distance">+ for right, - for left.</param> public void SlideHorizontally(int distance) { var cp = this.GetClickablePoint(); Mouse.Drag(MouseButton.Left, cp, cp + new Vector(distance, 0), DragSpeed); Wait.UntilInputIsProcessed(); } /// <summary> /// Moves the slider vertically. /// </summary> /// <param name="distance">+ for down, - for up.</param> public void SlideVertically(int distance) { var cp = this.GetClickablePoint(); Mouse.Drag(MouseButton.Left, cp, cp + new Vector(0, distance), DragSpeed); Wait.UntilInputIsProcessed(); } } } ```
d3f987fe-86d3-4a23-9ade-31dea7ab0990
{ "language": "C#" }
```c# using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.Settings; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Resources; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.Text; using JetBrains.UI.Icons; namespace JetBrains.ReSharper.Plugins.Yaml.Psi { [ProjectFileType(typeof(YamlProjectFileType))] public class YamlProjectFileLanguageService : ProjectFileLanguageService { private readonly YamlSupport myYamlSupport; public YamlProjectFileLanguageService(YamlSupport yamlSupport) : base(YamlProjectFileType.Instance) { myYamlSupport = yamlSupport; } public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null) { var languageService = YamlLanguage.Instance.LanguageService(); return languageService?.GetPrimaryLexerFactory(); } protected override PsiLanguageType PsiLanguageType { get { var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance; return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance; } } // TODO: Proper icon! public override IconId Icon => PsiCSharpThemedIcons.Csharp.Id; } }``` Use less confusing placeholder icon for YAML
```c# using JetBrains.Application.UI.Icons.Special.ThemedIcons; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.Settings; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.Text; using JetBrains.UI.Icons; namespace JetBrains.ReSharper.Plugins.Yaml.Psi { [ProjectFileType(typeof(YamlProjectFileType))] public class YamlProjectFileLanguageService : ProjectFileLanguageService { private readonly YamlSupport myYamlSupport; public YamlProjectFileLanguageService(YamlSupport yamlSupport) : base(YamlProjectFileType.Instance) { myYamlSupport = yamlSupport; } public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null) { var languageService = YamlLanguage.Instance.LanguageService(); return languageService?.GetPrimaryLexerFactory(); } protected override PsiLanguageType PsiLanguageType { get { var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance; return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance; } } // TODO: Proper icon! public override IconId Icon => SpecialThemedIcons.Placeholder.Id; } }```
4372c87b-c5e2-4a15-9b2e-7506f36a26ab
{ "language": "C#" }
```c# // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class DefinitionRequest { public static readonly RequestType<TextDocumentPosition, Location[], object, object> Type = RequestType<TextDocumentPosition, Location[], object, object>.Create("textDocument/definition"); } } ``` Add registration options for definition request
```c# // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class DefinitionRequest { public static readonly RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions> Type = RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions>.Create("textDocument/definition"); } } ```
70190975-92c9-45b6-be28-076cc0f87ab1
{ "language": "C#" }
```c# namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedPackage_CuratedFeedAndPackageRegistration"); } } } ``` Fix having the wrong Index name in migration CuratedFeedPackageUniqueness.Down()
```c# namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedFeed_PackageRegistration"); } } } ```
f1172516-0c83-4d1e-afc7-2c5102b07eb2
{ "language": "C#" }
```c# using System; using System.Linq; using System.Reflection; using Mongo.Migration.Extensions; using Mongo.Migration.Migrations.Adapters; namespace Mongo.Migration.Migrations.Locators { internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType> where TMigrationType: class, IMigration { private readonly IContainerProvider _containerProvider; public TypeMigrationDependencyLocator(IContainerProvider containerProvider) { _containerProvider = containerProvider; } public override void Locate() { var migrationTypes = (from assembly in Assemblies from type in assembly.GetTypes() where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract select type).Distinct(); Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary(); } private TMigrationType GetMigrationInstance(Type type) { ConstructorInfo constructor = type.GetConstructors()[0]; if(constructor != null) { object[] args = constructor .GetParameters() .Select(o => o.ParameterType) .Select(o => _containerProvider.GetInstance(o)) .ToArray(); return Activator.CreateInstance(type, args) as TMigrationType; } return Activator.CreateInstance(type) as TMigrationType; } } }``` Add an implementation IEqualityComparer<Type> to ensure the .Distinct call in the Locate() method works as expected.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Mongo.Migration.Extensions; using Mongo.Migration.Migrations.Adapters; namespace Mongo.Migration.Migrations.Locators { internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType> where TMigrationType: class, IMigration { private class TypeComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) { return x.AssemblyQualifiedName == y.AssemblyQualifiedName; } public int GetHashCode(Type obj) { return obj.AssemblyQualifiedName.GetHashCode(); } } private readonly IContainerProvider _containerProvider; public TypeMigrationDependencyLocator(IContainerProvider containerProvider) { _containerProvider = containerProvider; } public override void Locate() { var migrationTypes = (from assembly in Assemblies from type in assembly.GetTypes() where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract select type).Distinct(new TypeComparer()); Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary(); } private TMigrationType GetMigrationInstance(Type type) { ConstructorInfo constructor = type.GetConstructors()[0]; if(constructor != null) { object[] args = constructor .GetParameters() .Select(o => o.ParameterType) .Select(o => _containerProvider.GetInstance(o)) .ToArray(); return Activator.CreateInstance(type, args) as TMigrationType; } return Activator.CreateInstance(type) as TMigrationType; } } }```