doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
6729bde3-ad01-40a3-8187-88ee449c1b32
{ "language": "C#" }
```c# namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity { [JsonProperty("succeeded")] public bool Succeeded { get; set; } [JsonProperty("version")] public string Version { get; set; } } } ``` Add support for Authenticated on 3DS Charges
```c# namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity { /// <summary> /// Whether or not authentication was performed. 3D Secure will succeed without /// authentication when the card is not enrolled. /// </summary> [JsonProperty("authenticated")] public bool Authenticated { get; set; } /// <summary> /// Whether or not 3D Secure succeeded. /// </summary> [JsonProperty("succeeded")] public bool Succeeded { get; set; } /// <summary> /// The version of 3D Secure that was used for this payment. /// </summary> [JsonProperty("version")] public string Version { get; set; } } } ```
7c67380d-c77b-485d-88b0-5762ef5704d4
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2013-2015 Sergey Odinokov, Adam Barclay")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] // Don't edit manually! Use `build.bat version` command instead! [assembly: AssemblyVersion("0.1.0")] ``` Update assembly copyright notice to 2017
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Hangfire")] [assembly: AssemblyCopyright("Copyright © 2013-2017 Sergey Odinokov, Adam Barclay")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] // Don't edit manually! Use `build.bat version` command instead! [assembly: AssemblyVersion("0.1.0")] ```
b0ca1b81-0f95-4569-b87e-eab87b999f8c
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using Matcha.Game.Tweens; public class InteractiveEntity : MonoBehaviour { public enum EntityType { none, prize, weapon }; public EntityType entityType; [HideInInspector] public bool alreadyCollided = false; public bool disableIfOffScreen = true; public int worth; void OnBecameInvisible() { if(disableIfOffScreen) gameObject.SetActive(false); } void OnBecameVisible() { if(disableIfOffScreen) gameObject.SetActive(true); } public void React() { alreadyCollided = true; switch (entityType) { case EntityType.none: break; case EntityType.prize: MTween.PickupPrize(gameObject); break; case EntityType.weapon: MTween.PickupWeapon(gameObject); break; } } public void SelfDestruct(int inSeconds) { Destroy(gameObject, inSeconds); } } ``` Add automatic placement for Prizes.
```c# using UnityEngine; using System; using System.Collections; using Matcha.Game.Tweens; public class InteractiveEntity : MonoBehaviour { public enum EntityType { none, prize, weapon }; public EntityType entityType; [HideInInspector] public bool alreadyCollided = false; public bool disableIfOffScreen = true; public int worth; void Start() { switch (entityType) { case EntityType.none: break; case EntityType.prize: // still buggy // needs to be more succint transform.position = new Vector3(transform.position.x, (float)(Math.Ceiling(transform.position.y) - .623f), transform.position.z); break; case EntityType.weapon: break; } } void OnBecameInvisible() { if(disableIfOffScreen) gameObject.SetActive(false); } void OnBecameVisible() { if(disableIfOffScreen) gameObject.SetActive(true); } public void React() { alreadyCollided = true; switch (entityType) { case EntityType.none: break; case EntityType.prize: MTween.PickupPrize(gameObject); break; case EntityType.weapon: MTween.PickupWeapon(gameObject); break; } } public void SelfDestruct(int inSeconds) { Destroy(gameObject, inSeconds); } } ```
eb12a5c9-f12f-410a-9cf0-d369860ff816
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; namespace osu.Game.Beatmaps { public class BeatmapStatistic { [Obsolete("Use CreateIcon instead")] // can be removed 20210203 public IconUsage Icon = FontAwesome.Regular.QuestionCircle; /// <summary> /// A function to create the icon for display purposes. /// </summary> public Func<Drawable> CreateIcon; public string Content; public string Name; public BeatmapStatistic() { #pragma warning disable 618 CreateIcon = () => new SpriteIcon { Icon = Icon }; #pragma warning restore 618 } } } ``` Add scale to allow legacy icons to display correctly sized
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Game.Beatmaps { public class BeatmapStatistic { [Obsolete("Use CreateIcon instead")] // can be removed 20210203 public IconUsage Icon = FontAwesome.Regular.QuestionCircle; /// <summary> /// A function to create the icon for display purposes. /// </summary> public Func<Drawable> CreateIcon; public string Content; public string Name; public BeatmapStatistic() { #pragma warning disable 618 CreateIcon = () => new SpriteIcon { Icon = Icon, Scale = new Vector2(0.6f) }; #pragma warning restore 618 } } } ```
2d531056-c541-4575-a2ab-c5cf2e1e852c
{ "language": "C#" }
```c# using System; using Client.Common; using Client.Game; using UnityEngine; namespace Client.Controllers { // Create a ball. Once there is a Goal, create a new // ball at the given time frame. public class BallController : MonoBehaviour { [SerializeField] [Tooltip("The soccer ball prefab")] private GameObject prefabBall; private GameObject currentBall; // --- Messages --- private void Start() { if(prefabBall == null) { throw new Exception("Prefab should not be null!"); } CreateBall(); var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>(); var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>(); p1Goal.TriggerEnter += OnGoal; p2Goal.TriggerEnter += OnGoal; } // --- Functions --- // Create a ball. Removes the old one if there is one. private void CreateBall() { if(currentBall != null) { Destroy(currentBall); } currentBall = Instantiate(prefabBall); currentBall.name = Ball.Name; } private void OnGoal(Collider _) { Invoke("CreateBall", 5); } } }``` Make sure a ball can't happen while a goal has already happened!
```c# using System; using Client.Common; using Client.Game; using UnityEngine; namespace Client.Controllers { // Create a ball. Once there is a Goal, create a new // ball at the given time frame. public class BallController : MonoBehaviour { [SerializeField] [Tooltip("The soccer ball prefab")] private GameObject prefabBall; private GameObject currentBall; // property to ensure we don't try and create a ball while // creating a ball private bool isGoal; // --- Messages --- private void Start() { if(prefabBall == null) { throw new Exception("Prefab should not be null!"); } isGoal = false; var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>(); var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>(); p1Goal.TriggerEnter += OnGoal; p2Goal.TriggerEnter += OnGoal; CreateBall(); } // --- Functions --- // Create a ball. Removes the old one if there is one. private void OnGoal(Collider _) { if(!isGoal) { isGoal = true; Invoke("CreateBall", 5); } } private void CreateBall() { if(currentBall != null) { Destroy(currentBall); } currentBall = Instantiate(prefabBall); currentBall.name = Ball.Name; isGoal = false; } } }```
fbc13dbf-4083-4ec9-aeb3-80338f27ff9d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExoMail.Smtp.Extensions { public static class StringExtensions { public static Stream ToStream(this string str) { return new MemoryStream(Encoding.ASCII.GetBytes(str)); } public static string WordWrap(this string str, int cols) { return WordWrap(str, cols, string.Empty); } public static string WordWrap(this string str, int cols, string indent) { string[] words = str.Split(' '); var sb = new StringBuilder(); int colIndex = 0; string space = string.Empty; for (int i = 0; i < words.Count(); i++) { space = i == words.Count() ? string.Empty : " "; colIndex += words[i].Length + space.Length; if (colIndex <= cols) { sb.Append(string.Format("{0}{1}", words[i], space)); } else { colIndex = 0; sb.Append(string.Format("\r\n{0}{1}{2}", indent, words[i], space)); } } return sb.ToString(); } } } ``` Fix issues with wordwrap string extension method
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExoMail.Smtp.Extensions { public static class StringExtensions { public static Stream ToStream(this string str) { return new MemoryStream(Encoding.ASCII.GetBytes(str)); } public static string WordWrap(this string str, int cols) { return WordWrap(str, cols, string.Empty); } public static string WordWrap(this string str, int cols, string indent) { string[] words = str.Split(' '); var sb = new StringBuilder(); int colIndex = 0; string space = string.Empty; string newLine = "\r\n"; for (int i = 0; i < words.Count(); i++) { space = i == (words.Count() - 1) ? newLine : " "; colIndex += words[i].Length + space.Length + newLine.Length; if (colIndex <= cols) { sb.AppendFormat("{0}{1}", words[i], space); } else { colIndex = 0; sb.AppendFormat("\r\n{0}{1}{2}", indent, words[i], space); } if (words[i].Contains(';')) { colIndex = 0; sb.Append(newLine); sb.Append(indent); } } return sb.ToString(); } } } ```
8fd62c8c-9b27-40e9-b67c-c98f16bb9ab1
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tralus.Shell.WorkflowService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tralus.Shell.WorkflowService")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("1.0.*")] ``` Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tralus.Shell.WorkflowService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tralus.Shell.WorkflowService")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
f58a886d-bc2a-4c20-a2ed-912f288f256d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using TravelAgency.Data; using TravelAgency.Data.Migrations; using TravelAgency.MongoDbExtractor; namespace TravelAgency.Client { public class Startup { public static void Main() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<TravelAgencyDbContext, Configuration>()); var travelAgencyDbContext = new TravelAgencyDbContext(); var mongoExtractor = new MongoDbDataExtractor(); var dataImporter = new TravelAgenciesDataImporter(travelAgencyDbContext, mongoExtractor); dataImporter.ImportData(); try { travelAgencyDbContext.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { throw; } //// Just for test - to see if something has been written to the Database // Console.WriteLine(db.Destinations.Count()); } } } ``` Add using for db context
```c# using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using TravelAgency.Data; using TravelAgency.Data.Migrations; using TravelAgency.MongoDbExtractor; namespace TravelAgency.Client { public class Startup { public static void Main() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<TravelAgencyDbContext, Configuration>()); using (var travelAgencyDbContext = new TravelAgencyDbContext()) { var mongoExtractor = new MongoDbDataExtractor(); var dataImporter = new TravelAgenciesDataImporter(travelAgencyDbContext, mongoExtractor); dataImporter.ImportData(); travelAgencyDbContext.SaveChanges(); } //// Just for test - to see if something has been written to the Database // Console.WriteLine(db.Destinations.Count()); } } } ```
d6be67db-4814-4862-84dd-b0e9345f6662
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.IO; using System.Text; using JetBrains.Annotations; namespace Itg.ZabbixAgent.Core { internal class ZabbixProtocol { private static readonly byte[] headerBytes = Encoding.ASCII.GetBytes(ZabbixConstants.HeaderString); private static readonly byte[] zero = new byte[ 0 ]; /// <summary> /// Write a string to the stream prefixed with it's size and the Zabbix protocol header. /// </summary> public static void WriteWithHeader([NotNull] Stream stream, [NotNull] string valueString, [CanBeNull] string errorString) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse Debug.Assert(stream != null); // ReSharper disable once ConditionIsAlwaysTrueOrFalse Debug.Assert(valueString != null); // <HEADER> stream.Write(headerBytes, 0, headerBytes.Length); // <DATALEN> var valueStringBytes = Encoding.UTF8.GetBytes(valueString); var sizeBytes = BitConverter.GetBytes((long)valueStringBytes.Length); stream.Write(sizeBytes, 0, sizeBytes.Length); // <DATA> stream.Write(valueStringBytes, 0, valueStringBytes.Length); if (errorString != null) { // \0 stream.Write(zero, 0, 1); // <ERROR> var errorStringBytes = Encoding.UTF8.GetBytes(errorString); stream.Write(errorStringBytes, 0, errorStringBytes.Length); } } } } ``` Fix a bug in zabbix protocol with errors
```c# using System; using System.Diagnostics; using System.IO; using System.Text; using JetBrains.Annotations; namespace Itg.ZabbixAgent.Core { internal class ZabbixProtocol { private static readonly byte[] headerBytes = Encoding.ASCII.GetBytes(ZabbixConstants.HeaderString); private static readonly byte[] zero = { 0 }; /// <summary> /// Write a string to the stream prefixed with it's size and the Zabbix protocol header. /// </summary> public static void WriteWithHeader([NotNull] Stream stream, [NotNull] string valueString, [CanBeNull] string errorString) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse Debug.Assert(stream != null); // ReSharper disable once ConditionIsAlwaysTrueOrFalse Debug.Assert(valueString != null); // <HEADER> stream.Write(headerBytes, 0, headerBytes.Length); // <DATALEN> var valueStringBytes = Encoding.UTF8.GetBytes(valueString); var sizeBytes = BitConverter.GetBytes((long)valueStringBytes.Length); stream.Write(sizeBytes, 0, sizeBytes.Length); // <DATA> stream.Write(valueStringBytes, 0, valueStringBytes.Length); if (errorString != null) { // \0 stream.Write(zero, 0, 1); // <ERROR> var errorStringBytes = Encoding.UTF8.GetBytes(errorString); stream.Write(errorStringBytes, 0, errorStringBytes.Length); } } } } ```
6cffd277-5129-4c50-8abb-a768848ff0c5
{ "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.Game.Tournament.Components; namespace osu.Game.Tournament.Screens.Showcase { public class ShowcaseScreen : BeatmapInfoScreen { [BackgroundDependencyLoader] private void load() { AddRangeInternal(new Drawable[] { new TournamentLogo(), new TourneyVideo("showcase") { Loop = true, RelativeSizeAxes = Axes.Both, } }); } } } ``` Add Chroma keying to the background of the showcase video.
```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.Game.Tournament.Components; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Showcase { public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo { private Box chroma; [BackgroundDependencyLoader] private void load() { AddRangeInternal(new Drawable[] { new TournamentLogo(), new TourneyVideo("showcase") { Loop = true, RelativeSizeAxes = Axes.Both, }, chroma = new Box { // chroma key area for stable gameplay Name = "chroma", Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Height = 695, Width = 1366, Colour = new Color4(0, 255, 0, 255), } }); } } } ```
bcce1c0c-3f4f-46ff-8db0-1b07b0e4f553
{ "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.Game.Beatmaps; using osu.Game.Rulesets; namespace osu.Game.Scoring.Legacy { /// <summary> /// A <see cref="LegacyScoreDecoder"/> which retrieves the applicable <see cref="Beatmap"/> and <see cref="Ruleset"/> /// for the score from the database. /// </summary> public class DatabasedLegacyScoreDecoder : LegacyScoreDecoder { private readonly RulesetStore rulesets; private readonly BeatmapManager beatmaps; public DatabasedLegacyScoreDecoder(RulesetStore rulesets, BeatmapManager beatmaps) { this.rulesets = rulesets; this.beatmaps = beatmaps; } protected override Ruleset GetRuleset(int rulesetId) => rulesets.GetRuleset(rulesetId).CreateInstance(); protected override WorkingBeatmap GetBeatmap(string md5Hash) => beatmaps.GetWorkingBeatmap(beatmaps.QueryBeatmap(b => !b.BeatmapSet.DeletePending && b.MD5Hash == md5Hash)); } } ``` Update usages to consume `IRulesetStore`
```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.Game.Beatmaps; using osu.Game.Rulesets; namespace osu.Game.Scoring.Legacy { /// <summary> /// A <see cref="LegacyScoreDecoder"/> which retrieves the applicable <see cref="Beatmap"/> and <see cref="Ruleset"/> /// for the score from the database. /// </summary> public class DatabasedLegacyScoreDecoder : LegacyScoreDecoder { private readonly IRulesetStore rulesets; private readonly BeatmapManager beatmaps; public DatabasedLegacyScoreDecoder(IRulesetStore rulesets, BeatmapManager beatmaps) { this.rulesets = rulesets; this.beatmaps = beatmaps; } protected override Ruleset GetRuleset(int rulesetId) => rulesets.GetRuleset(rulesetId).CreateInstance(); protected override WorkingBeatmap GetBeatmap(string md5Hash) => beatmaps.GetWorkingBeatmap(beatmaps.QueryBeatmap(b => !b.BeatmapSet.DeletePending && b.MD5Hash == md5Hash)); } } ```
664c8fcb-2542-447c-b731-670acab6d127
{ "language": "C#" }
```c# using System; using System.Web; namespace RollbarSharp { public class RollbarHttpModule : IHttpModule { public void Init(HttpApplication context) { context.Error += SendError; } public void Dispose() { } private void SendError(object sender, EventArgs e) { var application = (HttpApplication)sender; new RollbarClient().SendException(application.Server.GetLastError().GetBaseException()); } } }``` Update spacing for project consistency
```c# using System; using System.Web; namespace RollbarSharp { public class RollbarHttpModule : IHttpModule { public void Init(HttpApplication context) { context.Error += SendError; } public void Dispose() { } private static void SendError(object sender, EventArgs e) { var application = (HttpApplication) sender; new RollbarClient().SendException(application.Server.GetLastError().GetBaseException()); } } }```
33a501da-d164-4171-bfc3-536f81871e87
{ "language": "C#" }
```c# namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Forms; using ClojSharp.Core.Language; using ClojSharp.Core.SpecialForms; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] [DeploymentItem("Src", "Src")] public class CoreTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); this.machine.EvaluateFile("Src\\core.clj"); } [TestMethod] public void MachineHasMacros() { this.IsMacro("defmacro"); this.IsMacro("defn"); } private void IsMacro(string name) { var result = this.machine.RootContext.GetValue(name); Assert.IsNotNull(result, name); Assert.IsInstanceOfType(result, typeof(IForm), name); Assert.IsInstanceOfType(result, typeof(Macro), name); } } } ``` Define and evaluate function, using defn defined in core.clj
```c# namespace ClojSharp.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClojSharp.Core.Compiler; using ClojSharp.Core.Forms; using ClojSharp.Core.Language; using ClojSharp.Core.SpecialForms; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] [DeploymentItem("Src", "Src")] public class CoreTests { private Machine machine; [TestInitialize] public void Setup() { this.machine = new Machine(); this.machine.EvaluateFile("Src\\core.clj"); } [TestMethod] public void MachineHasMacros() { this.IsMacro("defmacro"); this.IsMacro("defn"); } [TestMethod] public void DefineAndEvaluateFunction() { this.Evaluate("(defn incr [x] (+ x 1))"); Assert.AreEqual(2, this.Evaluate("(incr 1)")); } private void IsMacro(string name) { var result = this.machine.RootContext.GetValue(name); Assert.IsNotNull(result, name); Assert.IsInstanceOfType(result, typeof(IForm), name); Assert.IsInstanceOfType(result, typeof(Macro), name); } private object Evaluate(string text) { return this.Evaluate(text, this.machine.RootContext); } private object Evaluate(string text, IContext context) { Parser parser = new Parser(text); var expr = parser.ParseExpression(); Assert.IsNull(parser.ParseExpression()); return Machine.Evaluate(expr, context); } } } ```
428510a2-d17f-48e1-8010-cece6f029ea8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Web; using System.Web.UI; using System.Web.WebPages; using DotNetNuke.Web.Client; using DotNetNuke.Web.Client.ClientResourceManagement; namespace Satrabel.OpenContent.Components { public abstract class OpenContentWebPage<TModel> : DotNetNuke.Web.Razor.DotNetNukeWebPage<TModel> { int JSOrder = (int)FileOrder.Js.DefaultPriority; int CSSOrder = (int)FileOrder.Css.ModuleCss; public void RegisterStyleSheet(string filePath) { if (!filePath.StartsWith("http") && !filePath.StartsWith("/")) filePath = this.VirtualPath + filePath; ClientResourceManager.RegisterStyleSheet((Page)HttpContext.Current.CurrentHandler, filePath, CSSOrder); CSSOrder++; } public void RegisterScript(string filePath) { if (!filePath.StartsWith("http") && !filePath.StartsWith("/")) filePath = this.VirtualPath + filePath; ClientResourceManager.RegisterScript((Page)HttpContext.Current.CurrentHandler, filePath, JSOrder); JSOrder++; } } }``` Fix issue where RegisterScript did not load file in a IIS Virtual App environment
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Web; using System.Web.UI; using System.Web.WebPages; using DotNetNuke.Web.Client; using DotNetNuke.Web.Client.ClientResourceManagement; namespace Satrabel.OpenContent.Components { public abstract class OpenContentWebPage<TModel> : DotNetNuke.Web.Razor.DotNetNukeWebPage<TModel> { int JSOrder = (int)FileOrder.Js.DefaultPriority; int CSSOrder = (int)FileOrder.Css.ModuleCss; public void RegisterStyleSheet(string filePath) { if (!filePath.StartsWith("http") && !filePath.Contains("/")) { filePath = VirtualPath + filePath; } if (!filePath.StartsWith("http")) { var file = new FileUri(filePath); filePath = file.UrlFilePath; } ClientResourceManager.RegisterStyleSheet((Page)HttpContext.Current.CurrentHandler, filePath, CSSOrder); CSSOrder++; } public void RegisterScript(string filePath) { if (!filePath.StartsWith("http") && !filePath.Contains("/")) { filePath = VirtualPath + filePath; } if (!filePath.StartsWith("http")) { var file = new FileUri(filePath); filePath = file.UrlFilePath; } ClientResourceManager.RegisterScript((Page)HttpContext.Current.CurrentHandler, filePath, JSOrder); JSOrder++; } } }```
1efe2eff-e0b6-40f8-8aef-703064f9375c
{ "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.Collections.Generic; using Microsoft.AspNet.Http.Authentication; namespace Microsoft.AspNet.IISPlatformHandler { public class IISPlatformHandlerOptions { /// <summary> /// If true the authentication middleware alter the request user coming in and respond to generic challenges. /// If false the authentication middleware will only provide identity and respond to challenges when explicitly indicated /// by the AuthenticationScheme. /// </summary> public bool AutomaticAuthentication { get; set; } = true; /// <summary> /// If true authentication middleware will try to authenticate using platform handler windows authentication /// If false authentication middleware won't be added /// </summary> public bool FlowWindowsAuthentication { get; set; } = true; /// <summary> /// Additional information about the authentication type which is made available to the application. /// </summary> public IList<AuthenticationDescription> AuthenticationDescriptions { get; } = new List<AuthenticationDescription>() { new AuthenticationDescription() { AuthenticationScheme = IISPlatformHandlerDefaults.Negotiate, DisplayName = IISPlatformHandlerDefaults.Negotiate }, new AuthenticationDescription() { AuthenticationScheme = IISPlatformHandlerDefaults.Ntlm, DisplayName = IISPlatformHandlerDefaults.Ntlm } }; } }``` Remove display name for Negotiate and Ntlm
```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.Collections.Generic; using Microsoft.AspNet.Http.Authentication; namespace Microsoft.AspNet.IISPlatformHandler { public class IISPlatformHandlerOptions { /// <summary> /// If true the authentication middleware alter the request user coming in and respond to generic challenges. /// If false the authentication middleware will only provide identity and respond to challenges when explicitly indicated /// by the AuthenticationScheme. /// </summary> public bool AutomaticAuthentication { get; set; } = true; /// <summary> /// If true authentication middleware will try to authenticate using platform handler windows authentication /// If false authentication middleware won't be added /// </summary> public bool FlowWindowsAuthentication { get; set; } = true; /// <summary> /// Additional information about the authentication type which is made available to the application. /// </summary> public IList<AuthenticationDescription> AuthenticationDescriptions { get; } = new List<AuthenticationDescription>() { new AuthenticationDescription() { AuthenticationScheme = IISPlatformHandlerDefaults.Negotiate }, new AuthenticationDescription() { AuthenticationScheme = IISPlatformHandlerDefaults.Ntlm } }; } }```
525d4607-d0bd-42eb-a816-44277f5eda91
{ "language": "C#" }
```c# namespace Curse.NET.Model { public class CreateInviteResponse { public string InviteCode { get; set; } public int CreatorID { get; set; } public string CreatorName { get; set; } public string GroupID { get; set; } public Group Group { get; set; } public string ChannelID { get; set; } public Channel Channel { get; set; } public long DateCreated { get; set; } public long DateExpires { get; set; } public int MaxUses { get; set; } public int TimesUsed { get; set; } public bool IsRedeemable { get; set; } public string InviteUrl { get; set; } public string AdminDescription { get; set; } } }``` Add JSON Converter to date fields
```c# using System; using Newtonsoft.Json; namespace Curse.NET.Model { public class CreateInviteResponse { public string InviteCode { get; set; } public int CreatorID { get; set; } public string CreatorName { get; set; } public string GroupID { get; set; } public Group Group { get; set; } public string ChannelID { get; set; } public Channel Channel { get; set; } [JsonConverter(typeof(MillisecondEpochConverter))] public DateTime DateCreated { get; set; } [JsonConverter(typeof(MillisecondEpochConverter))] public DateTime DateExpires { get; set; } public int MaxUses { get; set; } public int TimesUsed { get; set; } public bool IsRedeemable { get; set; } public string InviteUrl { get; set; } public string AdminDescription { get; set; } } }```
dab8c18d-c9c3-4bc4-b46e-f87bdfc54266
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } } } ``` Create server side API for single multiple answer question
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ```
7b1cfbff-09b3-40a7-845a-e0c4aaa8be87
{ "language": "C#" }
```c# namespace StraightSql.Test { using System; using System.Threading.Tasks; using Xunit; public class DatabaseAbstractionTest { [Fact] public async Task DatabaseAbstractionTestAsync() { var queryDispatcher = new QueryDispatcher(new ConnectionFactory(ConnectionString.Default)); var database = new Database(queryDispatcher, TestReaderCollection.Default); var setupQueries = new String[] { "DROP TABLE IF EXISTS database_abstraction_test;", "CREATE TABLE database_abstraction_test (id INT NOT NULL, value TEXT NOT NULL);", "INSERT INTO database_abstraction_test VALUES (1, 'James');", "INSERT INTO database_abstraction_test VALUES (2, 'Madison');", "INSERT INTO database_abstraction_test VALUES (3, 'University');" }; foreach (var setupQuery in setupQueries) await queryDispatcher.ExecuteAsync(new Query(setupQuery)); var item = await database .CreateQuery(@" SELECT id, value FROM contextualized_query_builder_query_test WHERE value = :value;") .SetParameter("value", "Hopkins") .FirstAsync<TestItem>(); Assert.NotNull(item); Assert.Equal(item.Id, 3); Assert.Equal(item.Value, "Hopkins"); } } } ``` Fix database abstraction test to use correct table name, etc.
```c# namespace StraightSql.Test { using System; using System.Threading.Tasks; using Xunit; public class DatabaseAbstractionTest { [Fact] public async Task DatabaseAbstractionTestAsync() { var queryDispatcher = new QueryDispatcher(new ConnectionFactory(ConnectionString.Default)); var database = new Database(queryDispatcher, TestReaderCollection.Default); var setupQueries = new String[] { "DROP TABLE IF EXISTS database_abstraction_test;", "CREATE TABLE database_abstraction_test (id INT NOT NULL, value TEXT NOT NULL);", "INSERT INTO database_abstraction_test VALUES (1, 'James');", "INSERT INTO database_abstraction_test VALUES (2, 'Madison');", "INSERT INTO database_abstraction_test VALUES (3, 'University');" }; foreach (var setupQuery in setupQueries) await queryDispatcher.ExecuteAsync(new Query(setupQuery)); var item = await database .CreateQuery(@" SELECT id, value FROM database_abstraction_test WHERE id = :id;") .SetParameter("id", 1) .FirstAsync<TestItem>(); Assert.NotNull(item); Assert.Equal(item.Id, 1); Assert.Equal(item.Value, "James"); } } } ```
88b19344-94b7-490e-97ea-71e5f902757f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace aspnet_start { public class Startup { public static IWebHost WebHost = null; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } lifetime.ApplicationStarted.Register(OnAppStarted); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } private void OnAppStarted() { Program._startupTimer.Stop(); Log($"Startup elapsed ms: {Program._startupTimer.ElapsedMilliseconds} ms"); WebHost.StopAsync(TimeSpan.FromSeconds(1)); } private void Log(string s) { string time = DateTime.UtcNow.ToString(); Console.WriteLine($"[{time}] {s}"); } } } ``` Add more precision to aspnet_start reported times.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace aspnet_start { public class Startup { public static IWebHost WebHost = null; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } lifetime.ApplicationStarted.Register(OnAppStarted); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } private void OnAppStarted() { Program._startupTimer.Stop(); Log($"Startup elapsed ms: {Program._startupTimer.Elapsed.TotalMilliseconds} ms"); WebHost.StopAsync(TimeSpan.FromSeconds(1)); } private void Log(string s) { string time = DateTime.UtcNow.ToString(); Console.WriteLine($"[{time}] {s}"); } } } ```
75fede29-329e-4006-825b-6957d37bd795
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; namespace TimeToMain { public static class Program { [DllImport("libnative.so")] private static extern void write_marker(string name); public static void Main(string[] args) { write_marker("/function/main"); } } } ``` Convert source to Hello World.
```c# using System; using System.Runtime.InteropServices; namespace TimeToMain { public static class Program { [DllImport("libnative.so")] private static extern void write_marker(string name); public static void Main(string[] args) { Console.WriteLine("Hello World!"); write_marker("/function/main"); } } } ```
12cc4642-81f7-4654-805c-f117c8587d72
{ "language": "C#" }
```c# using System; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; namespace Our.Umbraco.OpeningHours.Converters { [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] public class OpeningHoursValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) { return propertyType.PropertyEditorAlias.InvariantEquals("OpeningHours"); } public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { try { return Model.OpeningHours.Deserialize(source as string); } catch (Exception e) { LogHelper.Error<OpeningHoursValueConverter>("Error converting value", e); } // Create default model return new Model.OpeningHours(); } } }``` Allow Models Builder to have correct type
```c# using System; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Our.Umbraco.OpeningHours.Model; namespace Our.Umbraco.OpeningHours.Converters { [PropertyValueType(typeof(OpeningHours))] [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] public class OpeningHoursValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) { return propertyType.PropertyEditorAlias.InvariantEquals("OpeningHours"); } public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { try { return Model.OpeningHours.Deserialize(source as string); } catch (Exception e) { LogHelper.Error<OpeningHoursValueConverter>("Error converting value", e); } // Create default model return new Model.OpeningHours(); } } } ```
40bcc700-c7b2-428d-bb6f-b066101fa6bf
{ "language": "C#" }
```c# using NakedObjects; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AdventureWorksModel { public partial class PersonPhone { #region Injected Services public IDomainObjectContainer Container { set; protected get; } #endregion #region Title public override string ToString() { var t = Container.NewTitleBuilder(); t.Append(PhoneNumberType).Append(":", PhoneNumber); return t.ToString(); } #endregion [NakedObjectsIgnore] public virtual int BusinessEntityID { get; set; } public virtual string PhoneNumber { get; set; } [NakedObjectsIgnore] public virtual int PhoneNumberTypeID { get; set; } [ConcurrencyCheck] public virtual DateTime ModifiedDate { get; set; } [NakedObjectsIgnore] public virtual Person Person { get; set; } public virtual PhoneNumberType PhoneNumberType { get; set; } } } ``` Fix AW error - creating new phone number
```c# using NakedObjects; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AdventureWorksModel { public partial class PersonPhone { #region Injected Services public IDomainObjectContainer Container { set; protected get; } #endregion #region Lifecycle methods public void Persisting() { ModifiedDate = DateTime.Now; } #endregion #region Title public override string ToString() { var t = Container.NewTitleBuilder(); t.Append(PhoneNumberType).Append(":", PhoneNumber); return t.ToString(); } #endregion [NakedObjectsIgnore] public virtual int BusinessEntityID { get; set; } public virtual string PhoneNumber { get; set; } [NakedObjectsIgnore] public virtual int PhoneNumberTypeID { get; set; } [ConcurrencyCheck] public virtual DateTime ModifiedDate { get; set; } [NakedObjectsIgnore] public virtual Person Person { get; set; } public virtual PhoneNumberType PhoneNumberType { get; set; } } } ```
a67b386a-15d9-4189-98f5-51d97c7941e2
{ "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.Graphics.Containers; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherSprite : CompositeDrawable { public CatcherSprite() { Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE; } [BackgroundDependencyLoader] private void load() { InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle") { RelativeSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }; } } } ``` Fix osu!catch catcher not scaling down correctly
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherSprite : CompositeDrawable { public CatcherSprite() { Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE; } [BackgroundDependencyLoader] private void load() { InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle", confineMode: ConfineMode.ScaleDownToFit) { RelativeSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }; } } } ```
b7c181a3-6412-45f9-b377-111b9aec3907
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace EasyNetQ.Management.Client.Model { public class ExchangeInfo { public string Type { get; private set; } public bool AutoDelete { get; private set; } public bool Durable { get; private set; } public bool Internal { get; private set; } public Arguments Arguments { get; private set; } private readonly string name; private readonly ISet<string> exchangeTypes = new HashSet<string> { "direct", "topic", "fanout", "headers" }; public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments()) { } public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments) { if(string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if(type == null) { throw new ArgumentNullException("type"); } if (!exchangeTypes.Contains(type)) { throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}", type, string.Join(", ", exchangeTypes)); } this.name = name; Type = type; AutoDelete = autoDelete; Durable = durable; Internal = @internal; Arguments = arguments; } public string GetName() { return name; } } }``` Add "x-delayed-message" as valid exchange type
```c# using System; using System.Collections.Generic; namespace EasyNetQ.Management.Client.Model { public class ExchangeInfo { public string Type { get; private set; } public bool AutoDelete { get; private set; } public bool Durable { get; private set; } public bool Internal { get; private set; } public Arguments Arguments { get; private set; } private readonly string name; private readonly ISet<string> exchangeTypes = new HashSet<string> { "direct", "topic", "fanout", "headers", "x-delayed-message" }; public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments()) { } public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments) { if(string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if(type == null) { throw new ArgumentNullException("type"); } if (!exchangeTypes.Contains(type)) { throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}", type, string.Join(", ", exchangeTypes)); } this.name = name; Type = type; AutoDelete = autoDelete; Durable = durable; Internal = @internal; Arguments = arguments; } public string GetName() { return name; } } } ```
0614c3eb-47e2-4773-9734-c9321ddaa923
{ "language": "C#" }
```c# using UnityEditor; using UnityEngine; namespace GitHub.Unity { public class PublishWindow : EditorWindow { private const string PublishTitle = "Publish this repository to GitHub"; private string repoName = ""; private string repoDescription = ""; private int selectedOrg = 0; private bool togglePrivate = false; private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" }; static void Init() { PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow)); window.Show(); } void OnGUI() { GUILayout.Label(PublishTitle, EditorStyles.boldLabel); GUILayout.Space(5); repoName = EditorGUILayout.TextField("Name", repoName); repoDescription = EditorGUILayout.TextField("Description", repoDescription); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private"); } GUILayout.EndHorizontal(); selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs); GUILayout.Space(5); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Create")) { Debug.Log("CREATING A REPO HAPPENS HERE!"); this.Close(); } } GUILayout.EndHorizontal(); } } } ``` Add an area for errors
```c# using UnityEditor; using UnityEngine; namespace GitHub.Unity { public class PublishWindow : EditorWindow { private const string PublishTitle = "Publish this repository to GitHub"; private string repoName = ""; private string repoDescription = ""; private int selectedOrg = 0; private bool togglePrivate = false; // TODO: Replace me since this is just to test rendering errors private bool error = true; private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" }; static void Init() { PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow)); window.Show(); } void OnGUI() { GUILayout.Label(PublishTitle, EditorStyles.boldLabel); GUILayout.Space(5); repoName = EditorGUILayout.TextField("Name", repoName); repoDescription = EditorGUILayout.TextField("Description", repoDescription); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private"); } GUILayout.EndHorizontal(); selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs); GUILayout.Space(5); if (error) GUILayout.Label("There was an error", Styles.ErrorLabel); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Create")) { Debug.Log("CREATING A REPO HAPPENS HERE!"); this.Close(); } } GUILayout.EndHorizontal(); } } } ```
dfb453a9-5758-4fd4-8fc6-087efd9fd6d3
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]``` Bump up new version for assemblyinfor file
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")] [assembly: AssemblyVersion("3.0.1.0")] [assembly: AssemblyFileVersion("3.0.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]```
f7eef529-6337-4fdd-9117-74e9848b2b1e
{ "language": "C#" }
```c# #region using System; using System.Reflection; using System.Runtime.InteropServices; #endregion namespace DesktopWidgets.Classes { internal static class AssemblyInfo { public static Version Version { get; } = Assembly.GetExecutingAssembly().GetName().Version; public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright); public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title); public static string Description { get; } = GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description); public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value); private static string GetAssemblyAttribute<T>(Func<T, string> value) where T : Attribute { var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T)); return value.Invoke(attribute); } } }``` Fix incorrect version number displayed when deployed
```c# #region using System; using System.Deployment.Application; using System.Reflection; using System.Runtime.InteropServices; #endregion namespace DesktopWidgets.Classes { internal static class AssemblyInfo { public static Version Version { get; } = (ApplicationDeployment.IsNetworkDeployed ? ApplicationDeployment.CurrentDeployment.CurrentVersion : Assembly.GetExecutingAssembly().GetName().Version); public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright); public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title); public static string Description { get; } = GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description); public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value); private static string GetAssemblyAttribute<T>(Func<T, string> value) where T : Attribute { var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T)); return value.Invoke(attribute); } } }```
d4fede5d-a77c-4238-bc97-66a29cccc77f
{ "language": "C#" }
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ``` Update server side API for single multiple answer question
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ```
acd5be95-c926-45c4-b6b7-68acb9382ddd
{ "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. namespace Microsoft.CodeAnalysis.Editor { internal struct CodeDefinitionWindowLocation { public string DisplayName { get; } public string FilePath { get; } public int Line { get; } public int Character { get; } public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character) { DisplayName = displayName; FilePath = filePath; Line = line; Character = character; } } } ``` Fix formatting and add some constructor overloads
```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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal struct CodeDefinitionWindowLocation { public string DisplayName { get; } public string FilePath { get; } public int Line { get; } public int Character { get; } public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character) { DisplayName = displayName; FilePath = filePath; Line = line; Character = character; } public CodeDefinitionWindowLocation(string displayName, string filePath, LinePositionSpan position) : this (displayName, filePath, position.Start.Line, position.Start.Character) { } public CodeDefinitionWindowLocation(string displayName, FileLinePositionSpan position) : this (displayName, position.Path, position.Span) { } } } ```
cee6e1cb-5c16-4999-b4d2-71b3aa2db26e
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace Tweetinvi.Models.V2 { public class UrlV2 { /// <summary> /// The URL as displayed in the Twitter client. /// </summary> [JsonProperty("display_url")] public string DisplayUrl { get; set; } /// <summary> /// The end position (zero-based) of the recognized URL within the Tweet. /// </summary> [JsonProperty("end")] public int End { get; set; } /// <summary> /// The fully resolved URL. /// </summary> [JsonProperty("expanded_url")] public string ExpandedUrl { get; set; } /// <summary> /// The start position (zero-based) of the recognized URL within the Tweet. /// </summary> [JsonProperty("start")] public int Start { get; set; } /// <summary> /// The URL in the format tweeted by the user. /// </summary> [JsonProperty("url")] public string Url { get; set; } /// <summary> /// The full destination URL. /// </summary> [JsonProperty("unwound_url")] public string UnwoundUrl { get; set; } } public class UrlsV2 { /// <summary> /// Contains details about text recognized as a URL. /// </summary> [JsonProperty("urls")] public UrlV2[] Urls { get; set; } } }``` Add more properties found in Twitter V2 Url
```c# using Newtonsoft.Json; namespace Tweetinvi.Models.V2 { public class UrlV2 { /// <summary> /// The URL as displayed in the Twitter client. /// </summary> [JsonProperty("display_url")] public string DisplayUrl { get; set; } /// <summary> /// The end position (zero-based) of the recognized URL within the Tweet. /// </summary> [JsonProperty("end")] public int End { get; set; } /// <summary> /// The fully resolved URL. /// </summary> [JsonProperty("expanded_url")] public string ExpandedUrl { get; set; } /// <summary> /// The start position (zero-based) of the recognized URL within the Tweet. /// </summary> [JsonProperty("start")] public int Start { get; set; } /// <summary> /// The URL in the format tweeted by the user. /// </summary> [JsonProperty("url")] public string Url { get; set; } /// <summary> /// The full destination URL. /// </summary> [JsonProperty("unwound_url")] public string UnwoundUrl { get; set; } /// <summary> /// Title of the URL /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// Description of the URL /// </summary> [JsonProperty("description")] public string Description { get; set; } } public class UrlsV2 { /// <summary> /// Contains details about text recognized as a URL. /// </summary> [JsonProperty("urls")] public UrlV2[] Urls { get; set; } } } ```
b4863652-5085-460e-b4d9-86dff5caec3b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePlayground { class Program { static void Main(string[] args) { // This doesn't change (yet): foreach (var item in GeneratedStrings()) Console.WriteLine(item); } // Core syntax for an enumerable: private static IEnumerable<string> GeneratedStrings() { yield return "one"; yield return "two"; yield return "three"; } } } ``` Use my enumerable in a loop
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePlayground { class Program { static void Main(string[] args) { // This doesn't change (yet): foreach (var item in GeneratedStrings()) Console.WriteLine(item); } // Core syntax for an enumerable: private static IEnumerable<string> GeneratedStrings() { var i = 0; while (i++ < 100) yield return i.ToString(); } } } ```
8b491bb7-3062-4777-abf6-394325b5b5f0
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Revenge Of The Cats - shell.cs // Code for Revenge Of The Cats' Shell //------------------------------------------------------------------------------ if(isObject(DefaultCursor)) { DefaultCursor.delete(); new GuiCursor(DefaultCursor) { hotSpot = "1 1"; bitmapName = "./pixmaps/mg_arrow2"; }; } function addWindow(%control) { if(Canvas.getContent() == Shell.getId()) Shell.add(%control); else ShellDlg.add(%control); %control.onAddedAsWindow(); Canvas.repaint(); } function removeWindow(%control) { %control.getParent().remove(%control); %control.onRemovedAsWindow(); Canvas.repaint(); } function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount) { // // display the root menu... // if( Shell.isMember(RootMenu) ) removeWindow(RootMenu); else { RootMenu.position = %coord; //addWindow(RootMenu); //Canvas.repaint(); } } function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount) { // } ``` Make sure window is visible.
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Revenge Of The Cats - shell.cs // Code for Revenge Of The Cats' Shell //------------------------------------------------------------------------------ if(isObject(DefaultCursor)) { DefaultCursor.delete(); new GuiCursor(DefaultCursor) { hotSpot = "1 1"; bitmapName = "./pixmaps/mg_arrow2"; }; } function addWindow(%control) { %parent = Shell; if(Canvas.getContent() != Shell.getId()) %parent = ShellDlg; %parent.add(%control); %parent.pushToBack(%control); %control.onAddedAsWindow(); Canvas.repaint(); } function removeWindow(%control) { %control.getParent().remove(%control); %control.onRemovedAsWindow(); Canvas.repaint(); } function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount) { // // display the root menu... // if( Shell.isMember(RootMenu) ) removeWindow(RootMenu); else { RootMenu.position = %coord; //addWindow(RootMenu); //Canvas.repaint(); } } function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount) { // } ```
6972bb8c-5968-4766-b103-ce6ad1546f15
{ "language": "C#" }
```c# using FireworksNet.Algorithm; using FireworksNet.Algorithm.Implementation; using FireworksNet.Problems; using FireworksNet.StopConditions; using System; using Xunit; namespace FireworksNet.Tests.Algorithm { public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource { } } ``` Add basic test for ParallelFireworkAlgorithm.
```c# using FireworksNet.Algorithm; using FireworksNet.Algorithm.Implementation; using FireworksNet.Problems; using FireworksNet.StopConditions; using System; using Xunit; namespace FireworksNet.Tests.Algorithm { public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource { [Theory] [MemberData("DataForTestingCreationOfParallelFireworkAlgorithm")] public void CreationParallelFireworkAlgorithm_PassEachParameterAsNullAndOtherIsCorrect_ArgumentNullExceptionThrown( Problem problem, IStopCondition stopCondition, ParallelFireworksAlgorithmSettings settings, string expectedParamName) { ArgumentException exception = Assert.Throws<ArgumentNullException>(() => new ParallelFireworksAlgorithm(problem, stopCondition, settings)); Assert.Equal(expectedParamName, exception.ParamName); } } } ```
2818d832-1501-4137-8db6-745384f4142f
{ "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.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } } ``` Fix health not being calculated in osu! mode (regression).
```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.Game.Modes.Objects.Drawables; using osu.Game.Modes.Osu.Judgements; using osu.Game.Modes.Osu.Objects; using osu.Game.Modes.Scoring; using osu.Game.Modes.UI; namespace osu.Game.Modes.Osu.Scoring { internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement> { public OsuScoreProcessor() { } public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer) : base(hitRenderer) { } protected override void Reset() { base.Reset(); Health.Value = 1; Accuracy.Value = 1; } protected override void OnNewJudgement(OsuJudgement judgement) { if (judgement != null) { switch (judgement.Result) { case HitResult.Hit: Health.Value += 0.1f; break; case HitResult.Miss: Health.Value -= 0.2f; break; } } int score = 0; int maxScore = 0; foreach (var j in Judgements) { score += j.ScoreValue; maxScore += j.MaxScoreValue; } TotalScore.Value = score; Accuracy.Value = (double)score / maxScore; } } } ```
a4f00429-2f67-4c2f-bcec-78895c97abbc
{ "language": "C#" }
```c# namespace Gigobyte.Daterpillar.Management { public interface ISchemaComparer : System.IDisposable { SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target); } }``` Add new overload to Compare method
```c# using Gigobyte.Daterpillar.Transformation; namespace Gigobyte.Daterpillar.Management { public interface ISchemaComparer : System.IDisposable { SchemaDiscrepancy Compare(Schema source, Schema target); SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target); } }```
40e117f8-18ee-4c50-9fcb-6a9985a5a3e1
{ "language": "C#" }
```c# namespace Gu.Analyzers.Test.GU0006UseNameofTests { using System.Threading.Tasks; using NUnit.Framework; internal class HappyPath : HappyPathVerifier<GU0006UseNameof> { [Test] public async Task WhenThrowingArgumentException() { var testCode = @" using System; public class Foo { public void Meh(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } } }"; await this.VerifyHappyPathAsync(testCode) .ConfigureAwait(false); } [Test] public async Task ArgumentOutOfRangeException() { var testCode = @" using System; public class Foo { public void Meh(StringComparison value) { switch (value) { default: throw new ArgumentOutOfRangeException(nameof(value), value, null); } } }"; await this.VerifyHappyPathAsync(testCode) .ConfigureAwait(false); } } }``` Test that nameof nag is ignored in
```c# namespace Gu.Analyzers.Test.GU0006UseNameofTests { using System.Threading.Tasks; using NUnit.Framework; internal class HappyPath : HappyPathVerifier<GU0006UseNameof> { [Test] public async Task WhenThrowingArgumentException() { var testCode = @" using System; public class Foo { public void Meh(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } } }"; await this.VerifyHappyPathAsync(testCode) .ConfigureAwait(false); } [Test] public async Task ArgumentOutOfRangeException() { var testCode = @" using System; public class Foo { public void Meh(StringComparison value) { switch (value) { default: throw new ArgumentOutOfRangeException(nameof(value), value, null); } } }"; await this.VerifyHappyPathAsync(testCode) .ConfigureAwait(false); } [Test] public async Task IgnoresDebuggerDisplay() { var testCode = @" [System.Diagnostics.DebuggerDisplay(""{Name}"")] public class Foo { public string Name { get; } }"; await this.VerifyHappyPathAsync(testCode) .ConfigureAwait(false); } } }```
d156acda-518c-4b89-a07e-e338f2ad8a82
{ "language": "C#" }
```c# using System; namespace BenchmarkDotNet.Diagnostics { [Obsolete("The \"GCDiagnoser\" has been renamed, please use the \"MemoryDiagnoser\" instead (it has the same functionality)", true)] public class GCDiagnoser { } } ``` Revert "give compilation error instead of warning or exception at runtime"
```c# using System; using System.Collections.Generic; using System.Diagnostics; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; namespace BenchmarkDotNet.Diagnostics.Windows { [Obsolete(message)] public class GCDiagnoser : IDiagnoser, IColumnProvider { const string message = "The \"GCDiagnoser\" has been renamed, please us the \"MemoryDiagnoser\" instead (it has the same functionality)"; public IEnumerable<IColumn> GetColumns { get { throw new InvalidOperationException(message); } } public void AfterBenchmarkHasRun(Benchmark benchmark, Process process) { throw new InvalidOperationException(message); } public void DisplayResults(ILogger logger) { throw new InvalidOperationException(message); } public void ProcessStarted(Process process) { throw new InvalidOperationException(message); } public void ProcessStopped(Process process) { throw new InvalidOperationException(message); } public void Start(Benchmark benchmark) { throw new InvalidOperationException(message); } public void Stop(Benchmark benchmark, BenchmarkReport report) { throw new InvalidOperationException(message); } } } ```
556349cc-6e95-42f5-99e4-f0685dbf377c
{ "language": "C#" }
```c# using System.ComponentModel.Composition.Hosting; using Raven.Client; using Raven.Client.Indexes; namespace Snittlistan.Infrastructure.Indexes { public static class IndexCreator { public static void CreateIndexes(IDocumentStore store) { var typeCatalog = new TypeCatalog(typeof(Matches_PlayerStats), typeof(Match_ByDate)); IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store); } } }``` Install all indexes by scanning assembly
```c# using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Raven.Client; using Raven.Client.Indexes; namespace Snittlistan.Infrastructure.Indexes { public static class IndexCreator { public static void CreateIndexes(IDocumentStore store) { var indexes = from type in Assembly.GetExecutingAssembly().GetTypes() where type.IsSubclassOf(typeof(AbstractIndexCreationTask)) select type; var typeCatalog = new TypeCatalog(indexes.ToArray()); IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store); } } }```
e43fbd33-8a67-4a82-a9e9-45920cf2bb90
{ "language": "C#" }
```c# namespace PersonPrisoner { class Program { static void Main(string[] args) { Person person = new Prisoner(); person.WalkEast(5); } } } ``` Add explanatory text comment for person-prisoner example
```c# namespace PersonPrisoner { class Program { static void Main(string[] args) { Person person = new Prisoner(); person.WalkEast(5); } } #region Explanation // At a first glance, it would be pretty obvious to make the prisoner derive from person class. // Just as obviously, this leads us into trouble, since a prisoner is not free to move an arbitrary distance // in any direction, yet the contract of the Person class states that a Person can. //So, in fact, the class Person could better be named FreePerson. If that were the case, then the idea that //class Prisoner extends FreePerson is clearly wrong. //By analogy, then, a Square is not an Rectangle, because it lacks the same degrees of freedom as an Rectangle. //This strongly suggests that inheritance should never be used when the sub-class restricts the freedom //implicit in the base class. It should only be used when the sub-class adds extra detail to the concept //represented by the base class, for example, 'Monkey' is-an 'Animal'. #endregion } ```
86f434ec-cebf-4343-bbf6-8aaaf9236b33
{ "language": "C#" }
```c# using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Models { /// <inheritdoc /> public sealed class ChatChannel : Api.Models.ChatChannel { /// <summary> /// The row Id /// </summary> public long Id { get; set; } /// <summary> /// The <see cref="Api.Models.Internal.ChatBot.Id"/> /// </summary> public long ChatSettingsId { get; set; } /// <summary> /// The <see cref="Models.ChatBot"/> /// </summary> public ChatBot ChatSettings { get; set; } /// <summary> /// Convert the <see cref="ChatChannel"/> to it's API form /// </summary> /// <returns>A new <see cref="Api.Models.ChatChannel"/></returns> public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel { DiscordChannelId = DiscordChannelId, IsAdminChannel = IsAdminChannel, IsWatchdogChannel = IsWatchdogChannel, IrcChannel = IrcChannel }; } } ``` Fix IsUpdatesChannel missing from ToApi()
```c# using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Models { /// <inheritdoc /> public sealed class ChatChannel : Api.Models.ChatChannel { /// <summary> /// The row Id /// </summary> public long Id { get; set; } /// <summary> /// The <see cref="Api.Models.Internal.ChatBot.Id"/> /// </summary> public long ChatSettingsId { get; set; } /// <summary> /// The <see cref="Models.ChatBot"/> /// </summary> public ChatBot ChatSettings { get; set; } /// <summary> /// Convert the <see cref="ChatChannel"/> to it's API form /// </summary> /// <returns>A new <see cref="Api.Models.ChatChannel"/></returns> public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel { DiscordChannelId = DiscordChannelId, IsAdminChannel = IsAdminChannel, IsWatchdogChannel = IsWatchdogChannel, IsUpdatesChannel = IsUpdatesChannel, IrcChannel = IrcChannel }; } } ```
470281d3-9776-47c2-ad1b-2492ab1ae077
{ "language": "C#" }
```c# using System; using Castle.DynamicProxy; using Dargon.Services.PortableObjects; using Dargon.Services.Utilities; namespace Dargon.Services.Client { public class ServiceInvocationInterceptor : IInterceptor { private readonly IServiceContext serviceContext; public ServiceInvocationInterceptor(IServiceContext serviceContext) { this.serviceContext = serviceContext; } public void Intercept(IInvocation invocation) { var methodName = invocation.Method.Name; var methodArguments = invocation.Arguments; invocation.ReturnValue = serviceContext.Invoke(methodName, methodArguments); } } }``` Throw exceptions returned by service context.
```c# using System; using Castle.DynamicProxy; using Dargon.Services.PortableObjects; using Dargon.Services.Utilities; namespace Dargon.Services.Client { public class ServiceInvocationInterceptor : IInterceptor { private readonly IServiceContext serviceContext; public ServiceInvocationInterceptor(IServiceContext serviceContext) { this.serviceContext = serviceContext; } public void Intercept(IInvocation invocation) { var methodName = invocation.Method.Name; var methodArguments = invocation.Arguments; var result = serviceContext.Invoke(methodName, methodArguments); var exception = result as Exception; if (exception != null) { throw exception; } else { invocation.ReturnValue = result;; } } } }```
775fe2a9-2bbb-4cd7-9130-91d20c8d2121
{ "language": "C#" }
```c# using System; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly AppHarborApi _appHarborApi; public CreateCommand(AppHarborApi appHarborApi) { _appHarborApi = appHarborApi; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } } ``` Create application when executing create command
```c# using System; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly AppHarborApi _appHarborApi; public CreateCommand(AppHarborApi appHarborApi) { _appHarborApi = appHarborApi; } public void Execute(string[] arguments) { var result = _appHarborApi.CreateApplication(arguments[0], arguments[1]); throw new NotImplementedException(); } } } ```
baac2ab4-8e78-451f-9b96-c41a1d080968
{ "language": "C#" }
```c# namespace Vlc.DotNet.Core { public interface IAudioManagement { IAudioOutputsManagement Outputs { get; } } } ``` Add Audio properties to IAudiomanagement
```c# namespace Vlc.DotNet.Core { public interface IAudioManagement { IAudioOutputsManagement Outputs { get; } bool IsMute { get; set; } void ToggleMute(); int Volume { get; set; } ITracksManagement Tracks { get; } int Channel { get; set; } long Delay { get; set; } } } ```
e30344ba-0e01-4267-82d4-9a7fa30bc7ed
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using JetBrains.Annotations; using JetBrains.Metadata.Utils; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations; using JetBrains.Util; namespace AgentHeisenbug.Annotations { #if DEBUG [PsiComponent] public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider { [NotNull] private readonly FileSystemPath _path; public HeisenbugDebugExternalAnnotationFileProvider() { _path = FileSystemPath.Parse(Assembly.GetExecutingAssembly().Location) .Combine("../../../#annotations"); } public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) { if (assemblyName == null) return Enumerable.Empty<FileSystemPath>(); var directoryForAssembly = _path.Combine(assemblyName.Name); if (!directoryForAssembly.ExistsDirectory) return Enumerable.Empty<FileSystemPath>(); return directoryForAssembly.GetDirectoryEntries("*.xml", true); } } #endif } ``` Fix to the last commit.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using JetBrains.Annotations; using JetBrains.Metadata.Utils; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations; using JetBrains.Util; namespace AgentHeisenbug.Annotations { #if DEBUG [PsiComponent] public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider { [NotNull] private readonly FileSystemPath _path; public HeisenbugDebugExternalAnnotationFileProvider() { _path = FileSystemPath.Parse(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).NotNull()) .Combine("../../../#annotations"); } public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) { if (assemblyName == null) return Enumerable.Empty<FileSystemPath>(); var directoryForAssembly = _path.Combine(assemblyName.Name); if (!directoryForAssembly.ExistsDirectory) return Enumerable.Empty<FileSystemPath>(); return directoryForAssembly.GetDirectoryEntries("*.xml", true); } } #endif } ```
9ef23df9-e499-4f8e-9906-2290e14d6bd2
{ "language": "C#" }
```c# using System.Threading.Tasks; using Newtonsoft.Json; namespace Audiotica.Core.Utils { public static class StringExtensions { public static string CleanForFileName(this string str, string invalidMessage) { if (string.IsNullOrEmpty(str)) { return null; } /* * A filename cannot contain any of the following characters: * \ / : * ? " < > | */ var name = str.Replace("\\", string.Empty) .Replace("/", string.Empty) .Replace(":", " ") .Replace("*", string.Empty) .Replace("?", string.Empty) .Replace("\"", "'") .Replace("<", string.Empty) .Replace(">", string.Empty) .Replace("|", " "); return string.IsNullOrEmpty(name) ? invalidMessage : name; } public static async Task<T> DeserializeAsync<T>(this string json) { return await Task.Factory.StartNew( () => { try { return JsonConvert.DeserializeObject<T>(json); } catch { return default(T); } }).ConfigureAwait(false); } public static string StripHtmlTags(this string str) { return HtmlRemoval.StripTagsRegex(str); } } }``` Fix path too long bug
```c# using System.Threading.Tasks; using Newtonsoft.Json; namespace Audiotica.Core.Utils { public static class StringExtensions { public static string CleanForFileName(this string str, string invalidMessage) { if (string.IsNullOrEmpty(str)) { return null; } if (str.Length > 35) { str = str.Substring(0, 35); } /* * A filename cannot contain any of the following characters: * \ / : * ? " < > | */ var name = str.Replace("\\", string.Empty) .Replace("/", string.Empty) .Replace(":", " ") .Replace("*", string.Empty) .Replace("?", string.Empty) .Replace("\"", "'") .Replace("<", string.Empty) .Replace(">", string.Empty) .Replace("|", " "); return string.IsNullOrEmpty(name) ? invalidMessage : name; } public static async Task<T> DeserializeAsync<T>(this string json) { return await Task.Factory.StartNew( () => { try { return JsonConvert.DeserializeObject<T>(json); } catch { return default(T); } }).ConfigureAwait(false); } public static string StripHtmlTags(this string str) { return HtmlRemoval.StripTagsRegex(str); } } }```
05771cc9-3419-4785-9d97-1674fe297c70
{ "language": "C#" }
```c# using System; using System.Drawing; using System.Reflection; using System.Windows.Forms; namespace IronAHK.Scripting { partial class Script { public static void CreateTrayMenu() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) return; var menu = new NotifyIcon { ContextMenu = new ContextMenu() }; menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); })); menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); })); var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico"); if (favicon != null) { menu.Icon = new Icon(favicon); menu.Visible = true; } } } } ``` Remove tray icon on safe exit.
```c# using System; using System.Drawing; using System.Reflection; using System.Windows.Forms; namespace IronAHK.Scripting { partial class Script { public static void CreateTrayMenu() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) return; var menu = new NotifyIcon { ContextMenu = new ContextMenu() }; menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); })); menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); })); var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico"); if (favicon != null) { menu.Icon = new Icon(favicon); menu.Visible = true; } ApplicationExit += delegate { menu.Visible = false; menu.Dispose(); }; } } } ```
635e700b-75a1-4b63-822c-53fecb107ba6
{ "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. #nullable disable using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Difficulty.Skills; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Taiko.Difficulty.Skills { /// <summary> /// Calculates the colour coefficient of taiko difficulty. /// </summary> public class Colour : StrainDecaySkill { protected override double SkillMultiplier => 1; protected override double StrainDecayBase => 0.4; public Colour(Mod[] mods) : base(mods) { } protected override double StrainValueOf(DifficultyHitObject current) { TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour; double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty; if (current != null && colour != null) { ColourEncoding[] payload = colour.Encoding.Payload; string payloadDisplay = ""; for (int i = 0; i < payload.Length; ++i) { payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})"; } System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}"); } return difficulty; } } } ``` Comment out logging for debugging purposes
```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. #nullable disable using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Difficulty.Skills; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Taiko.Difficulty.Skills { /// <summary> /// Calculates the colour coefficient of taiko difficulty. /// </summary> public class Colour : StrainDecaySkill { protected override double SkillMultiplier => 1; protected override double StrainDecayBase => 0.4; public Colour(Mod[] mods) : base(mods) { } protected override double StrainValueOf(DifficultyHitObject current) { TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour; double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty; // if (current != null && colour != null) // { // ColourEncoding[] payload = colour.Encoding.Payload; // string payloadDisplay = ""; // for (int i = 0; i < payload.Length; ++i) // { // payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})"; // } // System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}"); // } return difficulty; } } } ```
55033cf4-45e0-448a-853d-470e41cd4610
{ "language": "C#" }
```c# using Xunit; namespace Nett.UnitTests { public class TomlConfigTests { [Fact] public void WhenConfigHasActivator_ActivatorGetsUsed() { // Arrange var config = TomlConfig.Create(cfg => cfg .ConfigureType<IFoo>(ct => ct .CreateInstance(() => new Foo()) ) ); string toml = @"[Foo]"; // Act var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config); // Assert Assert.IsType<Foo>(co.Foo); } [Fact(DisplayName = "External configuration batch code is executed when configuration is done")] public void WhenConfigShouldRunExtenralConfig_ThisConfigGetsExecuted() { // Arrange var config = TomlConfig.Create(cfg => cfg .Apply(ExternalConfigurationBatch) ); string toml = @"[Foo]"; // Act var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config); // Assert Assert.IsType<Foo>(co.Foo); } private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder) { builder .ConfigureType<IFoo>(ct => ct .CreateInstance(() => new Foo()) ); } class ConfigObject { public TestStruct S { get; set; } } struct TestStruct { public int Value; } interface IFoo { } class Foo : IFoo { } class ConfigOjectWithInterface { public IFoo Foo { get; set; } } } } ``` Fix typo in unit test name
```c# using Xunit; namespace Nett.UnitTests { public class TomlConfigTests { [Fact] public void WhenConfigHasActivator_ActivatorGetsUsed() { // Arrange var config = TomlConfig.Create(cfg => cfg .ConfigureType<IFoo>(ct => ct .CreateInstance(() => new Foo()) ) ); string toml = @"[Foo]"; // Act var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config); // Assert Assert.IsType<Foo>(co.Foo); } [Fact(DisplayName = "External configuration batch code is executed when configuration is done")] public void WhenConfigShouldRunExternalConfig_ThisConfigGetsExecuted() { // Arrange var config = TomlConfig.Create(cfg => cfg .Apply(ExternalConfigurationBatch) ); string toml = @"[Foo]"; // Act var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config); // Assert Assert.IsType<Foo>(co.Foo); } private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder) { builder .ConfigureType<IFoo>(ct => ct .CreateInstance(() => new Foo()) ); } class ConfigObject { public TestStruct S { get; set; } } struct TestStruct { public int Value; } interface IFoo { } class Foo : IFoo { } class ConfigOjectWithInterface { public IFoo Foo { get; set; } } } } ```
eaeaaef5-6a16-4db0-bd32-d2f209fbb634
{ "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. namespace osu.Framework.Audio.Sample { /// <summary> /// A <see cref="SampleChannel"/> which explicitly plays no audio. /// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound. /// </summary> public sealed class SampleChannelVirtual : SampleChannel { public SampleChannelVirtual() : base(new SampleVirtual(), _ => { }) { } public override bool Playing => false; protected override void UpdateState() { // empty override to avoid affecting sample channel count in frame statistics } private class SampleVirtual : Sample { } } } ``` Allow virtual SampleChannels to count towards statistics
```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. namespace osu.Framework.Audio.Sample { /// <summary> /// A <see cref="SampleChannel"/> which explicitly plays no audio. /// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound. /// </summary> public sealed class SampleChannelVirtual : SampleChannel { public SampleChannelVirtual() : base(new SampleVirtual(), _ => { }) { } public override bool Playing => false; private class SampleVirtual : Sample { } } } ```
3abfc857-77ba-4b26-b2a5-b0252a222281
{ "language": "C#" }
```c# using System; using System.Threading; using UnityEngine; using UnityEngine.UI; namespace PatchKit.Unity.Patcher.Licensing { public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer { private State _state = State.None; private KeyLicense _keyLicense; private Animator _animator; public InputField KeyInputField; public GameObject ErrorMessage; private void Awake() { _animator = GetComponent<Animator>(); } private void Update() { _animator.SetBool("IsOpened", _state == State.Obtaining); ErrorMessage.SetActive(ShowError); } public void Cancel() { _state = State.Cancelled; } public void Confirm() { string key = KeyInputField.text; key = key.ToUpper().Trim(); _keyLicense = new KeyLicense { Key = KeyInputField.text }; _state = State.Confirmed; } public bool ShowError { get; set; } ILicense ILicenseObtainer.Obtain() { _state = State.Obtaining; while (_state != State.Confirmed && _state != State.Cancelled) { Thread.Sleep(10); } if (_state == State.Cancelled) { throw new OperationCanceledException(); } return _keyLicense; } private enum State { None, Obtaining, Confirmed, Cancelled } } }``` Fix problem with invalid whitespaces and lower characters in input license key code
```c# using System; using System.Threading; using UnityEngine; using UnityEngine.UI; namespace PatchKit.Unity.Patcher.Licensing { public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer { private State _state = State.None; private KeyLicense _keyLicense; private Animator _animator; public InputField KeyInputField; public GameObject ErrorMessage; private void Awake() { _animator = GetComponent<Animator>(); } private void Update() { _animator.SetBool("IsOpened", _state == State.Obtaining); ErrorMessage.SetActive(ShowError); } public void Cancel() { _state = State.Cancelled; } public void Confirm() { string key = KeyInputField.text; key = key.ToUpper().Trim(); _keyLicense = new KeyLicense { Key = key }; _state = State.Confirmed; } public bool ShowError { get; set; } ILicense ILicenseObtainer.Obtain() { _state = State.Obtaining; while (_state != State.Confirmed && _state != State.Cancelled) { Thread.Sleep(10); } if (_state == State.Cancelled) { throw new OperationCanceledException(); } return _keyLicense; } private enum State { None, Obtaining, Confirmed, Cancelled } } }```
0d175e37-b1fb-4e65-aaf7-b378e200b4f2
{ "language": "C#" }
```c# /* * FSpot.Query.OrderByTime.cs * * Author(s): * Stephane Delcroix <stephane@delcroix.org> * * This is free software. See COPYING for details. * */ using System; using FSpot.Utils; namespace FSpot.Query { public class OrderByTime : IQueryCondition, IOrderCondition { public static OrderByTime OrderByTimeAsc = new OrderByTime (true); public static OrderByTime OrderByTimeDesc = new OrderByTime (false); bool asc; public bool Asc { get { return asc; } } public OrderByTime (bool asc) { this.asc = asc; } public string SqlClause () { return String.Format (" time {0}, filename {0} ", asc ? "ASC" : "DESC"); } } } ``` Order by filename ASC, so that detached versions appear always after the original photo, even if Reverse Order is used
```c# /* * FSpot.Query.OrderByTime.cs * * Author(s): * Stephane Delcroix <stephane@delcroix.org> * * This is free software. See COPYING for details. * */ using System; using FSpot.Utils; namespace FSpot.Query { public class OrderByTime : IQueryCondition, IOrderCondition { public static OrderByTime OrderByTimeAsc = new OrderByTime (true); public static OrderByTime OrderByTimeDesc = new OrderByTime (false); bool asc; public bool Asc { get { return asc; } } public OrderByTime (bool asc) { this.asc = asc; } public string SqlClause () { // filenames must always appear in alphabetical order if times are the same return String.Format (" time {0}, filename ASC ", asc ? "ASC" : "DESC"); } } } ```
fcbba8eb-baa5-4335-aaa5-30502c4ac741
{ "language": "C#" }
```c# using System.Threading.Tasks; namespace MetaMediaPlugin.Abstractions { public interface IMediaService { bool IsCameraAvailable { get; } bool IsTakePhotoSupported { get; } bool IsPickPhotoSupported { get; } string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses Task<IMediaFile> PickPhotoAsync(); Task<IMediaFile> TakePhotoAsync(); } }``` Add some comments to the new PhotosDirectory field so users understand how it is used.
```c# using System.Threading.Tasks; namespace MetaMediaPlugin.Abstractions { public interface IMediaService { bool IsCameraAvailable { get; } bool IsTakePhotoSupported { get; } bool IsPickPhotoSupported { get; } /// <summary> /// Specify the photo directory to use for your app. /// In iOS, this has no effect. /// In Android, this will be the name of the subdirectory within the shared photos directory. /// </summary> /// <value>The photos directory.</value> string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses Task<IMediaFile> PickPhotoAsync(); Task<IMediaFile> TakePhotoAsync(); } }```
9689a484-6283-4390-8793-e04407d7acc1
{ "language": "C#" }
```c# using System; using System.IO; using System.Threading.Tasks; using Microsoft.Build.CommandLine; using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Build.Utilities; namespace StructuredLogViewer { public class HostedBuild { private string projectFilePath; public HostedBuild(string projectFilePath) { this.projectFilePath = projectFilePath; } public Task<Build> BuildAndGetResult(BuildProgress progress) { var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion); var loggerDll = typeof(StructuredLogger).Assembly.Location; var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml"; progress.MSBuildCommandLine = commandLine; StructuredLogger.SaveLogToDisk = false; return System.Threading.Tasks.Task.Run(() => { try { var result = MSBuildApp.Execute(commandLine); return StructuredLogger.CurrentBuild; } catch (Exception ex) { var build = new Build(); build.Succeeded = false; build.AddChild(new Message() { Text = "Exception occurred during build:" }); build.AddChild(new Error() { Text = ex.ToString() }); return build; } }); } } } ``` Set verbosity to diagnostic on hosted build.
```c# using System; using System.IO; using System.Threading.Tasks; using Microsoft.Build.CommandLine; using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Build.Utilities; namespace StructuredLogViewer { public class HostedBuild { private string projectFilePath; public HostedBuild(string projectFilePath) { this.projectFilePath = projectFilePath; } public Task<Build> BuildAndGetResult(BuildProgress progress) { var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion); var loggerDll = typeof(StructuredLogger).Assembly.Location; var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /v:diag /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml"; progress.MSBuildCommandLine = commandLine; StructuredLogger.SaveLogToDisk = false; return System.Threading.Tasks.Task.Run(() => { try { var result = MSBuildApp.Execute(commandLine); return StructuredLogger.CurrentBuild; } catch (Exception ex) { var build = new Build(); build.Succeeded = false; build.AddChild(new Message() { Text = "Exception occurred during build:" }); build.AddChild(new Error() { Text = ex.ToString() }); return build; } }); } } } ```
fbca48ab-a0e8-488d-a5ca-aeb3a0d75b23
{ "language": "C#" }
```c# namespace Grabacr07.KanColleWrapper.Translation { public static class ItemTranslationHelper { public static string TranslateItemName(string name) { string stripped = TranslationHelper.StripInvalidCharacters(name); string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture)); return (string.IsNullOrEmpty(translated) ? name : translated); } } } ``` Fix bug that was preventing transation of some items.
```c# namespace Grabacr07.KanColleWrapper.Translation { public static class ItemTranslationHelper { public static string TranslateItemName(string name) { string stripped = name; string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture)); return (string.IsNullOrEmpty(translated) ? name : translated); } } } ```
0f45bbeb-b01e-48b8-8c82-d5d672db8e81
{ "language": "C#" }
```c# using System; using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using System.Web; namespace Abp.Web.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason { get { if (OverridedValue != null) { return OverridedValue.Reason; } try { return HttpContext.Current?.Request.Url.AbsoluteUri; } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); return null; } } } public HttpRequestEntityChangeSetReasonProvider( IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { } } } ``` Handle HttpException explicitly and include comments for workaround
```c# using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using System.Web; namespace Abp.Web.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason { get { if (OverridedValue != null) { return OverridedValue.Reason; } try { return HttpContext.Current?.Request.Url.AbsoluteUri; } catch (HttpException ex) { /* Workaround: * Accessing HttpContext.Request during Application_Start or Application_End will throw exception. * This behavior is intentional from microsoft * See https://stackoverflow.com/questions/2518057/request-is-not-available-in-this-context/23908099#comment2514887_2518066 */ Logger.Warn("HttpContext.Request access when it is not suppose to", ex); return null; } } } public HttpRequestEntityChangeSetReasonProvider( IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { } } } ```
0cbe9583-8dd2-42f1-badd-be566441399c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using Bari.Core.Generic; using Bari.Core.Tools; using Bari.Core.UI; namespace Bari.Plugins.Gallio.Tools { public class Gallio: DownloadablePackedExternalTool, IGallio { private readonly IFileSystemDirectory targetDir; public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters) : base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"), @"bin\Gallio.Echo.exe", new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters) { this.targetDir = targetDir; } public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies) { List<string> ps = testAssemblies.Select(p => (string)p).ToList(); ps.Add("/report-type:Xml"); ps.Add("/report-directory:."); ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent"); ps.Add("/report-name-format:test-report"); return Run(targetDir, ps.ToArray()); } } }``` Fix for gallio on non-windows systems
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using Bari.Core.Generic; using Bari.Core.Tools; using Bari.Core.UI; namespace Bari.Plugins.Gallio.Tools { public class Gallio: DownloadablePackedExternalTool, IGallio { private readonly IFileSystemDirectory targetDir; public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters) : base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"), Path.Combine("bin", "Gallio.Echo.exe"), new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters) { this.targetDir = targetDir; } public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies) { List<string> ps = testAssemblies.Select(p => (string)p).ToList(); ps.Add("/report-type:Xml"); ps.Add("/report-directory:."); ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent"); ps.Add("/report-name-format:test-report"); return Run(targetDir, ps.ToArray()); } } }```
881742b6-42e6-488a-b7ee-c1b888747cc0
{ "language": "C#" }
```c# using System.Diagnostics; using System.Threading; static class DebugUtilities { public static void Burn(long ms) { Stopwatch stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < ms) { } } public static void Sleep(long ms) { Stopwatch stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < ms) { Thread.Yield(); } } } ``` Add a couple of SharpDX Math related assertion helpers
```c# using SharpDX; using System; using System.Diagnostics; using System.Threading; static class DebugUtilities { public static void Burn(long ms) { Stopwatch stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < ms) { } } public static void Sleep(long ms) { Stopwatch stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < ms) { Thread.Yield(); } } [Conditional("DEBUG")] public static void AssertSamePosition(Vector3 v1, Vector3 v2) { float distance = Vector3.Distance(v1, v2); float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f; float relativeDistance = distance / denominator; Debug.Assert(relativeDistance < 1e-2, "not same position"); } [Conditional("DEBUG")] public static void AssertSameDirection(Vector3 v1, Vector3 v2) { Vector3 u1 = Vector3.Normalize(v1); Vector3 u2 = Vector3.Normalize(v2); float dotProduct = Vector3.Dot(u1, u2); Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction"); } } ```
bef564ba-516b-483d-bafa-e56a4918bdec
{ "language": "C#" }
```c# using System; using System.Linq; namespace KornelijePetak.IncidentCS { public static partial class Incident { internal static Random Rand { get; private set; } public static PrimitiveRandomizer Primitive { get; private set; } public static TextRandomizer Text { get; private set; } static Incident() { Rand = new Random(); setupConcreteRandomizers(); } public static int Seed { set { Rand = new Random(value); } } } } ``` Convert .Text and .Primitive to interfaces
```c# using System; using System.Linq; namespace KornelijePetak.IncidentCS { public static partial class Incident { internal static Random Rand { get; private set; } public static IPrimitiveRandomizer Primitive { get; private set; } public static ITextRandomizer Text { get; private set; } static Incident() { Rand = new Random(); setupConcreteRandomizers(); } public static int Seed { set { Rand = new Random(value); } } } } ```
547b7d85-2283-4846-8d44-389dfe2c2b4f
{ "language": "C#" }
```c# using System.Linq; using Microsoft.AspNetCore.Mvc; using topicr.Models; namespace topicr.Controllers.Api { [Produces("application/json")] [Route("api/topics")] public class TopicController : Controller { private readonly TopicContext _db; public TopicController(TopicContext db) { _db = db; } [HttpGet] public IActionResult GetTopics() { return Json(_db.Topics .Select(p => new { p.Id, p.Title, p.Description }) .ToList()); } [HttpPost] [Route("new")] public IActionResult PostTopic(Topic topic) { _db.Topics.Add(topic); _db.SaveChanges(); return Ok(); } } } ``` Disable caching to force fetching of data when navigating backwards. Added api to clear db.
```c# using System.Linq; using Microsoft.AspNetCore.Mvc; using topicr.Models; namespace topicr.Controllers.Api { [Produces("application/json")] [Route("api/topics")] public class TopicController : Controller { private readonly TopicContext _db; public TopicController(TopicContext db) { _db = db; } [HttpGet] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult GetTopics() { return Json(_db.Topics .Select(p => new { p.Id, p.Title, p.Description }) .ToList()); } [HttpPost] [Route("new")] public IActionResult PostTopic(Topic topic) { _db.Topics.Add(topic); _db.SaveChanges(); return Ok(); } [HttpGet] [Route("clear")] public IActionResult ClearTopics() { foreach (var topic in _db.Topics) { _db.Topics.Remove(topic); } _db.SaveChanges(); return Ok(); } } } ```
218d181c-845e-4ebd-b6fc-3824f7c579bd
{ "language": "C#" }
```c# public static class Bob { public static string Response(string statement) { if (IsSilence(statement)) return "Fine. Be that way!"; if (IsYelling(statement)) return "Whoa, chill out!"; if (IsQuestion(statement)) return "Sure."; return "Whatever."; } private static bool IsSilence (string statement) { return statement.Trim() == ""; } private static bool IsYelling (string statement) { return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+"); } private static bool IsQuestion (string statement) { return statement.Trim().EndsWith("?"); } }``` Update example implementation for Bob exercise
```c# public static class Bob { public static string Response(string statement) { if (IsSilence(statement)) return "Fine. Be that way!"; if (IsYelling(statement) && IsQuestion(statement)) return "Calm down, I know what I'm doing!"; if (IsYelling(statement)) return "Whoa, chill out!"; if (IsQuestion(statement)) return "Sure."; return "Whatever."; } private static bool IsSilence (string statement) { return statement.Trim() == ""; } private static bool IsYelling (string statement) { return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+"); } private static bool IsQuestion (string statement) { return statement.Trim().EndsWith("?"); } }```
1e7ce3d9-14a7-449e-8b17-b173af54f55e
{ "language": "C#" }
```c# using System; namespace PalmDB { /// <summary> /// Typical guard class that contains methods to validate method arguments. /// </summary> public static class Guard { /// <summary> /// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>. /// </summary> /// <param name="argument">The argument to check for null.</param> /// <param name="name">The name of the argument.</param> public static void NotNull(object argument, string name) { if (argument == null) throw new ArgumentNullException(name); } /// <summary> /// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0. /// </summary> /// <param name="argument">The argument.</param> /// <param name="name">The name.</param> public static void NotNegative(int argument, string name) { if (argument < 0) throw new ArgumentException($"{name} cannot be less than 0.", name); } } }``` Make the guard class internal
```c# using System; namespace PalmDB { /// <summary> /// Typical guard class that contains methods to validate method arguments. /// </summary> internal static class Guard { /// <summary> /// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>. /// </summary> /// <param name="argument">The argument to check for null.</param> /// <param name="name">The name of the argument.</param> public static void NotNull(object argument, string name) { if (argument == null) throw new ArgumentNullException(name); } /// <summary> /// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0. /// </summary> /// <param name="argument">The argument.</param> /// <param name="name">The name.</param> public static void NotNegative(int argument, string name) { if (argument < 0) throw new ArgumentException($"{name} cannot be less than 0.", name); } } }```
ec96b87f-6d24-4a1d-91bf-125937a39798
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using NBi.Core; using NBi.Core.ResultSet; using static NBi.Core.ResultSet.ResultSetBuilder; namespace NBi.Xml.Items.ResultSet { public class ResultSetXml : BaseItem { [XmlElement("row")] public List<RowXml> _rows { get; set; } public IList<IRow> Rows { get { return _rows.Cast<IRow>().ToList(); } } public IList<string> Columns { get { if (_rows.Count == 0) return new List<string>(); var names = new List<string>(); var row = _rows[0]; foreach (var cell in row.Cells) { if (!string.IsNullOrEmpty(cell.ColumnName)) names.Add(cell.ColumnName); else names.Add(string.Empty); } return names; } } [XmlIgnore] public Content Content { get { return new Content(Rows, Columns); } } [XmlAttribute("file")] public string File { get; set; } public string GetFile() { var file = string.Empty; if (Path.IsPathRooted(File)) file = File; else file = Settings.BasePath + File; return file; } public ResultSetXml() { _rows = new List<RowXml>(); } } } ``` Fix (again) syntax issue with using static
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using NBi.Core; using NBi.Core.ResultSet; namespace NBi.Xml.Items.ResultSet { public class ResultSetXml : BaseItem { [XmlElement("row")] public List<RowXml> _rows { get; set; } public IList<IRow> Rows { get { return _rows.Cast<IRow>().ToList(); } } public IList<string> Columns { get { if (_rows.Count == 0) return new List<string>(); var names = new List<string>(); var row = _rows[0]; foreach (var cell in row.Cells) { if (!string.IsNullOrEmpty(cell.ColumnName)) names.Add(cell.ColumnName); else names.Add(string.Empty); } return names; } } [XmlIgnore] public ResultSetBuilder.Content Content { get { return new ResultSetBuilder.Content(Rows, Columns); } } [XmlAttribute("file")] public string File { get; set; } public string GetFile() { var file = string.Empty; if (Path.IsPathRooted(File)) file = File; else file = Settings.BasePath + File; return file; } public ResultSetXml() { _rows = new List<RowXml>(); } } } ```
00d896dc-e301-42e9-a1ff-71b89a9585ba
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FightFleet { public enum BoardCellStatus { Blank = 0, Ship = 1, Hit = 2 } } ``` Add a 4th board cell status "Miss" to show that the user shoot to a blank spot.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FightFleet { public enum BoardCellStatus { Blank = 0, Ship = 1, Hit = 2, Miss = 3 } } ```
39e844c0-423f-4950-96ef-29018538c409
{ "language": "C#" }
```c# using System.Reflection; using JetBrains.ActionManagement; using JetBrains.Application.PluginSupport; // 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("Reformatting Utilities")] [assembly: AssemblyDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: AssemblyCompany("Øystein Krog")] [assembly: AssemblyProduct("ReformatUtils")] [assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.*")] [assembly: AssemblyFileVersion("1.3.0.*")] // The following information is displayed by ReSharper in the Plugins dialog [assembly: PluginTitle("Reformatting Utilities")] [assembly: PluginDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: PluginVendor("Øystein Krog")]``` Fix bug in assembly file versioning ("*" was included in file version string)
```c# using System.Reflection; using JetBrains.ActionManagement; using JetBrains.Application.PluginSupport; // 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("Reformatting Utilities")] [assembly: AssemblyDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: AssemblyCompany("Øystein Krog")] [assembly: AssemblyProduct("ReformatUtils")] [assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.*")] // The following information is displayed by ReSharper in the Plugins dialog [assembly: PluginTitle("Reformatting Utilities")] [assembly: PluginDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: PluginVendor("Øystein Krog")]```
ca4ab90f-8482-4425-968e-6a1e9ede19b5
{ "language": "C#" }
```c# using System; class Protagonist { private static Protagonist INSTANCE; private static int MAX_MONEY = 99; private int balance; public int Balance { get { return balance; } } private Inventory inventory; public Inventory Inventory { get { return inventory; } } private Outfit outfit; private Protagonist() { balance = 99; outfit = new Outfit(); inventory = new Inventory(); } public static Protagonist GetInstance() { if (INSTANCE == null) { INSTANCE = new Protagonist(); } return INSTANCE; } public bool modifyBalance(int difference) { if (difference + balance < 0) { return false; } balance = Math.Min(balance + difference, MAX_MONEY); return true; } public bool CanPurchase(int price) { return (price >= 0) && balance - price >= 0; } } ``` Reset protagonist balance to 0
```c# using System; class Protagonist { private static Protagonist INSTANCE; private static int MAX_MONEY = 99; private int balance; public int Balance { get { return balance; } } private Inventory inventory; public Inventory Inventory { get { return inventory; } } private Outfit outfit; private Protagonist() { balance = 0; outfit = new Outfit(); inventory = new Inventory(); } public static Protagonist GetInstance() { if (INSTANCE == null) { INSTANCE = new Protagonist(); } return INSTANCE; } public bool modifyBalance(int difference) { if (difference + balance < 0) { return false; } balance = Math.Min(balance + difference, MAX_MONEY); return true; } public bool CanPurchase(int price) { return (price >= 0) && balance - price >= 0; } } ```
f2211e8d-97ea-49db-b7e7-650de7a23630
{ "language": "C#" }
```c# using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); authView.Initialize(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } } ``` Set window title for authentication
```c# using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { // Set window title titleContent = new GUIContent("Sign in", Styles.SmallLogo); Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); authView.Initialize(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } } ```
b5a42362-c6ce-4c8e-90e9-ce6e9d2557de
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace twitch_tv_viewer.Models { public class TwitchChannel : IComparable { public TwitchChannel() { } public TwitchChannel(JToken data) { var channel = data["channel"]; Name = channel["display_name"]?.ToString() ?? "no name"; Game = channel["game"]?.ToString() ?? "no game"; Status = channel["status"]?.ToString().Trim() ?? "no status"; Viewers = data["viewers"]?.ToString() ?? "???"; } public string Name { get; set; } public string Game { get; set; } public string Status { get; set; } public string Viewers { get; set; } public int CompareTo(object obj) { var that = obj as TwitchChannel; if (that == null) return 0; return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal); } public async Task<string> StartStream() { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{Name} high", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public void OpenChatroom() => Process.Start($"http://twitch.tv/{Name}/chat?popout="); } }``` Remove unneeded methods from model
```c# using System; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace twitch_tv_viewer.Models { public class TwitchChannel : IComparable { public TwitchChannel() { } public TwitchChannel(JToken data) { var channel = data["channel"]; Name = channel["display_name"]?.ToString() ?? "no name"; Game = channel["game"]?.ToString() ?? "no game"; Status = channel["status"]?.ToString().Trim() ?? "no status"; Viewers = data["viewers"]?.ToString() ?? "???"; } public string Name { get; set; } public string Game { get; set; } public string Status { get; set; } public string Viewers { get; set; } public int CompareTo(object obj) { var that = obj as TwitchChannel; if (that == null) return 0; return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal); } } }```
f04b5ec3-30dd-4c64-bf77-5d16a9f21fd4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Game; using GnomeServer.Extensions; using GnomeServer.Routing; namespace GnomeServer.Controllers { [Route("Game")] public sealed class GameController : ConventionRoutingController { [HttpGet] [Route("")] public IResponseFormatter Get(int speed) { GnomanEmpire.Instance.World.GameSpeed.Value = speed; String content = String.Format("Game Speed set to '{0}'", speed); return JsonResponse(content); } public IResponseFormatter Test() { BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; var fields = typeof(Character).GetFields(bindFlags); var behaviorTypeFields = fields.Where(obj => obj.FieldType == typeof(BehaviorType)).ToList(); List<TestResponse> testResponses = new List<TestResponse>(); var members = GnomanEmpire.Instance.GetGnomes(); foreach (var characterKey in members) { var character = characterKey.Value; var name = character.NameAndTitle(); foreach (var fieldInfo in behaviorTypeFields) { var val = (BehaviorType)(fieldInfo.GetValue(character)); testResponses.Add(new TestResponse { Name = name, Value = val.ToString(), }); } } return JsonResponse(testResponses); } private class TestResponse { public String Name { get; set; } public String Value { get; set; } } } } ``` Add endpoints for controlling game speed.
```c# using System.Globalization; using System.Net; using Game; using GnomeServer.Routing; namespace GnomeServer.Controllers { [Route("Game")] public sealed class GameController : ConventionRoutingController { [HttpGet] [Route("Speed")] public IResponseFormatter GetSpeed() { var world = GnomanEmpire.Instance.World; var speed = new { Speed = world.GameSpeed.Value.ToString(CultureInfo.InvariantCulture), IsPaused = world.Paused.Value.ToString(CultureInfo.InvariantCulture) }; return JsonResponse(speed); } [HttpPost] [Route("Speed")] public IResponseFormatter PostSpeed(int speed) { GnomanEmpire.Instance.World.GameSpeed.Value = speed; return BlankResponse(HttpStatusCode.NoContent); } [HttpPost] [Route("Pause")] public IResponseFormatter PostPause() { GnomanEmpire.Instance.World.Paused.Value = true; return BlankResponse(HttpStatusCode.NoContent); } [HttpPost] [Route("Play")] public IResponseFormatter PostPlay() { GnomanEmpire.Instance.World.Paused.Value = false; return BlankResponse(HttpStatusCode.NoContent); } } } ```
e3a5450c-d365-45c0-b78f-3f5cd5856b1a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Aspose.Cells.Examples.CSharp.Articles { public class LoadWorkbookWithSpecificCultureInfoNumberFormat { public static void Run() { // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat using (var inputStream = new MemoryStream()) { using (var writer = new StreamWriter(inputStream)) { writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>"); writer.Flush(); var culture = new CultureInfo("en-GB"); culture.NumberFormat.NumberDecimalSeparator = ","; culture.DateTimeFormat.DateSeparator = "-"; culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; LoadOptions options = new LoadOptions(LoadFormat.Html); options.CultureInfo = culture; using (var workbook = new Workbook(inputStream, options)) { var cell = workbook.Worksheets[0].Cells["A1"]; Assert.AreEqual(CellValueType.IsNumeric, cell.Type); Assert.AreEqual(1234.56, cell.DoubleValue); } } } // ExEnd:LoadWorkbookWithSpecificCultureInfo } } } ``` Correct the Example Name in Comment
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Aspose.Cells.Examples.CSharp.Articles { public class LoadWorkbookWithSpecificCultureInfoNumberFormat { public static void Run() { // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat using (var inputStream = new MemoryStream()) { using (var writer = new StreamWriter(inputStream)) { writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>"); writer.Flush(); var culture = new CultureInfo("en-GB"); culture.NumberFormat.NumberDecimalSeparator = ","; culture.DateTimeFormat.DateSeparator = "-"; culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; LoadOptions options = new LoadOptions(LoadFormat.Html); options.CultureInfo = culture; using (var workbook = new Workbook(inputStream, options)) { var cell = workbook.Worksheets[0].Cells["A1"]; Assert.AreEqual(CellValueType.IsNumeric, cell.Type); Assert.AreEqual(1234.56, cell.DoubleValue); } } } // ExEnd:LoadWorkbookWithSpecificCultureInfoNumberFormat } } } ```
a57da5d9-70ad-4166-8a77-c716f5d5cc05
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using OpenTK.Graphics; namespace osu.Game.Graphics.Backgrounds { public class Background : BufferedContainer { public Sprite Sprite; private readonly string textureName; public Background(string textureName = @"") { CacheDrawnFrameBuffer = true; this.textureName = textureName; RelativeSizeAxes = Axes.Both; Add(Sprite = new Sprite { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.DarkGray, FillMode = FillMode.Fill, }); } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { if (!string.IsNullOrEmpty(textureName)) Sprite.Texture = textures.Get(textureName); } } } ``` Fix background brightness being adjusted globally
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Graphics.Backgrounds { public class Background : BufferedContainer { public Sprite Sprite; private readonly string textureName; public Background(string textureName = @"") { CacheDrawnFrameBuffer = true; this.textureName = textureName; RelativeSizeAxes = Axes.Both; Add(Sprite = new Sprite { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, }); } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { if (!string.IsNullOrEmpty(textureName)) Sprite.Texture = textures.Get(textureName); } } } ```
25bae73e-7190-445c-a9f5-d7cbeb0dc23d
{ "language": "C#" }
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { public class ACFTController : Controller { private readonly Database db; public ACFTController(Database db) { this.db = db; } public async Task<IActionResult> Index() { return Content("Coming soon!"); } } } ``` Drop in other CRUD methods
```c# using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { public class ACFTController : Controller { private readonly Database db; public ACFTController(Database db) { this.db = db; } public async Task<IActionResult> Index() { return Content("Coming soon!"); } public async Task<IActionResult> Details(int id) { return View(await Get(db, id)); } public async Task<IActionResult> New(int soldier = 0) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View(nameof(Edit), new APFT { SoldierId = soldier }); } public async Task<IActionResult> Edit(int id) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View(await Get(db, id)); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Save(ACFT model) { if (!ModelState.IsValid) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View("Edit", model); } if (await db.ACFTs.AnyAsync(apft => apft.Id == model.Id) == false) { db.ACFTs.Add(model); } else { db.ACFTs.Update(model); } await db.SaveChangesAsync(); return RedirectToAction(nameof(Details), new { model.Id }); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Delete(int id) { var test = await Get(db, id); db.ACFTs.Remove(test); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public static async Task<ACFT> Get(Database db, int id) { return await db .ACFTs .Include(_ => _.Soldier) .ThenInclude(_ => _.Unit) .Where(_ => _.Id == id) .SingleOrDefaultAsync(); } } } ```
043ff96e-cded-4492-8417-01bbf88295f1
{ "language": "C#" }
```c# using System; using System.Linq; using Newtonsoft.Json; namespace Exceptional.Core { public class ExceptionSummary { [JsonProperty(PropertyName = "occurred_at")] public DateTime OccurredAt { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "backtrace")] public string[] Backtrace { get; set; } [JsonProperty(PropertyName = "exception_class")] public string ExceptionClass { get; set; } public ExceptionSummary() { OccurredAt = DateTime.UtcNow; } public static ExceptionSummary CreateFromException(Exception ex) { var summary = new ExceptionSummary(); summary.Message = ex.Message; summary.Backtrace = ex.StackTrace.Split('\r', '\n').Select(line => line.Trim()).ToArray(); summary.ExceptionClass = ex.GetType().Name; return summary; } } }``` Use 'o' format for date. Fixed splitting problem with backtrace.
```c# using System; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace Exceptional.Core { public class ExceptionSummary { [JsonProperty(PropertyName = "occurred_at")] public string OccurredAt { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "backtrace")] public string[] Backtrace { get; set; } [JsonProperty(PropertyName = "exception_class")] public string ExceptionClass { get; set; } public ExceptionSummary() { OccurredAt = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); } public static ExceptionSummary CreateFromException(Exception ex) { var summary = new ExceptionSummary(); summary.Message = ex.Message; summary.Backtrace = ex.StackTrace.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries).Select(line => line.Trim()).ToArray(); summary.ExceptionClass = ex.GetType().Name; return summary; } } }```
d900436f-74c5-4f7c-9c9c-2439dbdd3116
{ "language": "C#" }
```c# using System; using System.Web.Routing; using MvcContrib.TestHelper; using SnittListan.Controllers; using Xunit; namespace SnittListan.Test { public class RoutesTest : IDisposable { public RoutesTest() { new RouteConfigurator(RouteTable.Routes).Configure(); } public void Dispose() { RouteTable.Routes.Clear(); } [Fact] public void DefaultRoute() { "~/".ShouldMapTo<HomeController>(c => c.Index()); } [Fact] public void LowerCaseRoutes() { "~/account/register".ShouldMapTo<AccountController>(c => c.Register()); } [Fact] public void Shortcuts() { "~/register".ShouldMapTo<AccountController>(c => c.Register()); "~/logon".ShouldMapTo<AccountController>(c => c.LogOn()); "~/about".ShouldMapTo<HomeController>(c => c.About()); } } } ``` Verify should accept a guid activationKey
```c# using System; using System.Web.Routing; using MvcContrib.TestHelper; using SnittListan.Controllers; using Xunit; using System.Web.Mvc; namespace SnittListan.Test { public class RoutesTest : IDisposable { public RoutesTest() { new RouteConfigurator(RouteTable.Routes).Configure(); } public void Dispose() { RouteTable.Routes.Clear(); } [Fact] public void DefaultRoute() { "~/".ShouldMapTo<HomeController>(c => c.Index()); } [Fact] public void LowerCaseRoutes() { "~/account/register".ShouldMapTo<AccountController>(c => c.Register()); } [Fact] public void Shortcuts() { "~/register".ShouldMapTo<AccountController>(c => c.Register()); "~/logon".ShouldMapTo<AccountController>(c => c.LogOn()); "~/about".ShouldMapTo<HomeController>(c => c.About()); } [Fact] public void Verify() { var verify = "~/verify".WithMethod(HttpVerbs.Post); var guid = Guid.NewGuid(); verify.Values["activationKey"] = guid.ToString(); verify.ShouldMapTo<AccountController>(c => c.Verify(guid)); } } } ```
79f2be60-0ba5-4192-a8a2-2e8c052c0201
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. // Licensed under the MIT License using Microsoft.MixedReality.Toolkit.UI.Interaction; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Custom inspector for an InteractiveElement. /// </summary> [CustomEditor(typeof(InteractiveElement))] public class InteractiveElementInspector : BaseInteractiveElementInspector { protected override void OnEnable() { base.OnEnable(); } public override void OnInspectorGUI() { // Interactive Element is a place holder class base.OnInspectorGUI(); } } } ``` Remove override methods from Interactive Element Inspector
```c# // Copyright (c) Microsoft Corporation. // Licensed under the MIT License using Microsoft.MixedReality.Toolkit.UI.Interaction; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Custom inspector for an InteractiveElement. /// </summary> [CustomEditor(typeof(InteractiveElement))] public class InteractiveElementInspector : BaseInteractiveElementInspector { // Interactive Element is a place holder class } } ```
e1e69e1f-c059-473a-8193-682266a51ef3
{ "language": "C#" }
```c# using System.IO; using NClap.ConsoleInput; using NClap.Utilities; namespace NClap.Repl { /// <summary> /// Parameters for constructing a loop with advanced line input. The /// parameters indicate how the loop's textual input and output should /// be implemented. /// </summary> public class LoopInputOutputParameters { /// <summary> /// Writer to use for error output. /// </summary> public TextWriter ErrorWriter { get; set; } /// <summary> /// Line input object to use. /// </summary> public IConsoleLineInput LineInput { get; set; } /// <summary> /// The console input interface to use. /// </summary> public IConsoleInput ConsoleInput { get; set; } /// <summary> /// The console output interface to use. /// </summary> public IConsoleOutput ConsoleOutput { get; set; } /// <summary> /// Input prompt. /// </summary> public ColoredString Prompt { get; set; } } } ``` Add key binding set to loop i/o params
```c# using System.IO; using NClap.ConsoleInput; using NClap.Utilities; namespace NClap.Repl { /// <summary> /// Parameters for constructing a loop with advanced line input. The /// parameters indicate how the loop's textual input and output should /// be implemented. /// </summary> public class LoopInputOutputParameters { /// <summary> /// Optionally provides a writer to use for error output. /// </summary> public TextWriter ErrorWriter { get; set; } /// <summary> /// Line input object to use, or null for a default one to be /// constructed. /// </summary> public IConsoleLineInput LineInput { get; set; } /// <summary> /// The console input interface to use, or null to use the default one. /// </summary> public IConsoleInput ConsoleInput { get; set; } /// <summary> /// The console output interface to use, or null to use the default one. /// </summary> public IConsoleOutput ConsoleOutput { get; set; } /// <summary> /// The console key binding set to use, or null to use the default one. /// </summary> public IReadOnlyConsoleKeyBindingSet KeyBindingSet { get; set; } /// <summary> /// Input prompt, or null to use the default one. /// </summary> public ColoredString Prompt { get; set; } } } ```
ffd53b8b-97b6-4452-b835-a048f9ea0120
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)] public partial class Bugzilla51642 : ContentPage { public Bugzilla51642 () { InitializeComponent (); LoadDelayedVM(); BoundPicker.SelectedIndexChanged += (s, e) => { SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString(); }; } public async void LoadDelayedVM() { await Task.Delay(1000); Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM()); } } [Preserve(AllMembers=true)] class Bz51642VM { public IList<string> Items { get { return new List<String> { "Foo", "Bar", "Baz" }; } } } } ``` Fix build of test case
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)] public partial class Bugzilla51642 : ContentPage { #if APP public Bugzilla51642 () { InitializeComponent (); LoadDelayedVM(); BoundPicker.SelectedIndexChanged += (s, e) => { SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString(); }; } public async void LoadDelayedVM() { await Task.Delay(1000); Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM()); } #endif } [Preserve(AllMembers=true)] class Bz51642VM { public IList<string> Items { get { return new List<String> { "Foo", "Bar", "Baz" }; } } } } ```
7a75fe0b-6b3f-4c8f-9228-2b8211b80cc4
{ "language": "C#" }
```c# // Copyright 2017 Daniel Plemmons // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasicStageManagable : StageManagable{ private bool hasInitialized = false; protected virtual void Awake() { Initialize(); } protected virtual void Initialize() { if(hasInitialized) { return; } hasInitialized = true; gameObject.SetActive(false); } public override void Enter() { Initialize(); StartEnter(); gameObject.SetActive(true); CompleteEnter(); } public override void Exit() { Initialize(); StartExit(); gameObject.SetActive(false); CompleteExit(); } } ``` Remove some unused using statements
```c# // Copyright 2017 Daniel Plemmons // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. public class BasicStageManagable : StageManagable{ private bool hasInitialized = false; protected virtual void Awake() { Initialize(); } protected virtual void Initialize() { if(hasInitialized) { return; } hasInitialized = true; gameObject.SetActive(false); } public override void Enter() { Initialize(); StartEnter(); gameObject.SetActive(true); CompleteEnter(); } public override void Exit() { Initialize(); StartExit(); gameObject.SetActive(false); CompleteExit(); } } ```
9e1c261e-999e-458e-93ab-6ce804f12ea6
{ "language": "C#" }
```c# using System; using System.Linq; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace SQLite.Tests { [TestFixture] public class ScalarTest { class TestTable { [PrimaryKey, AutoIncrement] public int Id { get; set; } public int Two { get; set; } } const int Count = 100; SQLiteConnection CreateDb () { var db = new TestDb (); db.CreateTable<TestTable> (); var items = from i in Enumerable.Range (0, Count) select new TestTable { Two = 2 }; db.InsertAll (items); Assert.AreEqual (Count, db.Table<TestTable> ().Count ()); return db; } [Test] public void Int32 () { var db = CreateDb (); var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable"); Assert.AreEqual (Count * 2, r); } } } ``` Add test for scalar queries with 1 row
```c# using System; using System.Linq; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace SQLite.Tests { [TestFixture] public class ScalarTest { class TestTable { [PrimaryKey, AutoIncrement] public int Id { get; set; } public int Two { get; set; } } const int Count = 100; SQLiteConnection CreateDb () { var db = new TestDb (); db.CreateTable<TestTable> (); var items = from i in Enumerable.Range (0, Count) select new TestTable { Two = 2 }; db.InsertAll (items); Assert.AreEqual (Count, db.Table<TestTable> ().Count ()); return db; } [Test] public void Int32 () { var db = CreateDb (); var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable"); Assert.AreEqual (Count * 2, r); } [Test] public void SelectSingleRowValue () { var db = CreateDb (); var r = db.ExecuteScalar<int> ("SELECT Two FROM TestTable WHERE Id = 1 LIMIT 1"); Assert.AreEqual (2, r); } } } ```
a4dd7a44-dc64-474c-92e1-4a4a0da892d7
{ "language": "C#" }
```c# 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("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.5")] [assembly: AssemblyFileVersion("1.0.0.5")] ``` Increment version number to sync up with NuGet
```c# 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("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.5")] [assembly: AssemblyFileVersion("1.0.0.6")] ```
ea33c9bb-4ea3-4b8b-b4f5-c28bfd5b3016
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing { public class FishingSpotFlavor { public Coordinates Scan1 { get; } public Coordinates Scan2 { get; } public ScreenshotColor BubbleColor { get; } public int Tolerance { get; } public FishingSpotFlavor(Coordinates scan1, Coordinates scan2, ScreenshotColor bubbleColor, int tolerance) { this.Scan1 = scan1; this.Scan2 = scan2; this.BubbleColor = bubbleColor; this.Tolerance = tolerance; } // TODO: The Color value needs some adjustment! public static readonly FishingSpotFlavor PunchlinePlace = new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626), new ScreenshotColor(24, 142, 118), 16); } } ``` Adjust the values for the Punchline Place fishing spot.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TTMouseclickSimulator.Core.Environment; namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing { public class FishingSpotFlavor { public Coordinates Scan1 { get; } public Coordinates Scan2 { get; } public ScreenshotColor BubbleColor { get; } public int Tolerance { get; } public FishingSpotFlavor(Coordinates scan1, Coordinates scan2, ScreenshotColor bubbleColor, int tolerance) { this.Scan1 = scan1; this.Scan2 = scan2; this.BubbleColor = bubbleColor; this.Tolerance = tolerance; } // TODO: The Color value needs some adjustment! public static readonly FishingSpotFlavor PunchlinePlace = new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626), new ScreenshotColor(22, 140, 116), 13); } } ```
5395484a-b7f7-4734-b370-1205dcdcc2b6
{ "language": "C#" }
```c# namespace Foo.Tests.Web.Controllers { public class HomeControllerTest { } } ``` Initialize new home controller instance for test class
```c# using Foo.Web.Controllers; namespace Foo.Tests.Web.Controllers { public class HomeControllerTest { private readonly HomeController _controller; public HomeControllerTest() { _controller = new HomeController(); } } } ```
1072b0de-dba7-4e41-9d58-669ffc49c173
{ "language": "C#" }
```c# using Glimpse.Web; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Reflection; using System.Text; using Glimpse.Server.Web; namespace Glimpse.Agent.Browser.Resources { public class BrowserAgent : IMiddlewareResourceComposer { public void Register(IApplicationBuilder appBuilder) { appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context => { var response = context.Response; response.Headers.Set("Content-Type", "application/javascript"); var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly; var jqueryStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/jquery.jquery-2.1.1.js"); var signalrStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/signalr/jquery.signalR-2.2.0.js"); var agentStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/BrowserAgent.js"); using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8)) using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8)) using (var agentReader = new StreamReader(agentStream, Encoding.UTF8)) { // TODO: The worlds worst hack!!! Nik did this... await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd()); } })); } } }``` Update find resource code post internal change
```c# using Glimpse.Web; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System.IO; using System.Reflection; using System.Text; using Glimpse.Server.Web; namespace Glimpse.Agent.Browser.Resources { public class BrowserAgent : IMiddlewareResourceComposer { public void Register(IApplicationBuilder appBuilder) { appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context => { var response = context.Response; response.Headers.Set("Content-Type", "application/javascript"); var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly; var jqueryStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.jquery.jquery-2.1.1.js"); var signalrStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.signalr.jquery.signalR-2.2.0.js"); var agentStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.BrowserAgent.js"); using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8)) using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8)) using (var agentReader = new StreamReader(agentStream, Encoding.UTF8)) { // TODO: The worlds worst hack!!! Nik did this... await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd()); } })); } } }```
5dc4ca59-7f39-40b8-a074-bbaf5641d126
{ "language": "C#" }
```c# @{ Layout = "master.cshtml"; } <div class="admin-container"> <div class="admin-form-view"> <form role="form" method="POST" target="/"> <div class="form-group well"> <label for="key">Key</label> <input type="password" class="form-control" id="key" name="key" placeholder="key"> </div> <div class="well"> <div class="form-group"> <label for="username">Username</label> <input class="form-control" id="username" name="username" placeholder="username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="password" placeholder="password"> </div> </div> <button class="btn btn-danger btn-lg pull-right" type="submit">Install</button> </form> </div> </div>``` Fix target in installer form
```c# @{ Layout = "master.cshtml"; } <div class="admin-container"> <div class="admin-form-view"> <form role="form" method="POST"> <div class="form-group well"> <label for="key">Key</label> <input type="password" class="form-control" id="key" name="key" placeholder="key"> </div> <div class="well"> <div class="form-group"> <label for="username">Username</label> <input class="form-control" id="username" name="username" placeholder="username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="password" placeholder="password"> </div> </div> <button class="btn btn-danger btn-lg pull-right" type="submit">Install</button> </form> </div> </div>```
2400ebe7-737f-4718-9f63-60e36a0f65fb
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Management.Automation.Runspaces; using Aggregator.Core.Interfaces; using Aggregator.Core.Monitoring; namespace Aggregator.Core { /// <summary> /// Invokes Powershell scripting engine /// </summary> public class PsScriptEngine : ScriptEngine { private readonly Dictionary<string, string> scripts = new Dictionary<string, string>(); public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug) : base(store, logger, debug) { } public override bool Load(string scriptName, string script) { this.scripts.Add(scriptName, script); return true; } public override bool LoadCompleted() { return true; } public override void Run(string scriptName, IWorkItem workItem) { string script = this.scripts[scriptName]; var config = RunspaceConfiguration.Create(); using (var runspace = RunspaceFactory.CreateRunspace(config)) { runspace.Open(); runspace.SessionStateProxy.SetVariable("self", workItem); runspace.SessionStateProxy.SetVariable("store", this.Store); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); // execute var results = pipeline.Invoke(); this.Logger.ResultsFromScriptRun(scriptName, results); } } } } ``` FIX logger variable in PS scripts
```c# using System.Collections.Generic; using System.Management.Automation.Runspaces; using Aggregator.Core.Interfaces; using Aggregator.Core.Monitoring; namespace Aggregator.Core { /// <summary> /// Invokes Powershell scripting engine /// </summary> public class PsScriptEngine : ScriptEngine { private readonly Dictionary<string, string> scripts = new Dictionary<string, string>(); public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug) : base(store, logger, debug) { } public override bool Load(string scriptName, string script) { this.scripts.Add(scriptName, script); return true; } public override bool LoadCompleted() { return true; } public override void Run(string scriptName, IWorkItem workItem) { string script = this.scripts[scriptName]; var config = RunspaceConfiguration.Create(); using (var runspace = RunspaceFactory.CreateRunspace(config)) { runspace.Open(); runspace.SessionStateProxy.SetVariable("self", workItem); runspace.SessionStateProxy.SetVariable("store", this.Store); runspace.SessionStateProxy.SetVariable("logger", this.Logger); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); // execute var results = pipeline.Invoke(); this.Logger.ResultsFromScriptRun(scriptName, results); } } } } ```
1da5cdb1-7585-46ea-ac3b-8f8443c2a153
{ "language": "C#" }
```c# #region using System; using System.ComponentModel; using System.Windows; using System.Windows.Interop; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class SwitchWindow : Window { public SwitchWindow() { InitializeComponent(); ReloadAccountListBinding(); } public void ReloadAccountListBinding() { AccountView.DataContext = null; AccountView.DataContext = App.Accounts; } private void Window_Closing(object sender, CancelEventArgs e) { if (App.IsShuttingDown) return; if (Settings.Default.AlwaysOn) { e.Cancel = true; HideWindow(); return; } AppHelper.ShutdownApplication(); } public void HideWindow() { var visible = Visibility == Visibility.Visible; Hide(); if (visible && Settings.Default.AlwaysOn) TrayIconHelper.ShowRunningInTrayBalloon(); } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var mainWindowPtr = new WindowInteropHelper(this).Handle; var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr); mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc); } } }``` Fix "Keep Window Centered" option
```c# #region using System; using System.ComponentModel; using System.Windows; using System.Windows.Interop; using SteamAccountSwitcher.Properties; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class SwitchWindow : Window { public SwitchWindow() { InitializeComponent(); WindowStartupLocation = Settings.Default.SwitchWindowKeepCentered ? WindowStartupLocation.CenterScreen : WindowStartupLocation.Manual; ReloadAccountListBinding(); } public void ReloadAccountListBinding() { AccountView.DataContext = null; AccountView.DataContext = App.Accounts; } private void Window_Closing(object sender, CancelEventArgs e) { if (App.IsShuttingDown) return; if (Settings.Default.AlwaysOn) { e.Cancel = true; HideWindow(); return; } AppHelper.ShutdownApplication(); } public void HideWindow() { var visible = Visibility == Visibility.Visible; Hide(); if (visible && Settings.Default.AlwaysOn) TrayIconHelper.ShowRunningInTrayBalloon(); } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var mainWindowPtr = new WindowInteropHelper(this).Handle; var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr); mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc); } } }```
02e675b2-6113-4386-8368-9d2362116680
{ "language": "C#" }
```c# using System; using System.Windows.Forms; using GUI.Utils; namespace GUI.Forms { public partial class SettingsForm : Form { public SettingsForm() { InitializeComponent(); } private void SettingsForm_Load(object sender, EventArgs e) { foreach (var path in Settings.GameSearchPaths) { gamePaths.Items.Add(path); } } private void GamePathRemoveClick(object sender, EventArgs e) { if (gamePaths.SelectedIndex < 0) { return; } Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem); Settings.Save(); gamePaths.Items.RemoveAt(gamePaths.SelectedIndex); } private void GamePathAdd(object sender, EventArgs e) { using (var dlg = new FolderBrowserDialog()) { dlg.Description = "Select a folder"; if (dlg.ShowDialog() != DialogResult.OK) { return; } if (Settings.GameSearchPaths.Contains(dlg.SelectedPath)) { return; } Settings.GameSearchPaths.Add(dlg.SelectedPath); Settings.Save(); gamePaths.Items.Add(dlg.SelectedPath); } } private void button1_Click(object sender, EventArgs e) { var colorPicker = new ColorDialog(); colorPicker.Color = Settings.BackgroundColor; // Update the text box color if the user clicks OK if (colorPicker.ShowDialog() == DialogResult.OK) { Settings.BackgroundColor = colorPicker.Color; } } } } ``` Allow selecting vpks in content search paths
```c# using System; using System.Windows.Forms; using GUI.Utils; namespace GUI.Forms { public partial class SettingsForm : Form { public SettingsForm() { InitializeComponent(); } private void SettingsForm_Load(object sender, EventArgs e) { foreach (var path in Settings.GameSearchPaths) { gamePaths.Items.Add(path); } } private void GamePathRemoveClick(object sender, EventArgs e) { if (gamePaths.SelectedIndex < 0) { return; } Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem); Settings.Save(); gamePaths.Items.RemoveAt(gamePaths.SelectedIndex); } private void GamePathAdd(object sender, EventArgs e) { using (var dlg = new OpenFileDialog()) { dlg.Filter = "Valve Pak (*.vpk)|*.vpk|All files (*.*)|*.*"; if (dlg.ShowDialog() != DialogResult.OK) { return; } if (Settings.GameSearchPaths.Contains(dlg.FileName)) { return; } Settings.GameSearchPaths.Add(dlg.FileName); Settings.Save(); gamePaths.Items.Add(dlg.FileName); } } private void button1_Click(object sender, EventArgs e) { var colorPicker = new ColorDialog(); colorPicker.Color = Settings.BackgroundColor; // Update the text box color if the user clicks OK if (colorPicker.ShowDialog() == DialogResult.OK) { Settings.BackgroundColor = colorPicker.Color; } } } } ```
4c65d8fd-424a-4e1b-9c18-5eb19462e4d4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Umbraco.Core.IO; using umbraco.businesslogic; using umbraco.interfaces; namespace umbraco.presentation { public class EnsureSystemPathsApplicationStartupHandler : IApplicationStartupHandler { public EnsureSystemPathsApplicationStartupHandler() { EnsurePathExists(SystemDirectories.Css); EnsurePathExists(SystemDirectories.Data); EnsurePathExists(SystemDirectories.MacroScripts); EnsurePathExists(SystemDirectories.Masterpages); EnsurePathExists(SystemDirectories.Media); EnsurePathExists(SystemDirectories.Scripts); EnsurePathExists(SystemDirectories.UserControls); EnsurePathExists(SystemDirectories.Xslt); EnsurePathExists(SystemDirectories.MvcViews); EnsurePathExists(SystemDirectories.MvcViews + "/Partials"); EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials"); } public void EnsurePathExists(string path) { var absolutePath = IOHelper.MapPath(path); if (!Directory.Exists(absolutePath)) Directory.CreateDirectory(absolutePath); } } }``` Add App_Code, App_Data and App_Plugins folders to be created during app startup
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Umbraco.Core.IO; using umbraco.businesslogic; using umbraco.interfaces; namespace umbraco.presentation { public class EnsureSystemPathsApplicationStartupHandler : IApplicationStartupHandler { public EnsureSystemPathsApplicationStartupHandler() { EnsurePathExists("~/App_Code"); EnsurePathExists("~/App_Data"); EnsurePathExists(SystemDirectories.AppPlugins); EnsurePathExists(SystemDirectories.Css); EnsurePathExists(SystemDirectories.MacroScripts); EnsurePathExists(SystemDirectories.Masterpages); EnsurePathExists(SystemDirectories.Media); EnsurePathExists(SystemDirectories.Scripts); EnsurePathExists(SystemDirectories.UserControls); EnsurePathExists(SystemDirectories.Xslt); EnsurePathExists(SystemDirectories.MvcViews); EnsurePathExists(SystemDirectories.MvcViews + "/Partials"); EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials"); } public void EnsurePathExists(string path) { var absolutePath = IOHelper.MapPath(path); if (!Directory.Exists(absolutePath)) Directory.CreateDirectory(absolutePath); } } }```
3570e896-8ad2-469b-8822-5cc5b81c0030
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ooui; namespace Tests { [TestClass] public class CanvasTests { [TestMethod] public void Context2dState () { var c = new Canvas (); Assert.AreEqual (1, c.StateMessages.Count); var c2d = c.GetContext2d (); Assert.AreEqual (2, c.StateMessages.Count); var c2d2 = c.GetContext2d (); Assert.AreEqual (2, c.StateMessages.Count); Assert.AreEqual (c2d, c2d2); } [TestMethod] public void DefaultWidthAndHeight () { var c = new Canvas (); Assert.AreEqual (150, c.Width); Assert.AreEqual (150, c.Height); } [TestMethod] public void WidthAndHeight () { var c = new Canvas { Width = 640, Height = 480, }; Assert.AreEqual (640, c.Width); Assert.AreEqual (480, c.Height); } [TestMethod] public void CantBeNegativeOrZero () { var c = new Canvas { Width = 640, Height = 480, }; Assert.AreEqual (640, c.Width); Assert.AreEqual (480, c.Height); c.Width = 0; c.Height = 0; Assert.AreEqual (150, c.Width); Assert.AreEqual (150, c.Height); } } } ``` Fix Canvas negative Height test
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ooui; namespace Tests { [TestClass] public class CanvasTests { [TestMethod] public void Context2dState () { var c = new Canvas (); Assert.AreEqual (1, c.StateMessages.Count); var c2d = c.GetContext2d (); Assert.AreEqual (2, c.StateMessages.Count); var c2d2 = c.GetContext2d (); Assert.AreEqual (2, c.StateMessages.Count); Assert.AreEqual (c2d, c2d2); } [TestMethod] public void DefaultWidthAndHeight () { var c = new Canvas (); Assert.AreEqual (150, c.Width); Assert.AreEqual (150, c.Height); } [TestMethod] public void WidthAndHeight () { var c = new Canvas { Width = 640, Height = 480, }; Assert.AreEqual (640, c.Width); Assert.AreEqual (480, c.Height); } [TestMethod] public void CantBeNegativeOrZero () { var c = new Canvas { Width = 640, Height = 480, }; Assert.AreEqual (640, c.Width); Assert.AreEqual (480, c.Height); c.Width = 0; c.Height = -100; Assert.AreEqual (150, c.Width); Assert.AreEqual (150, c.Height); } } } ```
61131f1a-4858-46b6-8622-e2fd1a78b98a
{ "language": "C#" }
```c# namespace RollGen { public abstract class Dice { public abstract PartialRoll Roll(int quantity = 1); public abstract string RolledString(string roll); public abstract object CompiledObj(string rolled); public int Compiled(string rolled) => System.Convert.ToInt32(CompiledObj(rolled)); public int Roll(string roll) => Compiled(RolledString(roll)); } }``` Add T Compiled<T> to complement int Compiled
```c# namespace RollGen { public abstract class Dice { public abstract PartialRoll Roll(int quantity = 1); public abstract string RolledString(string roll); public abstract object CompiledObj(string rolled); public int Compiled(string rolled) => System.Convert.ToInt32(CompiledObj(rolled)); public T Compiled<T>(string rolled) => (T)System.Convert.ChangeType(CompiledObj(rolled), typeof(T)); public int Roll(string roll) => Compiled(RolledString(roll)); } }```
36800ef2-f33e-4493-8077-ce1c8d89e994
{ "language": "C#" }
```c# using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { var extractor = new Middleware.ZipkinHttpTraceExtractor(); app.Use(async (context, next) => { Trace trace; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; trace.Record(Annotations.ServerRecv()); trace.Record(Annotations.ServiceName(serviceName)); trace.Record(Annotations.Rpc(context.Request.Method)); await next.Invoke(); trace.Record(Annotations.ServerSend()); }); } } }``` Add exception handling in middleware
```c# using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { var extractor = new Middleware.ZipkinHttpTraceExtractor(); app.Use(async (context, next) => { Trace trace; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; trace.Record(Annotations.ServerRecv()); trace.Record(Annotations.ServiceName(serviceName)); trace.Record(Annotations.Rpc(context.Request.Method)); try { await next.Invoke(); } catch (System.Exception e) { trace.Record(Annotations.Tag("error", e.Message)); throw; } finally { trace.Record(Annotations.ServerSend()); } }); } } }```
ec58cbd0-1cfa-433d-a830-bdc67251406b
{ "language": "C#" }
```c# using UnityEngine; using UnityEditor; using System.IO; namespace ATP.AnimationPathTools { public static class ScriptableObjectUtility { /// <summary> // This makes it easy to create, name and place unique new ScriptableObject asset files. /// </summary> public static void CreateAsset<T> () where T : ScriptableObject { T asset = ScriptableObject.CreateInstance<T> (); string path = AssetDatabase.GetAssetPath (Selection.activeObject); if (path == "") { path = "Assets"; } else if (Path.GetExtension (path) != "") { path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), ""); } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + typeof(T).ToString() + ".asset"); AssetDatabase.CreateAsset (asset, assetPathAndName); AssetDatabase.SaveAssets (); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow (); Selection.activeObject = asset; } } }``` Remove "New" string from asset name
```c# using UnityEngine; using UnityEditor; using System.IO; namespace ATP.AnimationPathTools { public static class ScriptableObjectUtility { /// <summary> // This makes it easy to create, name and place unique new ScriptableObject asset files. /// </summary> public static void CreateAsset<T> () where T : ScriptableObject { T asset = ScriptableObject.CreateInstance<T> (); string path = AssetDatabase.GetAssetPath (Selection.activeObject); if (path == "") { path = "Assets"; } else if (Path.GetExtension (path) != "") { path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), ""); } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/" + typeof(T).ToString() + ".asset"); AssetDatabase.CreateAsset (asset, assetPathAndName); AssetDatabase.SaveAssets (); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow (); Selection.activeObject = asset; } } }```
ff30dd6e-2c0f-4c70-9c64-36f4f2a4d62a
{ "language": "C#" }
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { Tensor<double> result = new Tensor<double>(); result.SetValue(tensor1.GetValue() - tensor2.GetValue()); return result; } } } ``` Refactor Subtract Doubles Operation to use GetValues and CloneWithValues
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { double[] values1 = tensor1.GetValues(); int l = values1.Length; double[] values2 = tensor2.GetValues(); double[] newvalues = new double[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] - values2[k]; return tensor1.CloneWithNewValues(newvalues); } } } ```
3f163e14-823f-4f71-8a24-c876d6b7c95b
{ "language": "C#" }
```c# // Copyright (C) 2020 Fievus // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Reflection; using System.Runtime.Loader; namespace Carna.ConsoleRunner { internal class CarnaAssemblyLoadContext : AssemblyLoadContext { private readonly AssemblyDependencyResolver assemblyDependencyResolver; public CarnaAssemblyLoadContext(string assemblyPath) { assemblyDependencyResolver = new AssemblyDependencyResolver(assemblyPath); } protected override Assembly Load(AssemblyName assemblyName) { var assemblyPath = assemblyDependencyResolver.ResolveAssemblyToPath(assemblyName); return assemblyPath == null ? null : LoadFromAssemblyPath(assemblyPath); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var unmanagedDllPath = assemblyDependencyResolver.ResolveUnmanagedDllToPath(unmanagedDllName); return unmanagedDllPath == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(unmanagedDllName); } } } ``` Fix to be able to load unmanaged dlls in the carna-runner.
```c# // Copyright (C) 2020 Fievus // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Reflection; using System.Runtime.Loader; namespace Carna.ConsoleRunner { internal class CarnaAssemblyLoadContext : AssemblyLoadContext { private readonly AssemblyDependencyResolver assemblyDependencyResolver; public CarnaAssemblyLoadContext(string assemblyPath) { assemblyDependencyResolver = new AssemblyDependencyResolver(assemblyPath); } protected override Assembly Load(AssemblyName assemblyName) { var assemblyPath = assemblyDependencyResolver.ResolveAssemblyToPath(assemblyName); return assemblyPath == null ? null : LoadFromAssemblyPath(assemblyPath); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var unmanagedDllPath = assemblyDependencyResolver.ResolveUnmanagedDllToPath(unmanagedDllName); return unmanagedDllPath == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(unmanagedDllPath); } } } ```
039c7cf3-0573-4dce-9931-2ffb0272c4a5
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using Census.Interfaces; namespace Census.UmbracoObject { public class Property : IUmbracoObject { public string Name { get { return "Document Type"; } } public List<string> BackofficePages { get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; } } DataTable IUmbracoObject.ToDataTable(object usages) { return ToDataTable(usages); } public static DataTable ToDataTable(object usages, int propertyId = 0) { var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages; var dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Alias"); dt.Columns.Add("Property"); foreach (var documentType in documentTypes) { var row = dt.NewRow(); row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif"); row["Alias"] = documentType.Alias; if (propertyId > 0) { var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId); if (prop != null) row["Property"] = prop.Name; } dt.Rows.Add(row); row.AcceptChanges(); } return dt; } } }``` FIx issue looking up property aliases for built-in datatypes
```c# using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using Census.Interfaces; namespace Census.UmbracoObject { public class Property : IUmbracoObject { public string Name { get { return "Document Type"; } } public List<string> BackofficePages { get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; } } DataTable IUmbracoObject.ToDataTable(object usages) { return ToDataTable(usages); } public static DataTable ToDataTable(object usages, int propertyId = 0) { var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages; var dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Alias"); dt.Columns.Add("Property"); foreach (var documentType in documentTypes) { var row = dt.NewRow(); row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif"); row["Alias"] = documentType.Alias; if (propertyId != 0) { var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId); if (prop != null) row["Property"] = prop.Name; } dt.Rows.Add(row); row.AcceptChanges(); } return dt; } } }```
0f759f0b-84f3-47ea-9c31-5342d1a02d10
{ "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.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A button with added default sound effects. /// </summary> public class OsuButton : Button { private SampleChannel sampleClick; private SampleChannel sampleHover; protected override bool OnClick(InputState state) { sampleClick?.Play(); return base.OnClick(state); } protected override bool OnHover(InputState state) { sampleHover?.Play(); return base.OnHover(state); } [BackgroundDependencyLoader] private void load(OsuColour colours, AudioManager audio) { sampleClick = audio.Sample.Get(@"UI/generic-select"); sampleHover = audio.Sample.Get(@"UI/generic-hover"); } } } ``` Add choices of hover sample sets
```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 System.ComponentModel; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Extensions; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A button with added default sound effects. /// </summary> public class OsuButton : Button { private SampleChannel sampleClick; private SampleChannel sampleHover; protected HoverSampleSet SampleSet = HoverSampleSet.Normal; protected override bool OnClick(InputState state) { sampleClick?.Play(); return base.OnClick(state); } protected override bool OnHover(InputState state) { sampleHover?.Play(); return base.OnHover(state); } [BackgroundDependencyLoader] private void load(AudioManager audio) { sampleClick = audio.Sample.Get($@"UI/generic-select{SampleSet.GetDescription()}"); sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}"); } public enum HoverSampleSet { [Description("")] Normal, [Description("-soft")] Soft, [Description("-softer")] Softer } } } ```
a5a4631d-1bfb-419e-bfc2-a53e69a67b60
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using Mlabs.Ogg.Metadata; namespace Mlabs.Ogg { public class OggReader { private readonly Stream m_fileStream; private readonly bool m_owns; public OggReader(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); m_owns = true; } public OggReader(Stream fileStream) { if (fileStream == null) throw new ArgumentNullException("fileStream"); m_fileStream = fileStream; m_owns = false; } public IStreamInfo Read() { var p = new PageReader(); var pages = p.ReadPages(m_fileStream).ToList(); if (m_owns) m_fileStream.Dispose(); return null; } } }``` Read pages and break them down into streams If file stream was not owned by us, rewind it after reading
```c# using System; using System.IO; using System.Linq; namespace Mlabs.Ogg { public class OggReader { private readonly Stream m_fileStream; private readonly bool m_owns; public OggReader(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); m_owns = true; } public OggReader(Stream fileStream) { if (fileStream == null) throw new ArgumentNullException("fileStream"); m_fileStream = fileStream; m_owns = false; } public IOggInfo Read() { long originalOffset = m_fileStream.Position; var p = new PageReader(); //read pages and break them down to streams var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber); if (m_owns) { m_fileStream.Dispose(); } else { //if we didn't create stream rewind it, so that user won't get any surprise :) m_fileStream.Seek(originalOffset, SeekOrigin.Begin); } return null; } } }```
75bd620b-659d-46f0-9d5b-b91bd2f91c44
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RimTrans.Builder; using RimTrans.Builder.Crawler; namespace RimTransLibTest { public static class GenHelper { public static void Gen_DefTypeNameOf() { Console.Write(DefTypeCrawler.GenCode(true, false)); } public static void Gen_DefsTemplate() { DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs"); Capture capture = Capture.Parse(coreDefinitionData); capture.ProcessFieldNames(coreDefinitionData); coreDefinitionData.Save(@"D:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed"); string sourceCodePath = @"D:\git\rw\RimWorld-Decompile\Assembly-CSharp"; Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true); templates.Save(@"D:\git\rw\RimWorld-Defs-Templates\Templates"); } } } ``` Change path for def template generator
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RimTrans.Builder; using RimTrans.Builder.Crawler; namespace RimTransLibTest { public static class GenHelper { public static void Gen_DefTypeNameOf() { Console.Write(DefTypeCrawler.GenCode(true, false)); } public static void Gen_DefsTemplate() { DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs"); Capture capture = Capture.Parse(coreDefinitionData); capture.ProcessFieldNames(coreDefinitionData); coreDefinitionData.Save(@"C:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed"); string sourceCodePath = @"C:\git\rw\RimWorld-Decompile\Assembly-CSharp"; Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true); templates.Save(@"C:\git\rw\RimWorld-Defs-Templates\Templates"); } } } ```
1e16fbd4-da2d-45f0-988f-748c9d3c1598
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Timing; namespace osu.Framework.Audio.Track { public class TrackVirtual : Track { private readonly StopwatchClock clock = new StopwatchClock(); private double seekOffset; public override bool Seek(double seek) { double current = CurrentTime; seekOffset = seek; lock (clock) clock.Restart(); if (Length > 0 && seekOffset > Length) seekOffset = Length; return current != seekOffset; } public override void Start() { lock (clock) clock.Start(); } public override void Reset() { lock (clock) clock.Reset(); seekOffset = 0; base.Reset(); } public override void Stop() { lock (clock) clock.Stop(); } public override bool IsRunning { get { lock (clock) return clock.IsRunning; } } public override bool HasCompleted { get { lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length; } } public override double CurrentTime { get { lock (clock) return seekOffset + clock.CurrentTime; } } public override void Update() { lock (clock) { if (CurrentTime >= Length) Stop(); } } } } ``` Make virtual tracks reeeeeeeaaally long
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Timing; namespace osu.Framework.Audio.Track { public class TrackVirtual : Track { private readonly StopwatchClock clock = new StopwatchClock(); private double seekOffset; public TrackVirtual() { Length = double.MaxValue; } public override bool Seek(double seek) { double current = CurrentTime; seekOffset = seek; lock (clock) clock.Restart(); if (Length > 0 && seekOffset > Length) seekOffset = Length; return current != seekOffset; } public override void Start() { lock (clock) clock.Start(); } public override void Reset() { lock (clock) clock.Reset(); seekOffset = 0; base.Reset(); } public override void Stop() { lock (clock) clock.Stop(); } public override bool IsRunning { get { lock (clock) return clock.IsRunning; } } public override bool HasCompleted { get { lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length; } } public override double CurrentTime { get { lock (clock) return seekOffset + clock.CurrentTime; } } public override void Update() { lock (clock) { if (CurrentTime >= Length) Stop(); } } } } ```
48c57a4c-479d-463e-9d13-21c11014f02e
{ "language": "C#" }
```c# <?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Report</category> </item><?cs /with ?><?cs /each ?> </channel> </rss> ``` Fix category of revision log RSS feeds.
```c# <?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Log</category> </item><?cs /with ?><?cs /each ?> </channel> </rss> ```
c956affc-ed24-4e0e-a32d-2a34cac5f6c5
{ "language": "C#" }
```c# namespace ZWave.CommandClasses { public enum ThermostatFanModeValue : byte { AutoLow = 0x00, Low = 0x01, AutoHigh = 0x02, High = 0x03, AutoMedium = 0x04, Medium = 0x05, Circulation = 0x06, HumidityCirculation = 0x07, LeftAndRight = 0x08, UpAndDown = 0x09, Quiet = 0x0A, ExternalCirculation = 0x0B, EnergyCool = 0x0C, Away = 0x0D, Reserved = 0x0E, FullPower = 0x0F, ManufacturerSpecific = 0x1F }; } ``` Remove these enum values that were copy-pasted by mistake.
```c# namespace ZWave.CommandClasses { public enum ThermostatFanModeValue : byte { AutoLow = 0x00, Low = 0x01, AutoHigh = 0x02, High = 0x03, AutoMedium = 0x04, Medium = 0x05, Circulation = 0x06, HumidityCirculation = 0x07, LeftAndRight = 0x08, UpAndDown = 0x09, Quiet = 0x0A, ExternalCirculation = 0x0B }; } ```