doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
e8ebf73e-945b-4602-8193-759c25812539
{ "language": "C#" }
```c# using System; using OpenStardriveServer.Domain.Systems.Standard; namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines; public record EnginesState : StandardSystemBaseState { public int CurrentSpeed { get; init; } public EngineSpeedConfig SpeedConfig { get; init; } public int CurrentHeat { get; init; } public EngineHeatConfig HeatConfig { get; init; } public SpeedPowerRequirement[] SpeedPowerRequirements = Array.Empty<SpeedPowerRequirement>(); } public record EngineSpeedConfig { public int MaxSpeed { get; init; } public int CruisingSpeed { get; init; } } public record EngineHeatConfig { public int PoweredHeat { get; init; } public int CruisingHeat { get; init; } public int MaxHeat { get; init; } public int MinutesAtMaxSpeed { get; init; } public int MinutesToCoolDown { get; init; } } public record SpeedPowerRequirement { public int Speed { get; init; } public int PowerNeeded { get; init; } }``` Fix bug where prop was not serialized
```c# using System; using OpenStardriveServer.Domain.Systems.Standard; namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines; public record EnginesState : StandardSystemBaseState { public int CurrentSpeed { get; init; } public EngineSpeedConfig SpeedConfig { get; init; } public int CurrentHeat { get; init; } public EngineHeatConfig HeatConfig { get; init; } public SpeedPowerRequirement[] SpeedPowerRequirements { get; init; } = Array.Empty<SpeedPowerRequirement>(); } public record EngineSpeedConfig { public int MaxSpeed { get; init; } public int CruisingSpeed { get; init; } } public record EngineHeatConfig { public int PoweredHeat { get; init; } public int CruisingHeat { get; init; } public int MaxHeat { get; init; } public int MinutesAtMaxSpeed { get; init; } public int MinutesToCoolDown { get; init; } } public record SpeedPowerRequirement { public int Speed { get; init; } public int PowerNeeded { get; init; } }```
f1b20a04-f7ab-41f6-a2ca-2e7919264d51
{ "language": "C#" }
```c# using System; namespace RapidCore.Locking { public class DistributedAppLockException : Exception { public DistributedAppLockException() { } public DistributedAppLockException(string message) : base(message) { } public DistributedAppLockException(string message, Exception inner) : base(message, inner) { } public DistributedAppLockExceptionReason Reason { get; set; } } }``` Add overloads to exception to take in the Reason
```c# using System; namespace RapidCore.Locking { public class DistributedAppLockException : Exception { public DistributedAppLockException() { } public DistributedAppLockException(string message) : base(message) { } public DistributedAppLockException(string message, DistributedAppLockExceptionReason reason) : base(message) { Reason = reason; } public DistributedAppLockException(string message, Exception inner) : base(message, inner) { } public DistributedAppLockException(string message, Exception inner, DistributedAppLockExceptionReason reason) : base(message, inner) { Reason = reason; } public DistributedAppLockExceptionReason Reason { get; set; } } }```
0c5a032f-5ee1-4bb7-b020-eed4dad3070a
{ "language": "C#" }
```c# using UnityEngine; namespace HoloToolkit.Unity { public static class CameraExtensions { /// <summary> /// Get the horizontal FOV from the stereo camera /// </summary> /// <returns></returns> public static float GetHorizontalFieldOfViewRadians(this Camera camera) { float horizontalFovRadians = 2 * Mathf.Atan(Mathf.Tan((camera.fieldOfView * Mathf.Deg2Rad) / 2) * camera.aspect); return horizontalFovRadians; } /// <summary> /// Returns if a point will be rendered on the screen in either eye /// </summary> /// <param name="position"></param> /// <returns></returns> public static bool IsInFOV(this Camera camera, Vector3 position) { float verticalFovHalf = camera.fieldOfView / 2; float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg / 2; Vector3 deltaPos = position - camera.transform.position; Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized; float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg; float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg; return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf); } } }``` Use floats across the camera calculations /2 > 0.5f
```c# using UnityEngine; namespace HoloToolkit.Unity { public static class CameraExtensions { /// <summary> /// Get the horizontal FOV from the stereo camera /// </summary> /// <returns></returns> public static float GetHorizontalFieldOfViewRadians(this Camera camera) { float horizontalFovRadians = 2f * Mathf.Atan(Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * camera.aspect); return horizontalFovRadians; } /// <summary> /// Returns if a point will be rendered on the screen in either eye /// </summary> /// <param name="position"></param> /// <returns></returns> public static bool IsInFOV(this Camera camera, Vector3 position) { float verticalFovHalf = camera.fieldOfView * 0.5f; float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg * 0.5f; Vector3 deltaPos = position - camera.transform.position; Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized; float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg; float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg; return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf); } } }```
ae072c52-8b25-4ce1-8f1b-40123915f782
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace compiler.middleend.ir { class ParseResult { public Operand Operand { get; set; } public List<Instruction> Instructions { get; set; } public Dictionary<SsaVariable, Instruction> VarTable { get; set; } public ParseResult() { Operand = null; Instructions = null; VarTable = new Dictionary<SsaVariable, Instruction>(); } public ParseResult(Dictionary<SsaVariable, Instruction> symTble ) { Operand = null; Instructions = null; VarTable = new Dictionary<SsaVariable, Instruction>(symTble); } public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<SsaVariable, Instruction> pSymTble) { Operand = pOperand; Instructions = new List<Instruction>(pInstructions); VarTable = new Dictionary<SsaVariable, Instruction>(pSymTble); } } } ``` Fix Dictionary type to be more useful
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace compiler.middleend.ir { class ParseResult { public Operand Operand { get; set; } public List<Instruction> Instructions { get; set; } public Dictionary<int, SsaVariable> VarTable { get; set; } public ParseResult() { Operand = null; Instructions = null; VarTable = new Dictionary<int, SsaVariable>(); } public ParseResult(Dictionary<int, SsaVariable> symTble ) { Operand = null; Instructions = null; VarTable = new Dictionary<int, SsaVariable>(symTble); } public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<int, SsaVariable> pSymTble) { Operand = pOperand; Instructions = new List<Instruction>(pInstructions); VarTable = new Dictionary<int, SsaVariable>(pSymTble); } } } ```
bee4210a-16e4-44db-b530-074098a938c1
{ "language": "C#" }
```c# namespace SimpleOrderRouting.Journey1 { public class ExecutionState { public ExecutionState(InvestorInstruction investorInstruction) { this.Quantity = investorInstruction.Quantity; this.Price = investorInstruction.Price; this.Way = investorInstruction.Way; this.AllowPartialExecution = investorInstruction.AllowPartialExecution; } public int Quantity { get; set; } public decimal Price { get; set; } public Way Way { get; set; } public bool AllowPartialExecution { get; set; } { this.Quantity -= quantity; } } }``` Fix fat-finger made before the previous commit
```c# namespace SimpleOrderRouting.Journey1 { public class ExecutionState { public ExecutionState(InvestorInstruction investorInstruction) { this.Quantity = investorInstruction.Quantity; this.Price = investorInstruction.Price; this.Way = investorInstruction.Way; this.AllowPartialExecution = investorInstruction.AllowPartialExecution; } public int Quantity { get; set; } public decimal Price { get; set; } public Way Way { get; set; } public bool AllowPartialExecution { get; set; } public void Executed(int quantity) { this.Quantity -= quantity; } } }```
28d636f7-6dbf-4ca1-8f47-0b87f70eee49
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using System.Collections.Generic; public class PowerRandom : BaseSpecialPower { [SerializeField] private List<BaseSpecialPower> powers; private BaseSpecialPower activePower = null; protected override void Start() { base.Start(); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; } protected override void Activate() { StartCoroutine(WaitForDestroy()); } protected override void Update() { if(activePower.mana > 0) { base.Update(); } } IEnumerator WaitForDestroy() { yield return null; while(activePower.coolDownTimer > 0) { yield return null; } float currentMana = activePower.mana; DestroyImmediate(activePower.gameObject); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; yield return null; activePower.mana = currentMana; yield return null; EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI } } ``` Fix random power use when cooldown
```c# using UnityEngine; using System.Collections; using System.Collections.Generic; public class PowerRandom : BaseSpecialPower { [SerializeField] private List<BaseSpecialPower> powers; private BaseSpecialPower activePower = null; protected override void Start() { base.Start(); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; } protected override void Activate() { if(activePower.coolDownTimer <= 0) StartCoroutine(WaitForDestroy()); } protected override void Update() { if(activePower.mana > 0) { base.Update(); } } IEnumerator WaitForDestroy() { yield return null; while(activePower.coolDownTimer > 0) { yield return null; } float currentMana = activePower.mana; Debug.Log(currentMana); DestroyImmediate(activePower.gameObject); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; yield return null; activePower.mana = currentMana; yield return null; EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI } } ```
7bbad602-6066-4411-bc7b-4bd647961e69
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Xml.Linq; using JetBrains.Annotations; namespace Dasher.Schemata { public interface IWriteSchema { /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IWriteSchema CopyTo(SchemaCollection collection); } public interface IReadSchema { bool CanReadFrom(IWriteSchema writeSchema, bool strict); /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IReadSchema CopyTo(SchemaCollection collection); } public abstract class Schema { internal abstract IEnumerable<Schema> Children { get; } public override bool Equals(object obj) { var other = obj as Schema; return other != null && Equals(other); } public abstract bool Equals(Schema other); public override int GetHashCode() => ComputeHashCode(); protected abstract int ComputeHashCode(); } /// <summary>For complex, union and enum.</summary> public abstract class ByRefSchema : Schema { [CanBeNull] internal string Id { get; set; } internal abstract XElement ToXml(); public override string ToString() => Id; } /// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary> public abstract class ByValueSchema : Schema { internal abstract string MarkupValue { get; } public override string ToString() => MarkupValue; } }``` Improve ToString when Id is null
```c# using System.Collections.Generic; using System.Xml.Linq; using JetBrains.Annotations; namespace Dasher.Schemata { public interface IWriteSchema { /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IWriteSchema CopyTo(SchemaCollection collection); } public interface IReadSchema { bool CanReadFrom(IWriteSchema writeSchema, bool strict); /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IReadSchema CopyTo(SchemaCollection collection); } public abstract class Schema { internal abstract IEnumerable<Schema> Children { get; } public override bool Equals(object obj) { var other = obj as Schema; return other != null && Equals(other); } public abstract bool Equals(Schema other); public override int GetHashCode() => ComputeHashCode(); protected abstract int ComputeHashCode(); } /// <summary>For complex, union and enum.</summary> public abstract class ByRefSchema : Schema { [CanBeNull] internal string Id { get; set; } internal abstract XElement ToXml(); public override string ToString() => Id ?? GetType().Name; } /// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary> public abstract class ByValueSchema : Schema { internal abstract string MarkupValue { get; } public override string ToString() => MarkupValue; } }```
3e07343c-eba4-4ebe-b49d-35b56aa12115
{ "language": "C#" }
```c# namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions { using System; using System.Web; using Sitecore.Diagnostics; using Sitecore.Rules; using Sitecore.Rules.Conditions; /// <summary> /// UserAgentCondition /// </summary> /// <typeparam name="T"></typeparam> public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public string Value { get; set; } /// <summary> /// Executes the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> /// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns> protected override bool Execute(T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); string str = this.Value ?? string.Empty; var userAgent = HttpContext.Current.Request.UserAgent; if (!string.IsNullOrEmpty(userAgent)) { return userAgent.IndexOf(str, StringComparison.OrdinalIgnoreCase) >= 0; } return false; } } } ``` Support full range of comparison operators instead of IndexOf
```c# namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions { using System; using System.Web; using Sitecore.Diagnostics; using Sitecore.Rules; using Sitecore.Rules.Conditions; /// <summary> /// UserAgentCondition /// </summary> /// <typeparam name="T"></typeparam> public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public string Value { get; set; } /// <summary> /// Executes the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> /// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns> protected override bool Execute(T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); string str = this.Value ?? string.Empty; var userAgent = HttpContext.Current.Request.UserAgent; if (!string.IsNullOrEmpty(userAgent)) { return Compare(str, userAgent); } return false; } } } ```
0ee04e87-7941-4fb9-8d7a-463790ced450
{ "language": "C#" }
```c# using System.Diagnostics; using System.IO; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection collection = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(NTAccount)); foreach(FileSystemAccessRule rule in collection){ if ((rule.FileSystemRights & right) == right){ return true; } } return false; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } } ``` Revert "Rewrite folder write permission check to hopefully make it more reliable"
```c# using System.Diagnostics; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier)); WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (identity.Groups == null){ return false; } bool accessAllow = false, accessDeny = false; foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){ switch(rule.AccessControlType){ case AccessControlType.Allow: accessAllow = true; break; case AccessControlType.Deny: accessDeny = true; break; } } return accessAllow && !accessDeny; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } } ```
c45950e9-fb47-438f-94a7-fc81d0e0b8e0
{ "language": "C#" }
```c# namespace Mollie.Api.Models.Connect { public static class AppPermissions { public const string PaymentsRead = "payments.read"; public const string PaymentsWrite = "payments.write"; public const string RefundsRead = "refunds.read"; public const string RefundsWrite = "refunds.write"; public const string CustomersRead = "customers.read"; public const string CustomersWrite = "customers.write"; public const string MandatesRead = "mandates.read"; public const string MandatesWrite = "mandates.write"; public const string SubscriptionsRead = "subscriptions.read"; public const string SubscriptionsWrite = "subscriptions.write"; public const string ProfilesRead = "profiles.read"; public const string ProfilesWrite = "profiles.write"; public const string InvoicesRead = "invoices.read"; public const string OrdersRead = "orders.read"; public const string OrdersWrite = "orders.write"; public const string ShipmentsRead = "shipments.read"; public const string ShipmentsWrite = "shipments.write"; public const string OrganizationRead = "organizations.read"; public const string OrganizationWrite = "organizations.write"; public const string OnboardingRead = "onboarding.write"; public const string OnboardingWrite = "onboarding.write"; } } ``` Fix typo in OnboardingRead and add SettlementsRead
```c# namespace Mollie.Api.Models.Connect { public static class AppPermissions { public const string PaymentsRead = "payments.read"; public const string PaymentsWrite = "payments.write"; public const string RefundsRead = "refunds.read"; public const string RefundsWrite = "refunds.write"; public const string CustomersRead = "customers.read"; public const string CustomersWrite = "customers.write"; public const string MandatesRead = "mandates.read"; public const string MandatesWrite = "mandates.write"; public const string SubscriptionsRead = "subscriptions.read"; public const string SubscriptionsWrite = "subscriptions.write"; public const string ProfilesRead = "profiles.read"; public const string ProfilesWrite = "profiles.write"; public const string InvoicesRead = "invoices.read"; public const string OrdersRead = "orders.read"; public const string OrdersWrite = "orders.write"; public const string ShipmentsRead = "shipments.read"; public const string ShipmentsWrite = "shipments.write"; public const string OrganizationRead = "organizations.read"; public const string OrganizationWrite = "organizations.write"; public const string OnboardingRead = "onboarding.read"; public const string OnboardingWrite = "onboarding.write"; public const string SettlementsRead = "settlements.read"; } } ```
4792eb86-5c99-48ab-a8b9-dde1d64b3639
{ "language": "C#" }
```c# namespace Endjin.Cancelable.Demo { #region Using Directives using System; using System.Threading; using System.Threading.Tasks; using Endjin.Contracts; using Endjin.Core.Composition; using Endjin.Core.Container; #endregion public class Program { public static void Main(string[] args) { ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait(); var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>(); var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045"; cancelable.CreateToken(cancellationToken); cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait(); Console.WriteLine("Press Any Key to Exit!"); Console.ReadKey(); } private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken) { int counter = 0; while (!cancellationToken.IsCancellationRequested) { Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T")); await Task.Delay(TimeSpan.FromSeconds(1)); counter++; if (counter == 15) { Console.WriteLine("Long Running Process Ran to Completion!"); break; } } if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Long Running Process was Cancelled!"); } } } }``` Add warning message to ensure user is running the Azure Emulator
```c# namespace Endjin.Cancelable.Demo { #region Using Directives using System; using System.Threading; using System.Threading.Tasks; using Endjin.Contracts; using Endjin.Core.Composition; using Endjin.Core.Container; #endregion public class Program { public static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("Ensure you are running the Azure Storage Emulator!"); Console.ResetColor(); ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait(); var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>(); var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045"; cancelable.CreateToken(cancellationToken); cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait(); Console.WriteLine("Press Any Key to Exit!"); Console.ReadKey(); } private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken) { int counter = 0; while (!cancellationToken.IsCancellationRequested) { Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T")); await Task.Delay(TimeSpan.FromSeconds(1)); counter++; if (counter == 15) { Console.WriteLine("Long Running Process Ran to Completion!"); break; } } if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Long Running Process was Cancelled!"); } } } }```
850f510c-510e-401b-ace6-165ec3fb1613
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Net.Mail; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions; using Microsoft.Azure.WebJobs.Host; using OutgoingHttpRequestWebJobsExtension; namespace ExtensionsSample { public static class Program { public static void Main(string[] args) { var config = new JobHostConfiguration(); config.UseDevelopmentSettings(); config.UseOutgoingHttpRequests(); var host = new JobHost(config); var method = typeof(Program).GetMethod("MyCoolMethod"); host.Call(method); } public static void MyCoolMethod( [OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer) { writer.Write("Test sring sent to OutgoingHttpRequest!"); } } }``` Add input param. logger and get test string from cmd line
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using Microsoft.Azure.WebJobs; using OutgoingHttpRequestWebJobsExtension; namespace ExtensionsSample { public static class Program { public static void Main(string[] args) { string inputString = args.Length > 0 ? args[0] : "Some test string"; var config = new JobHostConfiguration(); config.UseDevelopmentSettings(); config.UseOutgoingHttpRequests(); var host = new JobHost(config); var method = typeof(Program).GetMethod("MyCoolMethod"); host.Call(method, new Dictionary<string, object> { {"input", inputString } }); } public static void MyCoolMethod( string input, [OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer, TextWriter logger) { logger.Write(input); writer.Write(input); } } }```
20a2786a-4f56-433f-9448-6b08123829c6
{ "language": "C#" }
```c# /* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.2f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.05); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } } ``` Tweak skybox rotation direction and speed
```c# /* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateRotationZ(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.25f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.04); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } } ```
9afc7ef7-d6ad-4389-97bd-5cad8111f1f7
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } } ``` Update nullable annotations in Experiments folder
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } } ```
a497a0a7-202a-41ab-ab96-7c830e4ed18a
{ "language": "C#" }
```c# using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } } ``` Throw a CommandException if no hostname is specified
```c# using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("No hostname was specified"); } throw new NotImplementedException(); } } } ```
65dc058e-014d-4550-a319-701db339e1ae
{ "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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } } ``` Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
```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.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } } ```
b946bd19-9464-4c52-95f5-973c87078272
{ "language": "C#" }
```c# namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = this.ExecutedCommand.Parameters["value"].First.ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } } ``` Fix for wrong keys when using python binding
```c# namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = string.Join(string.Empty, this.ExecutedCommand.Parameters["value"]); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } } ```
6690e38e-35c9-4699-b186-3ddc0922c98f
{ "language": "C#" }
```c# using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"[A-Z]{2}\d{3}", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } }``` Update RobotName name test to be more restrictive
```c# using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } } ```
d308cd69-4f02-4d99-aabd-f7ef155763c8
{ "language": "C#" }
```c# using System; using System.Linq; namespace NReplayGain { /// <summary> /// Contains ReplayGain data for an album. /// </summary> public class AlbumGain { private GainData albumData; public AlbumGain() { this.albumData = new GainData(); } /// <summary> /// After calculating the ReplayGain data for an album, call this to append the data to the album. /// </summary> public void AppendTrackData(TrackGain trackGain) { int[] sourceAccum = trackGain.gainData.Accum; for (int i = 0; i < sourceAccum.Length; ++i) { this.albumData.Accum[i] = sourceAccum[i]; } this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample); } /// <summary> /// Returns the normalization gain for the entire album in decibels. /// </summary> public double GetGain() { return ReplayGain.AnalyzeResult(this.albumData.Accum); } /// <summary> /// Returns the peak album value, normalized to the [0,1] interval. /// </summary> public double GetPeak() { return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE; } } } ``` Fix bug in album gain calculation.
```c# using System; using System.Linq; namespace NReplayGain { /// <summary> /// Contains ReplayGain data for an album. /// </summary> public class AlbumGain { private GainData albumData; public AlbumGain() { this.albumData = new GainData(); } /// <summary> /// After calculating the ReplayGain data for an album, call this to append the data to the album. /// </summary> public void AppendTrackData(TrackGain trackGain) { int[] sourceAccum = trackGain.gainData.Accum; for (int i = 0; i < sourceAccum.Length; ++i) { this.albumData.Accum[i] += sourceAccum[i]; } this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample); } /// <summary> /// Returns the normalization gain for the entire album in decibels. /// </summary> public double GetGain() { return ReplayGain.AnalyzeResult(this.albumData.Accum); } /// <summary> /// Returns the peak album value, normalized to the [0,1] interval. /// </summary> public double GetPeak() { return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE; } } } ```
aaf4a9f0-80ed-486f-90a3-4274af491ba2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Routing; namespace wwwplatform.Extensions { public class SitePageRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string path = httpContext.Request.Url.AbsolutePath; string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller)); return controllers.Count() == 0; } } } ``` Fix route matching for typed-in urls
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Routing; namespace wwwplatform.Extensions { public class SitePageRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string path = httpContext.Request.Url.AbsolutePath; string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller, StringComparison.InvariantCultureIgnoreCase)); return controllers.Count() == 0; } } } ```
af722f8d-3ced-431e-9668-e8725556ae0f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Qowaiv.ComponentModel { /// <summary>Represents a result of a validation, executed command, etcetera.</summary> public class Result<T> : Result { /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> /// <param name="messages"> /// The messages related to the result. /// </param> public Result(T data, IEnumerable<ValidationResult> messages) : base(messages) { Data = data; } /// <summary>Gets the data related to result.</summary> public T Data { get; } /// <summary>Implicitly casts the <see cref="Result"/> to the type of the related model.</summary> public static implicit operator T(Result<T> result) => result == null ? default(T) : result.Data; /// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary> public static explicit operator Result<T>(T model) => new Result<T>(model); } } ``` Add a constructor that only requires messages.
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Qowaiv.ComponentModel { /// <summary>Represents a result of a validation, executed command, etcetera.</summary> public class Result<T> : Result { /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> public Result(IEnumerable<ValidationResult> messages) : this(default(T), messages) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> /// <param name="messages"> /// The messages related to the result. /// </param> public Result(T data, IEnumerable<ValidationResult> messages) : base(messages) { Data = data; } /// <summary>Gets the data related to result.</summary> public T Data { get; } /// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary> public static implicit operator Result<T>(T model) => new Result<T>(model); /// <summary>Explicitly casts the <see cref="Result"/> to the type of the related model.</summary> public static explicit operator T(Result<T> result) => result == null ? default(T) : result.Data; } } ```
e587d7d3-760d-4ddc-b3d7-715c069818f6
{ "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.Game.Beatmaps.Timing; using osu.Game.Graphics; using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays breaks in the song. /// </summary> public class BreakPart : TimelinePart { protected override void LoadBeatmap(EditorBeatmap beatmap) { base.LoadBeatmap(beatmap); foreach (var breakPeriod in beatmap.Breaks) Add(new BreakVisualisation(breakPeriod)); } private class BreakVisualisation : DurationVisualisation { public BreakVisualisation(BreakPeriod breakPeriod) : base(breakPeriod.StartTime, breakPeriod.EndTime) { } [BackgroundDependencyLoader] private void load(OsuColour colours) => Colour = colours.Yellow; } } } ``` Update break colour to not look like kiai time
```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.Game.Beatmaps.Timing; using osu.Game.Graphics; using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays breaks in the song. /// </summary> public class BreakPart : TimelinePart { protected override void LoadBeatmap(EditorBeatmap beatmap) { base.LoadBeatmap(beatmap); foreach (var breakPeriod in beatmap.Breaks) Add(new BreakVisualisation(breakPeriod)); } private class BreakVisualisation : DurationVisualisation { public BreakVisualisation(BreakPeriod breakPeriod) : base(breakPeriod.StartTime, breakPeriod.EndTime) { } [BackgroundDependencyLoader] private void load(OsuColour colours) => Colour = colours.GreyCarmineLight; } } } ```
b156c46b-684a-4225-8f64-73f5c8be4a9e
{ "language": "C#" }
```c# using System; using System.Linq; using Cqrs.Configuration; using Ninject; using Ninject.Parameters; namespace Cqrs.Ninject.Configuration { public class NinjectDependencyResolver : IServiceLocator { public static IServiceLocator Current { get; private set; } static NinjectDependencyResolver() { Current = new NinjectDependencyResolver(new StandardKernel()); } protected IKernel Kernel { get; private set; } public NinjectDependencyResolver(IKernel kernel) { Kernel = kernel; } /// <summary> /// Starts the <see cref="NinjectDependencyResolver"/> /// </summary> /// <remarks> /// this exists to the static constructor can be triggered. /// </remarks> public static void Start() { } public T GetService<T>() { return Resolve<T>(); } public object GetService(Type type) { return Resolve(type); } protected T Resolve<T>() { return (T)Resolve(typeof(T)); } protected object Resolve(Type serviceType) { return Kernel.Resolve(Kernel.CreateRequest(serviceType, null, new Parameter[0], true, true)).SingleOrDefault(); } } }``` Allow the static property to be protected
```c# using System; using System.Linq; using Cqrs.Configuration; using Ninject; using Ninject.Parameters; namespace Cqrs.Ninject.Configuration { public class NinjectDependencyResolver : IServiceLocator { public static IServiceLocator Current { get; protected set; } static NinjectDependencyResolver() { Current = new NinjectDependencyResolver(new StandardKernel()); } protected IKernel Kernel { get; private set; } public NinjectDependencyResolver(IKernel kernel) { Kernel = kernel; } /// <summary> /// Starts the <see cref="NinjectDependencyResolver"/> /// </summary> /// <remarks> /// this exists to the static constructor can be triggered. /// </remarks> public static void Start() { } public T GetService<T>() { return Resolve<T>(); } public object GetService(Type type) { return Resolve(type); } protected T Resolve<T>() { return (T)Resolve(typeof(T)); } protected object Resolve(Type serviceType) { return Kernel.Resolve(Kernel.CreateRequest(serviceType, null, new Parameter[0], true, true)).SingleOrDefault(); } } }```
d78bf231-1126-4dd5-80c5-08dc3b004b94
{ "language": "C#" }
```c# @model int? @{ ViewBag.Title = "Error"; ViewBag.Message = ViewBag.Message ?? "An error occurred while processing your request."; } <h1 class="text-danger">Error (HTTP @(Model ?? 500))</h1> <h2 class="text-danger">@ViewBag.Message</h2> ``` Add NOINDEX to error pages
```c# @model int? @{ ViewBag.MetaDescription = string.Empty; ViewBag.MetaRobots = "NOINDEX"; ViewBag.Title = "Error"; ViewBag.Message = ViewBag.Message ?? "An error occurred while processing your request."; } <h1 class="text-danger">Error (HTTP @(Model ?? 500))</h1> <h2 class="text-danger">@ViewBag.Message</h2> ```
f29bf58e-09bb-449a-97c2-71c6c583576a
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Rulesets; using osuTK; namespace osu.Game.Overlays { public class OverlayRulesetSelector : RulesetSelector { public OverlayRulesetSelector() { AutoSizeAxes = Axes.Both; } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new OverlayRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(20, 0), }; } } ``` Select user preferred ruleset on overlay ruleset selectors initially
```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.Framework.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Rulesets; using osuTK; namespace osu.Game.Overlays { public class OverlayRulesetSelector : RulesetSelector { public OverlayRulesetSelector() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(RulesetStore store, IAPIProvider api) { var preferredRuleset = store.GetRuleset(api.LocalUser.Value.PlayMode); if (preferredRuleset != null) Current.Value = preferredRuleset; } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new OverlayRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(20, 0), }; } } ```
9b138f84-f316-42c4-a5ff-47b49add5d79
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; namespace osu.Framework.Graphics.Shaders { /// <summary> /// A mapping of a global uniform to many shaders which need to receive updates on a change. /// </summary> internal class UniformMapping<T> : IUniformMapping where T : struct { public T Value; public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>(); public string Name { get; } public UniformMapping(string name) { Name = name; } public void LinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; typedUniform.UpdateValue(this); LinkedUniforms.Add(typedUniform); } public void UnlinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; LinkedUniforms.Remove(typedUniform); } public void UpdateValue(ref T newValue) { Value = newValue; // Iterate by index to remove an enumerator allocation // ReSharper disable once ForCanBeConvertedToForeach for (int i = 0; i < LinkedUniforms.Count; i++) LinkedUniforms[i].UpdateValue(this); } } } ``` Remove no longer necessary comment
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; namespace osu.Framework.Graphics.Shaders { /// <summary> /// A mapping of a global uniform to many shaders which need to receive updates on a change. /// </summary> internal class UniformMapping<T> : IUniformMapping where T : struct { public T Value; public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>(); public string Name { get; } public UniformMapping(string name) { Name = name; } public void LinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; typedUniform.UpdateValue(this); LinkedUniforms.Add(typedUniform); } public void UnlinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; LinkedUniforms.Remove(typedUniform); } public void UpdateValue(ref T newValue) { Value = newValue; for (int i = 0; i < LinkedUniforms.Count; i++) LinkedUniforms[i].UpdateValue(this); } } } ```
3cdcc2c7-422d-43d4-9e47-229d6dd99fb8
{ "language": "C#" }
```c# // Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.HtmlBrowser { public interface IWebBrowser { bool CanGoBack { get; } bool CanGoForward { get; } string DocumentText { set; } string DocumentTitle { get; } bool Focused { get; } bool IsBusy { get; } bool IsWebBrowserContextMenuEnabled { get; set; } string StatusText { get; } Uri Url { get; set; } bool GoBack(); bool GoForward(); void Navigate(string urlString); void Navigate(Uri url); void Refresh(); void Refresh(WebBrowserRefreshOption opt); void Stop(); void ScrollLastElementIntoView(); object NativeBrowser { get; } } }``` Document a promise to reintroduce the DocumentText get
```c# // Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.HtmlBrowser { public interface IWebBrowser { bool CanGoBack { get; } bool CanGoForward { get; } /// <summary> /// Set of the DocumentText will load the given string content into the browser. /// If a get for DocumentText proves necessary Jason promises to write the reflective /// gecko implementation. /// </summary> string DocumentText { set; } string DocumentTitle { get; } bool Focused { get; } bool IsBusy { get; } bool IsWebBrowserContextMenuEnabled { get; set; } string StatusText { get; } Uri Url { get; set; } bool GoBack(); bool GoForward(); void Navigate(string urlString); void Navigate(Uri url); void Refresh(); void Refresh(WebBrowserRefreshOption opt); void Stop(); void ScrollLastElementIntoView(); object NativeBrowser { get; } } }```
122ed4eb-f2eb-44ad-afbf-fb67c7ef1d49
{ "language": "C#" }
```c# namespace AgileObjects.AgileMapper.UnitTests { using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenViewingMappingPlans { [Fact] public void ShouldIncludeASimpleTypeMemberMapping() { var plan = Mapper .GetPlanFor<PublicField<string>>() .ToANew<PublicProperty<string>>(); plan.ShouldContain("instance.Value = omc.Source.Value;"); } [Fact] public void ShouldIncludeAComplexTypeMemberMapping() { var plan = Mapper .GetPlanFor<PersonViewModel>() .ToANew<Person>(); plan.ShouldContain("instance.Name = omc.Source.Name;"); plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;"); } [Fact] public void ShouldIncludeASimpleTypeEnumerableMemberMapping() { var plan = Mapper .GetPlanFor<PublicProperty<int[]>>() .ToANew<PublicField<IEnumerable<int>>>(); plan.ShouldContain("omc.Source.ForEach"); plan.ShouldContain("instance.Add"); } } } ``` Test coverage for viewing a simple type member conversion in a mapping plan
```c# namespace AgileObjects.AgileMapper.UnitTests { using System; using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenViewingMappingPlans { [Fact] public void ShouldIncludeASimpleTypeMemberMapping() { var plan = Mapper .GetPlanFor<PublicField<string>>() .ToANew<PublicProperty<string>>(); plan.ShouldContain("instance.Value = omc.Source.Value;"); } [Fact] public void ShouldIncludeAComplexTypeMemberMapping() { var plan = Mapper .GetPlanFor<PersonViewModel>() .ToANew<Person>(); plan.ShouldContain("instance.Name = omc.Source.Name;"); plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;"); } [Fact] public void ShouldIncludeASimpleTypeEnumerableMemberMapping() { var plan = Mapper .GetPlanFor<PublicProperty<int[]>>() .ToANew<PublicField<IEnumerable<int>>>(); plan.ShouldContain("omc.Source.ForEach"); plan.ShouldContain("instance.Add"); } [Fact] public void ShouldIncludeASimpleTypeMemberConversion() { var plan = Mapper .GetPlanFor<PublicProperty<Guid>>() .ToANew<PublicField<string>>(); plan.ShouldContain("omc.Source.Value.ToString("); } } } ```
fe84c03f-15d2-42b1-98b2-373f693ff635
{ "language": "C#" }
```c# using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way /// function method for committing bits /// </summary> public class BitCommitmentProvider { public byte[] AliceRandBytes1 { get; set; } public byte[] AliceRandBytes2 { get; set; } public byte[] AliceMessageBytesBytes { get; set; } public BitCommitmentProvider(byte[] one, byte[] two, byte[] messageBytes) { AliceRandBytes1 = one; AliceRandBytes2 = two; AliceMessageBytesBytes = messageBytes; } public byte[] BitCommitMessage() { throw new NotImplementedException(); } } } ``` Refactor to make steps of protocol clearer
```c# using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. Based on Bruce Schneier's RandBytes1-way /// function method for committing bits /// </summary> public class BitCommitmentProvider { public byte[] AliceRandBytes1 { get; set; } public byte[] AliceRandBytes2 { get; set; } public byte[] AliceBytesToCommitBytesToCommit { get; set; } public BitCommitmentProvider(byte[] randBytes1, byte[] randBytes2, byte[] bytesToCommit) { AliceRandBytes1 = randBytes1; AliceRandBytes2 = randBytes2; AliceBytesToCommitBytesToCommit = bytesToCommit; } public byte[] BitCommitMessage() { throw new NotImplementedException(); } } } ```
342ac524-62ea-4d29-9a3e-0f2630e98974
{ "language": "C#" }
```c# using System.Dynamic; using BobTheBuilder.ArgumentStore; namespace BobTheBuilder.Syntax { public class DynamicBuilder<T> : DynamicBuilderBase<T> where T: class { public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { } public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result) { ParseMembersFromMethodName(binder, args); result = this; return true; } private void ParseMembersFromMethodName(InvokeMemberBinder binder, object[] args) { var memberName = binder.Name.Replace("With", ""); argumentStore.SetMemberNameAndValue(memberName, args[0]); } } }``` Implement IParser on method syntax builder.
```c# using System.Dynamic; using BobTheBuilder.ArgumentStore; namespace BobTheBuilder.Syntax { public class DynamicBuilder<T> : DynamicBuilderBase<T>, IParser where T: class { public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { } public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result) { Parse(binder, args); result = this; return true; } public bool Parse(InvokeMemberBinder binder, object[] args) { var memberName = binder.Name.Replace("With", ""); argumentStore.SetMemberNameAndValue(memberName, args[0]); return true; } } }```
b2732dc1-30f9-4c02-b2a4-06493af1c5cb
{ "language": "C#" }
```c# using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions : IZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 1000.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 5; ClosedStateDuration = 15.Seconds(); ReceiveHighWaterMark = 20000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDuration { get; set; } public int ReceiveHighWaterMark { get; set; } } }``` Make send try policy more aggressive
```c# using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions : IZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 100.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 2; ClosedStateDuration = 15.Seconds(); ReceiveHighWaterMark = 20000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDuration { get; set; } public int ReceiveHighWaterMark { get; set; } } }```
59f4c2ae-f433-4648-8b57-2972e168b75a
{ "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.Screens; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenBehaviour : OsuManualInputManagerTestScene { public TestSceneFirstRunScreenBehaviour() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenBehaviour()); }); } } } ``` Add missing dependencies for behaviour screen test
```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.Screens; using osu.Game.Overlays; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenBehaviour : OsuManualInputManagerTestScene { [Cached] private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); public TestSceneFirstRunScreenBehaviour() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenBehaviour()); }); } } } ```
6af4a984-f719-4fac-bb4f-ced38d0807e8
{ "language": "C#" }
```c# using CefSharp; using CefSharp.Handler; using TweetDuck.Controls; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling.General { sealed class CustomLifeSpanHandler : LifeSpanHandler { private static bool IsPopupAllowed(string url) { return url.StartsWith("https://twitter.com/teams/authorize?"); } public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) { switch (targetDisposition) { case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl): case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) { return false; } } } ``` Fix popups for Google & Apple sign-in
```c# using System; using CefSharp; using CefSharp.Handler; using TweetDuck.Controls; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling.General { sealed class CustomLifeSpanHandler : LifeSpanHandler { private static bool IsPopupAllowed(string url) { return url.StartsWith("https://twitter.com/teams/authorize?", StringComparison.Ordinal) || url.StartsWith("https://accounts.google.com/", StringComparison.Ordinal) || url.StartsWith("https://appleid.apple.com/", StringComparison.Ordinal); } public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) { switch (targetDisposition) { case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl): case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) { return false; } } } ```
0a429aa8-0465-4c7a-b28d-9e3b20e54768
{ "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 osuTK; namespace osu.Game.Rulesets.Edit { /// <summary> /// A snap provider which given the position of a hit object, offers a more correct position and time value inferred from the context of the beatmap. /// Provided values are done so in an isolated context, without consideration of other nearby hit objects. /// </summary> public interface IPositionSnapProvider { /// <summary> /// Given a position, find a valid time and position snap. /// </summary> /// <remarks> /// This call should be equivalent to running <see cref="FindSnappedPosition"/> with any additional logic that can be performed without the time immutability restriction. /// </remarks> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The time and position post-snapping.</returns> SnapResult FindSnappedPositionAndTime(Vector2 screenSpacePosition); /// <summary> /// Given a position, find a value position snap, restricting time to its input value. /// </summary> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The position post-snapping. Time will always be null.</returns> SnapResult FindSnappedPosition(Vector2 screenSpacePosition); } } ``` Reword slightly, to allow better conformity with `IDistanceSnapProvider`
```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 osuTK; namespace osu.Game.Rulesets.Edit { /// <summary> /// A snap provider which given a proposed position for a hit object, potentially offers a more correct position and time value inferred from the context of the beatmap. /// Provided values are inferred in an isolated context, without consideration of other nearby hit objects. /// </summary> public interface IPositionSnapProvider { /// <summary> /// Given a position, find a valid time and position snap. /// </summary> /// <remarks> /// This call should be equivalent to running <see cref="FindSnappedPosition"/> with any additional logic that can be performed without the time immutability restriction. /// </remarks> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The time and position post-snapping.</returns> SnapResult FindSnappedPositionAndTime(Vector2 screenSpacePosition); /// <summary> /// Given a position, find a value position snap, restricting time to its input value. /// </summary> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The position post-snapping. Time will always be null.</returns> SnapResult FindSnappedPosition(Vector2 screenSpacePosition); } } ```
6a314062-1474-40b9-8eb1-22fdf265185a
{ "language": "C#" }
```c# using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"), DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, SourceLinkSettings = SourceLinkSettings.Default, }); }); } ``` Remove use of obsolete property.
```c# using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"), DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, }); }); } ```
22e032bb-815b-4632-9a4b-2532da78dd05
{ "language": "C#" }
```c# using System.Resources; 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("CallMeMaybe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CallMeMaybe")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Set auto-incrementing file version, starting with 0.1, since we're at alpha stage
```c# using System.Resources; 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("CallMeMaybe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CallMeMaybe")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("0.1.*")] //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")] ```
cb6a701a-2348-472d-aced-290b561e0bbb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; using JetBrains.Annotations; namespace Booma.Proxy { /// <summary> /// Marks the 0x60 command server payload with the associated operation code. /// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute { /// <inheritdoc /> public SubCommand60ServerAttribute(SubCommand60OperationCode opCode) : base((int)opCode, typeof(BlockNetworkCommandEventClientPayload)) { if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode)); } } } ``` Fix fault with subcommand server attribute
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; using JetBrains.Annotations; namespace Booma.Proxy { /// <summary> /// Marks the 0x60 command server payload with the associated operation code. /// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute { /// <inheritdoc /> public SubCommand60ServerAttribute(SubCommand60OperationCode opCode) : base((int)opCode, typeof(BlockNetworkCommandEventServerPayload)) { if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode)); } } } ```
a2e6cd75-2456-426d-8cfa-2ce48712e924
{ "language": "C#" }
```c# using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }``` Add administrator user by default
```c# using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }```
76ad1b84-e82a-4c18-984c-75febdf0c211
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Web.Deployment; namespace WAWSDeploy { public class WebDeployHelper { public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile) { var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } } private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions) { var document = XDocument.Load(path); var profile = document.Descendants("publishProfile").First(); string siteName = profile.Attribute("msdeploySite").Value; deploymentBaseOptions = new DeploymentBaseOptions { ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName), UserName = profile.Attribute("userName").Value, Password = profile.Attribute("userPWD").Value, AuthenticationType = "Basic" }; return siteName; } } } ``` Use full path to source folder
```c# using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Web.Deployment; namespace WAWSDeploy { public class WebDeployHelper { public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile) { contentPath = Path.GetFullPath(contentPath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } } private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions) { var document = XDocument.Load(path); var profile = document.Descendants("publishProfile").First(); string siteName = profile.Attribute("msdeploySite").Value; deploymentBaseOptions = new DeploymentBaseOptions { ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName), UserName = profile.Attribute("userName").Value, Password = profile.Attribute("userPWD").Value, AuthenticationType = "Basic" }; return siteName; } } } ```
429d0016-b96e-4ed6-84b5-47f2b864e31f
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; namespace LightBlue.Standalone { public class StandaloneAzureStorage : IAzureStorage { public const string DevelopmentAccountName = "dev"; private readonly string _storageAccountDirectory; public StandaloneAzureStorage(string connectionString) { var storageAccountName = ExtractAccountName(connectionString); _storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName); Directory.CreateDirectory(_storageAccountDirectory); } public IAzureBlobStorageClient CreateAzureBlobStorageClient() { return new StandaloneAzureBlobStorageClient(_storageAccountDirectory); } public IAzureQueueStorageClient CreateAzureQueueStorageClient() { throw new NotSupportedException(); } private static string ExtractAccountName(string connectionString) { try { var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]); if (valuePairs.ContainsKey("accountname")) { return valuePairs["accountname"]; } if (valuePairs.ContainsKey("usedevelopmentstorage")) { return DevelopmentAccountName; } } catch (IndexOutOfRangeException ex) { throw new FormatException("Settings must be of the form \"name=value\".", ex); } throw new FormatException("Could not parse the connection string."); } } }``` Allow access to standalone queue storage
```c# using System; using System.IO; using System.Linq; namespace LightBlue.Standalone { public class StandaloneAzureStorage : IAzureStorage { public const string DevelopmentAccountName = "dev"; private readonly string _storageAccountDirectory; public StandaloneAzureStorage(string connectionString) { var storageAccountName = ExtractAccountName(connectionString); _storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName); Directory.CreateDirectory(_storageAccountDirectory); } public IAzureBlobStorageClient CreateAzureBlobStorageClient() { return new StandaloneAzureBlobStorageClient(_storageAccountDirectory); } public IAzureQueueStorageClient CreateAzureQueueStorageClient() { return new StandaloneAzureQueueStorageClient(_storageAccountDirectory); } private static string ExtractAccountName(string connectionString) { try { var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]); if (valuePairs.ContainsKey("accountname")) { return valuePairs["accountname"]; } if (valuePairs.ContainsKey("usedevelopmentstorage")) { return DevelopmentAccountName; } } catch (IndexOutOfRangeException ex) { throw new FormatException("Settings must be of the form \"name=value\".", ex); } throw new FormatException("Could not parse the connection string."); } } }```
8cf2a61c-99ae-4792-9612-a56c273dc5ff
{ "language": "C#" }
```c# using System; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.DynamoDB.Tests { public class TriggerGroupGetTests { IJobStore _sut; public TriggerGroupGetTests() { _sut = new JobStore(); var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler(); var loadHelper = new SimpleTypeLoadHelper(); _sut.Initialize(loadHelper, signaler); } } } ``` Add failing test for get paused trigger groups
```c# using System; using Quartz.Simpl; using Quartz.Spi; using Xunit; namespace Quartz.DynamoDB.Tests { public class TriggerGroupGetTests { IJobStore _sut; public TriggerGroupGetTests() { _sut = new JobStore(); var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler(); var loadHelper = new SimpleTypeLoadHelper(); _sut.Initialize(loadHelper, signaler); } /// <summary> /// Get paused trigger groups returns one record. /// </summary> [Fact] [Trait("Category", "Integration")] public void GetPausedTriggerGroupReturnsOneRecord() { //create a trigger group by calling for it to be paused. string triggerGroup = Guid.NewGuid().ToString(); _sut.PauseTriggers(Quartz.Impl.Matchers.GroupMatcher<TriggerKey>.GroupEquals(triggerGroup)); var result = _sut.GetPausedTriggerGroups(); Assert.True(result.Contains(triggerGroup)); } } } ```
e2d68765-84e7-47c4-8244-2f3eea27d468
{ "language": "C#" }
```c# using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { public TransparentForm() { InitializeComponent(); DoubleBuffered = true; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl); TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & w positions, used to invalidate } } ``` Hide the form in the taskbar
```c# using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { public TransparentForm() { InitializeComponent(); DoubleBuffered = true; ShowInTaskbar = false; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl); TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & w positions, used to invalidate } } ```
06d8525b-98e4-4394-a6a5-43eac5485bd7
{ "language": "C#" }
```c# namespace Novell.Directory.Ldap { /// <summary> /// Extension Methods for <see cref="ILdapConnection"/> to /// avoid bloating that interface. /// </summary> public static class LdapConnectionExtensionMethods { /// <summary> /// Get some common Attributes from the Root DSE. /// This is really just a specialized <see cref="LdapSearchRequest"/> /// to handle getting some commonly requested information. /// </summary> public static RootDseInfo GetRootDseInfo(this ILdapConnection conn) { var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "supportedExtension" }, false); if (searchResults.HasMore()) { var sr = searchResults.Next(); return new RootDseInfo(sr); } return null; } } } ``` Add "+" to attributes to fetch since ApacheDS doesn't return all on * and AD doesn't return anything on +
```c# namespace Novell.Directory.Ldap { /// <summary> /// Extension Methods for <see cref="ILdapConnection"/> to /// avoid bloating that interface. /// </summary> public static class LdapConnectionExtensionMethods { /// <summary> /// Get some common Attributes from the Root DSE. /// This is really just a specialized <see cref="LdapSearchRequest"/> /// to handle getting some commonly requested information. /// </summary> public static RootDseInfo GetRootDseInfo(this ILdapConnection conn) { var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "+", "supportedExtension" }, false); if (searchResults.HasMore()) { var sr = searchResults.Next(); return new RootDseInfo(sr); } return null; } } } ```
c0189e01-659c-4a8c-89b2-46749ad8e732
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eco { /// <summary> /// Eco configuration library supports string varibales. /// You can enable variables in your configuration file by adding 'public variable[] variables;' /// field to your root configuration type. /// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}. /// /// Variable's value can reference another variable. In this case variable value is expanded recursively. /// Eco library throws an exception if a circular variable dendency is detected. /// </summary> [Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")] public class variable { [Required, Doc("Name of the varible. Can contain 'word' characters only.")] public string name; [Required, Doc("Variable's value.")] public string value; } } ``` Update the 'name' field description
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eco { /// <summary> /// Eco configuration library supports string varibales. /// You can enable variables in your configuration file by adding 'public variable[] variables;' /// field to your root configuration type. /// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}. /// /// Variable's value can reference another variable. In this case variable value is expanded recursively. /// Eco library throws an exception if a circular variable dendency is detected. /// </summary> [Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")] public class variable { [Required, Doc("Name of the varible. Can contain 'word' characters only (ie [A-Za-z0-9_]).")] public string name; [Required, Doc("Variable's value.")] public string value; } } ```
34e91d16-1cd9-4ed5-acef-1f1b6ee59f2e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Adaptive.Aeron { internal class ActiveSubscriptions : IDisposable { private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>(); public void ForEach(int streamId, Action<Subscription> handler) { List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { subscriptions.ForEach(handler); } } public void Add(Subscription subscription) { List<Subscription> subscriptions; if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions)) { subscriptions = new List<Subscription>(); _subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions; } subscriptions.Add(subscription); } public void Remove(Subscription subscription) { int streamId = subscription.StreamId(); var subscriptions = _subscriptionsByStreamIdMap[streamId]; if (subscriptions.Remove(subscription) && subscriptions.Count == 0) { _subscriptionsByStreamIdMap.Remove(streamId); } } public void Dispose() { var subscriptions = from subs in _subscriptionsByStreamIdMap.Values from subscription in subs select subscription; foreach (var subscription in subscriptions) { subscription.Dispose(); } } } }``` Deal with case of removing a Subscription that has been previously removed (06624d)
```c# using System; using System.Collections.Generic; using System.Linq; namespace Adaptive.Aeron { internal class ActiveSubscriptions : IDisposable { private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>(); public void ForEach(int streamId, Action<Subscription> handler) { List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { subscriptions.ForEach(handler); } } public void Add(Subscription subscription) { List<Subscription> subscriptions; if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions)) { subscriptions = new List<Subscription>(); _subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions; } subscriptions.Add(subscription); } public void Remove(Subscription subscription) { int streamId = subscription.StreamId(); List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { if (subscriptions.Remove(subscription) && subscriptions.Count == 0) { _subscriptionsByStreamIdMap.Remove(streamId); } } } public void Dispose() { var subscriptions = from subs in _subscriptionsByStreamIdMap.Values from subscription in subs select subscription; foreach (var subscription in subscriptions) { subscription.Dispose(); } } } }```
170e8505-d160-4716-8079-d4885dc62992
{ "language": "C#" }
```c# using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = false }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } } ``` Fix to allow plugin to start up disabled as default
```c# using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = metadata.Disabled }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } } ```
25765835-399f-4c0a-85b1-f49a12ae058f
{ "language": "C#" }
```c# using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } } ``` Add OrderingDomainException when the order doesn't exist with id orderId
```c# using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using Ordering.Domain.Exceptions; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId) ?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}"); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } } ```
3e728f4d-8ea4-4189-b3d3-1b58a92ec7d0
{ "language": "C#" }
```c# using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null && right == null) { return true; } if (left == null && right != null || left != null && right == null) { return false; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } } ``` Check if tree is mirror. Improved logics.
```c# using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null || right == null) { return left == null && right == null; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } } ```
b2b11d03-c256-40ef-876a-0b0c8d269415
{ "language": "C#" }
```c# namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Equal(797, forms.Length); using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } } ``` Update test for possible sizes
```c# namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Contains(new[] { 344, 797 }, forms.Length); // 797 on Mac, 344 on Ubuntu using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } } ```
69255dd1-1826-42aa-a591-1d75c6dc66e5
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } // TODO: Remove the below if statement once SourceBasedTestDiscoveryIncrementalAnalyzer has been switched to UnitTestingIncrementalAnalyzer if (incrementalAnalyzer.GetType().FullName == "Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.SourceBasedTestDiscoveryIncrementalAnalyzer") { return BackgroundAnalysisScope.FullSolution; } return defaultBackgroundAnalysisScope; } } } ``` Revert the hard coded name check for SBD incremental analyzer as unit test team has moved to IUnitTestingIncrementalAnalyzer
```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.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } return defaultBackgroundAnalysisScope; } } } ```
b263fe6d-eacc-4364-a49e-5d15880cd1dc
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.c6b5bf2a")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")] ``` Update Messages to correct location
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.5b2eaa85")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")] ```
aa604bb8-7a00-4de5-98e7-610829fb6862
{ "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.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public bool NewCombo { get; set; } public int ComboOffset { get; set; } } } ``` Fix catch spinners not being allowed for conversion
```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.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasXPosition, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public float X => 256; // Required for CatchBeatmapConverter public bool NewCombo { get; set; } public int ComboOffset { get; set; } } } ```
202b8d55-5a1c-4d80-993d-f8a2ba9cd66e
{ "language": "C#" }
```c# namespace InfoCarrier.Core.Client.Query.Internal { using System; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } } }``` Disable unwanted lazy loading during query execution
```c# namespace InfoCarrier.Core.Client.Query.Internal { using System; using Common; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } public override void StartTracking(object entity, EntityTrackingInfo entityTrackingInfo) { using (new PropertyLoadController(this.ServerContext.DataContext, enableLoading: false)) { base.StartTracking(entity, entityTrackingInfo); } } } }```
0a7b5203-2fa8-4955-a077-bc4e24d8a56a
{ "language": "C#" }
```c# using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }``` Apply SqliteForeignKeyIndexConvention right after the ForeignKeyIndexConvetion.
```c# using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using SQLite.CodeFirst.Convention; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); modelBuilder.Conventions.AddAfter<ForeignKeyIndexConvention>(new SqliteForeignKeyIndexConvention()); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }```
d777cca9-b3ff-453f-a096-d299c62c9188
{ "language": "C#" }
```c# using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Yaml", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } }``` Fix incorrect project file type description
```c# using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Meta File", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } } ```
600e2c29-7de2-4900-b372-88d107a6a5c4
{ "language": "C#" }
```c# @inject BTCPayServer.Security.ContentSecurityPolicies csp @{ Layout = null; csp.Add("script-src", "https://cdn.jsdelivr.net"); csp.Add("worker-src", "blob:"); } <!DOCTYPE html> <html> <head> <title>BTCPay Server Greenfield API</title> <!-- needed for adaptive design --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true"> <link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true"> <!-- ReDoc doesn't change outer page styles --> <style> body { margin: 0; padding: 0; } </style> </head> <body> @*Ignore this, this is for making the test ClickOnAllSideMenus happy*@ <div class="navbar-brand" style="visibility:collapse;"></div> <redoc spec-url="@Url.ActionLink("Swagger")"></redoc> <script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script> </body> </html> ``` Make CSP more specific for docs
```c# @inject BTCPayServer.Security.ContentSecurityPolicies csp @{ Layout = null; csp.Add("script-src", "https://cdn.jsdelivr.net"); csp.Add("worker-src", "blob: self"); } <!DOCTYPE html> <html> <head> <title>BTCPay Server Greenfield API</title> <!-- needed for adaptive design --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true"> <link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true"> <!-- ReDoc doesn't change outer page styles --> <style> body { margin: 0; padding: 0; } </style> </head> <body> @*Ignore this, this is for making the test ClickOnAllSideMenus happy*@ <div class="navbar-brand" style="visibility:collapse;"></div> <redoc spec-url="@Url.ActionLink("Swagger")"></redoc> <script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script> </body> </html> ```
4e4bdf0f-e743-4386-87be-4476835a24ed
{ "language": "C#" }
```c# using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } } ``` Fix a typo in a view
```c# using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } } ```
1acbb819-edfc-45a5-bf1a-df2c46beb85e
{ "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.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !verify.HiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) verify.HiddenIssueTypes.Add(issueType); else verify.HiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } } ``` Use local bound copy for `HiddenIssueTypes`
```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.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { var hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy(); foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !hiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) hiddenIssueTypes.Add(issueType); else hiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } } ```
1260ca81-059e-4f33-9df6-81b0d5869ed0
{ "language": "C#" }
```c# namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } bool IsValid(); string ToString(); } } ``` Revert "Added method to perform validity check for effect parameters"
```c# namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } string ToString(); } } ```
3b9da6cc-c9ce-4ed1-9229-f12570c2ffdd
{ "language": "C#" }
```c# using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; private string lastMapSearchString = ""; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); } public void CreateTokens(MapSearchResult map) { if (map.Action == OsuStatus.Playing) { if (lastMapSearchString == map.MapSearchString) Retrys++; else Plays++; lastMapSearchString = map.MapSearchString; } _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }``` Refactor plays/retries counting using osu events
```c# using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); UpdateTokens(); } public void CreateTokens(MapSearchResult map) { //ignore replays/spect if (map.Action != OsuStatus.Playing) return; switch (map.SearchArgs.EventType) { case OsuEventType.SceneChange: case OsuEventType.MapChange: Plays++; break; case OsuEventType.PlayChange: Retrys++; break; } UpdateTokens(); } private void UpdateTokens() { _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }```
3b24a386-f760-4b65-b5a5-8432027a59c2
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; 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.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } } } ``` Clear all transforms of catcher trail sprite before returned to pool
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; 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.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } } ```
8357b005-32df-4889-bb0d-fc94ff3cf77d
{ "language": "C#" }
```c# using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: first"); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: container"); } } } }``` Remove test on argument null exception message
```c# using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } } }```
2ad0c001-96ff-4c7a-8698-6a9ee1abdd5f
{ "language": "C#" }
```c# namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } } }``` Add option to install command
```c# namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } [Option('u', "skipUnnecessaryFiles", HelpText = "Skip unnecessary files to speed up installation", DefaultValue = AttachDatabasesDefault)] public override bool? SkipUnnecessaryFiles { get; set; } } }```
39ef758c-383f-4ff0-94cb-caec6967125a
{ "language": "C#" }
```c# using System; namespace Marten.Services { public class ConcurrentUpdateException : Exception { public ConcurrentUpdateException(Exception innerException) : base("Write collission detected while commiting the transaction.", innerException) { } } }``` Fix spelling mistake, 'collission' => 'collision'
```c# using System; namespace Marten.Services { public class ConcurrentUpdateException : Exception { public ConcurrentUpdateException(Exception innerException) : base("Write collision detected while commiting the transaction.", innerException) { } } } ```
ba4dddc9-16b3-4e7b-965d-658fe258d374
{ "language": "C#" }
```c# using Microsoft.Extensions.DependencyInjection; using System; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } } ``` Add Nesting ServiceCollection Extension method overloads
```c# using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { return AddNestedServices<string>( rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices ); } public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) => AddNestedServices<T>(rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices); public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, IEqualityComparer<string> keyComparer, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } } ```
47e733bd-6cea-4ef1-9bd7-8295620909b6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } } } ``` Add Int.To(Int) Method, which allow to generate a sequence between two numbers.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } public static IEnumerable<int> To(this int n, int to) { if (n == to) { yield return n; } else if (to > n) { for (int i = n; i < to; ++i) yield return i; } else { for (int i = n; i > to; --i) yield return i; } } } } ```
057f3ffd-fd09-4655-a762-abe627625957
{ "language": "C#" }
```c# @model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '#copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div id="copy-@Model.CopyId" class="@(UserHelper.IsAdmin ? "admin" : "") copy-block"> @Html.Raw(Model.CopyBody) </div> </div> ``` Copy Updates Other Copy elements of the Same Type on the Same Page When Saving
```c# @model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '.copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); $('.copy-@(Model.CopyId)').html(ed.getContent()); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div class="@(UserHelper.IsAdmin ? "admin" : "") copy-@Model.CopyId copy-block"> @Html.Raw(Model.CopyBody) </div> </div> ```
f63f9aa6-3e8f-49a5-a780-24c6648c629f
{ "language": "C#" }
```c# #tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Build") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "../../nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);``` Fix output path for nuget package.
```c# #tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Clean") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);```
42ca8215-c6d1-4cc6-b2ef-2d3d38e80228
{ "language": "C#" }
```c# using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = 500, int stackTraceDepth = 10, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }``` Change extension method default parameters to use constants
```c# using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = GraylogSinkOptions.DefaultShortMessageMaxLength, int stackTraceDepth = GraylogSinkOptions.DefaultStackTraceDepth, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }```
608126c2-d187-484d-ba93-a6763e8d293d
{ "language": "C#" }
```c# using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }``` Optimize away empty string literals.
```c# using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { if (string.IsNullOrEmpty(node.LiteralContent)) return; LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }```
250471a3-dad5-43ee-935b-970428c2ce9c
{ "language": "C#" }
```c# using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); _pressedButtons.Add(e.KeyValue); } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } } ``` Add ability to enter commands
```c# using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); private bool _isKeyStrokeEnabled = false; public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { //key command ended, start new one if (_pressedButtons.Count == 0) { _isKeyStrokeEnabled = false; } if (_isKeyStrokeEnabled) { tbCommand.Text += "-"; } else { if (tbCommand.Text.Length > 0) tbCommand.Text += ","; } tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); tbCommand.SelectionStart = tbCommand.Text.Length; _pressedButtons.Add(e.KeyValue); } else { if (_pressedButtons.Last() == e.KeyValue) { _isKeyStrokeEnabled = true; } } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } } ```
960f4afa-d549-45e7-beed-f6542645ed2c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { yield return new TerminalGremlinStep( "values", this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToImmutableList()); } } }``` Make one of two red tests green by implementing basic support for the Values-method with Id-Property.
```c# using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { var keys = this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToArray(); var numberOfIdSteps = keys .OfType<T>() .Count(x => x == T.Id); var propertyKeys = keys .OfType<string>() .Cast<object>() .ToArray(); if (numberOfIdSteps > 1 || (numberOfIdSteps > 0 && propertyKeys.Length > 0)) throw new NotSupportedException(); if (numberOfIdSteps > 0) yield return new TerminalGremlinStep("id"); else { yield return new TerminalGremlinStep( "values", propertyKeys .ToImmutableList()); } } } }```
6cf765df-cf8d-4b44-8fbe-baeb886db1f7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); return vector; } } } ``` Make it configurable if high or low throws.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public bool lowToThrow { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); vector.Add((byte)(lowToThrow ? 1 : 0)); return vector; } } } ```
122f3c20-a773-49a7-87e3-c0bdfa0313ab
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } } private void Start() { text = GetComponent<Text>(); if (game != null) { HandleGameStateChanged(null, null); } } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } } ``` Fix status text not updating upon reset
```c# using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Start() { text = GetComponent<Text>(); UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } } ```
2c53a0cc-ddd9-49e9-a8df-14ebe73da75a
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { Text text; GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Start() { text = GetComponent<Text>(); UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } } ``` Fix null error on status text initialization
```c# using UnityEngine; using UnityEngine.UI; /// <summary> /// Attach this to the status text game object /// </summary> public class StatusText : MonoBehaviour { GlobalGame game; public GlobalGame Game { get { return game; } set { if (game != null) { game.WinnerChanged -= HandleGameStateChanged; game.TurnChanged -= HandleGameStateChanged; } game = value; if (game != null) { game.WinnerChanged += HandleGameStateChanged; game.TurnChanged += HandleGameStateChanged; } UpdateState(); } } void UpdateState() { HandleGameStateChanged(game, null); } private void Awake() { UpdateState(); } public void HandleGameStateChanged(object o, GameEventArgs e) { Text text = GetComponent<Text>(); if (game == null) { text.text = ""; return; } if (game.GameOver()) { if (game.Winner != null) { text.text = game.Winner.Name + " wins!"; return; } text.text = "Tie game"; return; } text.text = game.ActivePlayer().Name + "'s turn"; } } ```
4a14bfe8-d025-40ca-9020-3f5496c65b26
{ "language": "C#" }
```c# using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr") .Select(row => ParseRow(row)) .ToList(); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } } ``` Add service alert for app update notice
```c# using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr") .Select(row => ParseRow(row)) .ToList(); alerts.Insert(0, new ServiceAlert( title: "App Update for Upcoming CTS Schedule", publishDate: "2019-09-09T00:00:00-07:00", link: "https://rikkigibson.github.io/corvallisbus")); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } } ```
0a737e64-0b89-42f5-a2db-be80e54c8608
{ "language": "C#" }
```c# using System; using DesktopWidgets.Properties; namespace DesktopWidgets.Helpers { public static class DoubleHelper { public static bool IsEqual(this double val1, double val2) => double.IsNaN(val1) || double.IsNaN(val1) || (Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance); } }``` Fix NaN floating point comparison
```c# using System; using DesktopWidgets.Properties; namespace DesktopWidgets.Helpers { public static class DoubleHelper { public static bool IsEqual(this double val1, double val2) => double.IsNaN(val1) || double.IsNaN(val2) || (Math.Abs(val1 - val2) > Settings.Default.DoubleComparisonTolerance); } }```
4643a05a-46b9-4ddc-aec4-dabe53548b7b
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Specialized; using System.Text; namespace TweetDuck.Core.Other.Analytics{ sealed class AnalyticsReport : IEnumerable{ private OrderedDictionary data = new OrderedDictionary(32); private int separators; public void Add(int ignored){ // adding separators to pretty print data.Add((++separators).ToString(), null); } public void Add(string key, string value){ data.Add(key, value); } public AnalyticsReport FinalizeReport(){ if (!data.IsReadOnly){ data = data.AsReadOnly(); } return this; } public IEnumerator GetEnumerator(){ return data.GetEnumerator(); } public NameValueCollection ToNameValueCollection(){ NameValueCollection collection = new NameValueCollection(); foreach(DictionaryEntry entry in data){ if (entry.Value != null){ collection.Add((string)entry.Key, (string)entry.Value); } } return collection; } public override string ToString(){ StringBuilder build = new StringBuilder(); foreach(DictionaryEntry entry in data){ if (entry.Value == null){ build.AppendLine(); } else{ build.AppendLine(entry.Key+": "+entry.Value); } } return build.ToString(); } } } ``` Tweak key format in analytics request
```c# using System.Collections; using System.Collections.Specialized; using System.Text; namespace TweetDuck.Core.Other.Analytics{ sealed class AnalyticsReport : IEnumerable{ private OrderedDictionary data = new OrderedDictionary(32); private int separators; public void Add(int ignored){ // adding separators to pretty print data.Add((++separators).ToString(), null); } public void Add(string key, string value){ data.Add(key, value); } public AnalyticsReport FinalizeReport(){ if (!data.IsReadOnly){ data = data.AsReadOnly(); } return this; } public IEnumerator GetEnumerator(){ return data.GetEnumerator(); } public NameValueCollection ToNameValueCollection(){ NameValueCollection collection = new NameValueCollection(); foreach(DictionaryEntry entry in data){ if (entry.Value != null){ collection.Add(((string)entry.Key).ToLower().Replace(' ', '_'), (string)entry.Value); } } return collection; } public override string ToString(){ StringBuilder build = new StringBuilder(); foreach(DictionaryEntry entry in data){ if (entry.Value == null){ build.AppendLine(); } else{ build.AppendLine(entry.Key+": "+entry.Value); } } return build.ToString(); } } } ```
898027dd-0c77-4147-a51d-9c6e349d207b
{ "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.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator2.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator2.ppy.sh/multiplayer"; } } } ``` Update spectator/multiplayer endpoint in line with new deployment
```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.Game.Online { public class ProductionEndpointConfiguration : EndpointConfiguration { public ProductionEndpointConfiguration() { WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh"; APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk"; APIClientID = "5"; SpectatorEndpointUrl = "https://spectator.ppy.sh/spectator"; MultiplayerEndpointUrl = "https://spectator.ppy.sh/multiplayer"; } } } ```
53d90c2b-e11e-4779-97b8-db00418a8f87
{ "language": "C#" }
```c# @using JoinRpg.Web.Models @model CharacterDetailsViewModel <div> @Html.Partial("CharacterNavigation", Model.Navigation) @* TODO: Жесточайше причесать эту страницу*@ <dl class="dl-horizontal"> <dt>Игрок</dt> <dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd> <dt>@Html.DisplayNameFor(model => model.Description)</dt> <dd>@Html.DisplayFor(model => model.Description)</dd> <dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt> <dd>@Html.DisplayFor(model => model.ParentGroups)</dd> </dl> <h4>Поля персонажа</h4> <div class="form-horizontal"> @Html.Partial("_EditFieldsPartial", Model.Fields) </div> @Html.Partial("_PlotForCharacterPartial", Model.Plot) </div> ``` Hide character fields header if no fields
```c# @using JoinRpg.Web.Models @model CharacterDetailsViewModel <div> @Html.Partial("CharacterNavigation", Model.Navigation) @* TODO: Жесточайше причесать эту страницу*@ <dl class="dl-horizontal"> <dt>Игрок</dt> <dd>@Html.DisplayFor(model => model, "IPlayerCharacter")</dd> <dt>@Html.DisplayNameFor(model => model.Description)</dt> <dd>@Html.DisplayFor(model => model.Description)</dd> <dt>@Html.DisplayNameFor(model => model.ParentGroups)</dt> <dd>@Html.DisplayFor(model => model.ParentGroups)</dd> </dl> @if (Model.Fields.CharacterFields.Any()) { <h4>Поля персонажа</h4> <div class="form-horizontal"> @Html.Partial("_EditFieldsPartial", Model.Fields) </div> } @Html.Partial("_PlotForCharacterPartial", Model.Plot) </div> ```
1b22e336-8c37-4649-8401-40b983eddcd5
{ "language": "C#" }
```c# using static System.Console; using CIV.Ccs; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } } ``` Add CIV.Interfaces reference in Main
```c# using static System.Console; using CIV.Ccs; using CIV.Interfaces; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } } ```
0c656b80-d038-4e63-a1a5-52ab9cb4f594
{ "language": "C#" }
```c# using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { static Bootstrapper() { Init(); } public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .Where(c=>c.Name.EndsWith("Controller")) .AsSelf(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }``` Revert "Revert "registration of api controllers fixed""
```c# using System.Reflection; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }```
174d7620-9654-4008-a66e-30641c23f1b6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecurringDates { public static class Extensions { public static SetUnionRule Or(this IRule first, params IRule[] otherRules) { return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)}; } public static SetIntersectionRule And(this IRule first, params IRule[] otherRules) { return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) }; } public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule) { return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule }; } public static NotRule Not(this IRule rule) { return new NotRule { ReferencedRule = rule }; } public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence) { return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule}; } public static MonthsFilterRule InMonths(this IRule rule, params Month[] months) { return new MonthsFilterRule { Months = months, ReferencedRule = rule }; } } } ``` Add new fluent syntax: DayOfWeek.Monday.EveryWeek()
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecurringDates { public static class Extensions { public static SetUnionRule Or(this IRule first, params IRule[] otherRules) { return new SetUnionRule {Rules = new[] {first}.Concat(otherRules)}; } public static SetIntersectionRule And(this IRule first, params IRule[] otherRules) { return new SetIntersectionRule { Rules = new[] { first }.Concat(otherRules) }; } public static SetDifferenceRule Except(this IRule includeRule, IRule excludeRule) { return new SetDifferenceRule { IncludeRule = includeRule , ExcludeRule = excludeRule }; } public static NotRule Not(this IRule rule) { return new NotRule { ReferencedRule = rule }; } public static NthInMonthRule NthInMonth(this IRule rule, int nthOccurrence) { return new NthInMonthRule {Nth = nthOccurrence, ReferencedRule = rule}; } public static MonthsFilterRule InMonths(this IRule rule, params Month[] months) { return new MonthsFilterRule { Months = months, ReferencedRule = rule }; } public static DayOfWeekRule EveryWeek(this DayOfWeek dow) { return new DayOfWeekRule(dow); } } } ```
abc3908a-f4c3-4d29-9a98-15a14e8794a4
{ "language": "C#" }
```c# using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Core.Noark5; using Arkivverket.Arkade.Identify; using Arkivverket.Arkade.Logging; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<TestSessionFactory>().AsSelf(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance(); builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>(); builder.RegisterType<TestProvider>().As<ITestProvider>(); builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance(); builder.RegisterType<Noark5TestProvider>().AsSelf(); } } } ``` Add missing dependencies to autofac module
```c# using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Core.Addml; using Arkivverket.Arkade.Core.Noark5; using Arkivverket.Arkade.Identify; using Arkivverket.Arkade.Logging; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<AddmlDatasetTestEngine>().AsSelf(); builder.RegisterType<AddmlProcessRunner>().AsSelf(); builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<FlatFileReaderFactory>().AsSelf(); builder.RegisterType<Noark5TestEngine>().AsSelf().SingleInstance(); builder.RegisterType<Noark5TestProvider>().AsSelf(); builder.RegisterType<StatusEventHandler>().As<IStatusEventHandler>().SingleInstance(); builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<TestEngineFactory>().AsSelf(); builder.RegisterType<TestProvider>().As<ITestProvider>(); builder.RegisterType<TestSessionFactory>().AsSelf(); } } } ```
586b5629-e2b4-4632-ad6d-e0c07ec7ef48
{ "language": "C#" }
```c# // // Copyright 2019 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 NUnit.Framework; using System.Diagnostics; namespace Google.Solutions.IapDesktop.Application.Test { public abstract class FixtureBase { [SetUp] public void SetUpTracing() { TraceSources.IapDesktop.Listeners.Add(new ConsoleTraceListener()); TraceSources.IapDesktop.Switch.Level = SourceLevels.Verbose; } } } ``` Enable tracing for IAP code
```c# // // Copyright 2019 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 NUnit.Framework; using System.Diagnostics; namespace Google.Solutions.IapDesktop.Application.Test { public abstract class FixtureBase { private static TraceSource[] Traces = new[] { Google.Solutions.Compute.TraceSources.Compute, Google.Solutions.IapDesktop.Application.TraceSources.IapDesktop }; [SetUp] public void SetUpTracing() { var listener = new ConsoleTraceListener(); foreach (var trace in Traces) { trace.Listeners.Add(listener); trace.Switch.Level = System.Diagnostics.SourceLevels.Verbose; } } } } ```
b79dc0ac-ff86-40be-93b1-060b82a84bad
{ "language": "C#" }
```c# using Blogifier.Core.Common; using Blogifier.Core.Data.Domain; using Blogifier.Core.Data.Interfaces; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Blogifier.Core.Services.Social { public class SocialService : ISocialService { IUnitOfWork _db; public SocialService(IUnitOfWork db) { _db = db; } public Task<Dictionary<string, string>> GetSocialButtons(Profile profile) { var buttons = ApplicationSettings.SocialButtons; if(profile != null) { // override with profile customizations var dbFields = _db.CustomFields.Find(f => f.CustomType == CustomType.Profile && f.ParentId == profile.Id); if (dbFields != null && dbFields.Count() > 0) { foreach (var field in dbFields) { if (buttons.ContainsKey(field.CustomKey)) { buttons[field.CustomKey] = field.CustomValue; } } } } return Task.Run(()=> buttons); } } } ``` Fix social buttons not copying setting valus
```c# using Blogifier.Core.Common; using Blogifier.Core.Data.Domain; using Blogifier.Core.Data.Interfaces; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Blogifier.Core.Services.Social { public class SocialService : ISocialService { IUnitOfWork _db; public SocialService(IUnitOfWork db) { _db = db; } public Task<Dictionary<string, string>> GetSocialButtons(Profile profile) { var buttons = new Dictionary<string, string>(); foreach (var item in ApplicationSettings.SocialButtons) { buttons.Add(item.Key, item.Value); } if(profile != null) { // override with profile customizations var dbFields = _db.CustomFields.Find(f => f.CustomType == CustomType.Profile && f.ParentId == profile.Id); if (dbFields != null && dbFields.Count() > 0) { foreach (var field in dbFields) { if (buttons.ContainsKey(field.CustomKey)) { buttons[field.CustomKey] = field.CustomValue; } } } } return Task.Run(()=> buttons); } } } ```
328db394-7d12-4dea-968f-1ed874ff3423
{ "language": "C#" }
```c# // SampSharp // Copyright 2022 Tim Potze // // 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. namespace SampSharp.Entities.SAMP; /// <summary>Represents a system for handling dialog functionality</summary> public class DialogSystem : ISystem { [Event] // ReSharper disable once UnusedMember.Local private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _) { player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null)); } [Event] // ReSharper disable once UnusedMember.Local private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText) { if (dialogId != DialogService.DialogId) return; // Prevent dialog hacks player.ResponseReceived = true; player.Handler(new DialogResult(response == 1 ? DialogResponse.LeftButton : DialogResponse.RightButtonOrCancel, listItem, inputText)); } }``` Fix issues related to open dialogs when a player disconnects
```c# // SampSharp // Copyright 2022 Tim Potze // // 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. namespace SampSharp.Entities.SAMP; /// <summary>Represents a system for handling dialog functionality</summary> public class DialogSystem : ISystem { [Event] // ReSharper disable once UnusedMember.Local private void OnPlayerDisconnect(VisibleDialog player, DisconnectReason _) { player.ResponseReceived = true; player.Handler(new DialogResult(DialogResponse.Disconnected, 0, null)); } [Event] // ReSharper disable once UnusedMember.Local private void OnDialogResponse(VisibleDialog player, int dialogId, int response, int listItem, string inputText) { if (dialogId != DialogService.DialogId) return; // Prevent dialog hacks player.ResponseReceived = true; player.Handler(new DialogResult(response == 1 ? DialogResponse.LeftButton : DialogResponse.RightButtonOrCancel, listItem, inputText)); player.Destroy(); } }```
a04ec86f-847d-421c-a58b-8959252df8b8
{ "language": "C#" }
```c# using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC")] ``` Add missing ARC runtime linker flag
```c# using System; using MonoTouch.ObjCRuntime; [assembly: LinkWith ("PSPDFKit.a", LinkTarget.ArmV7s | LinkTarget.ArmV7 | LinkTarget.Simulator, ForceLoad = true, IsCxx = true, Frameworks = "MediaPlayer CoreText QuartzCore MessageUI ImageIO CoreMedia CoreGraphics AVFoundation", LinkerFlags = "-lz -ObjC -fobjc-arc")] ```
636e9253-b556-4277-909c-2448bc932823
{ "language": "C#" }
```c# using System.Reflection; using Funq; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using SimpleEventMonitor.Core; namespace SimpleEventMonitor.Web { public class AppHostSimpleEventMonitor : AppHostBase { public AppHostSimpleEventMonitor(IEventDataStore dataStore) : base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly()) { Container.Register(dataStore); } public override void Configure(Container container) { JsConfig.IncludeNullValues = true; SetConfig( new EndpointHostConfig { DebugMode = true, DefaultContentType = ContentType.Json, EnableFeatures = Feature.All }); } } }``` Debug mode only enabled for Debug Build configuration
```c# using System.Reflection; using Funq; using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using SimpleEventMonitor.Core; namespace SimpleEventMonitor.Web { public class AppHostSimpleEventMonitor : AppHostBase { public AppHostSimpleEventMonitor(IEventDataStore dataStore) : base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly()) { Container.Register(dataStore); } public override void Configure(Container container) { #if DEBUG bool debug = true; var enableFeatures = Feature.All; #else bool debug = false; var enableFeatures = Feature.All.Remove(Feature.Metadata); #endif JsConfig.IncludeNullValues = true; SetConfig( new EndpointHostConfig { DebugMode = debug, DefaultContentType = ContentType.Json, EnableFeatures = enableFeatures }); } } }```
1df3f9af-f811-455f-b538-7e9bbc395809
{ "language": "C#" }
```c# using System; using System.Drawing.Imaging; using System.IO; using OpenQA.Selenium; namespace Selenium.WebDriver.Equip { public class TestCapture { private IWebDriver _browser = null; private string fileName; public TestCapture(IWebDriver iWebDriver, string type = "Failed") { fileName = string.Format(@"{0}\{1}.{2}", Directory.GetCurrentDirectory(), DateTime.Now.Ticks, type); _browser = iWebDriver; } public void CaptureWebPage() { WebDriverLogsLogs(); PageSource(); ScreenShot(); } public void PageSource() { string htmlFile = string.Format(@"{0}.html", fileName); using (var sw = new StreamWriter(htmlFile, false)) sw.Write(_browser.PageSource); } public void ScreenShot() { _browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg); } public void WebDriverLogsLogs() { foreach (var log in _browser.Manage().Logs.AvailableLogTypes) using (var sw = new StreamWriter(string.Format(@"{0}.{1}.log", fileName, log), false)) foreach (var logentry in _browser.Manage().Logs.GetLog(log)) sw.WriteLine(logentry); } } } ``` Fix screen capture durring test failure
```c# using OpenQA.Selenium; using System; using System.IO; using System.Reflection; namespace Selenium.WebDriver.Equip { public class TestCapture { private IWebDriver _browser = null; private string fileName; public TestCapture(IWebDriver iWebDriver, string type = "Failed") { fileName = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\{DateTime.Now.Ticks}.{type}"; _browser = iWebDriver; } public void CaptureWebPage() { WebDriverLogsLogs(); PageSource(); ScreenShot(); } public void PageSource() { string htmlFile = $"{fileName}.html"; using (var sw = new StreamWriter(htmlFile, false)) sw.Write(_browser.PageSource); } public void ScreenShot() { _browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg); } public void WebDriverLogsLogs() { foreach (var log in _browser.Manage().Logs.AvailableLogTypes) using (var sw = new StreamWriter($"{fileName}.{log}.log", false)) foreach (var logentry in _browser.Manage().Logs.GetLog(log)) sw.WriteLine(logentry); } } } ```
9632c550-5977-4489-99c2-470563332e6f
{ "language": "C#" }
```c# namespace JsonDiffPatchDotNet { public sealed class Options { public Options() { ArrayDiff = ArrayDiffMode.Efficient; TextDiff = TextDiffMode.Efficient; MinEfficientTextDiffLength = 50; } public ArrayDiffMode ArrayDiff { get; set; } public TextDiffMode TextDiff { get; set; } public long MinEfficientTextDiffLength { get; set; } } } ``` Switch simple array diff to default until Efficient array diffing is implemented
```c# namespace JsonDiffPatchDotNet { public sealed class Options { public Options() { ArrayDiff = ArrayDiffMode.Simple; TextDiff = TextDiffMode.Efficient; MinEfficientTextDiffLength = 50; } public ArrayDiffMode ArrayDiff { get; set; } public TextDiffMode TextDiff { get; set; } public long MinEfficientTextDiffLength { get; set; } } } ```
8921a5d9-33ae-4a35-ac40-85c004b929ea
{ "language": "C#" }
```c# using System.Drawing; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class SeekBar : ProgressBar{ private readonly SolidBrush brush; public SeekBar(){ brush = new SolidBrush(Color.White); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } protected override void OnPaint(PaintEventArgs e){ if (brush.Color != ForeColor){ brush.Color = ForeColor; } Rectangle rect = e.ClipRectangle; rect.Width = (int)(rect.Width*((double)Value/Maximum)); e.Graphics.FillRectangle(brush, rect); } protected override void Dispose(bool disposing){ base.Dispose(disposing); if (disposing){ brush.Dispose(); } } } } ``` Add a hover effect to video player seek bar
```c# using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace TweetDuck.Video.Controls{ sealed class SeekBar : ProgressBar{ private readonly SolidBrush brushFore; private readonly SolidBrush brushHover; private readonly SolidBrush brushOverlap; public SeekBar(){ brushFore = new SolidBrush(Color.White); brushHover = new SolidBrush(Color.White); brushOverlap = new SolidBrush(Color.White); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } protected override void OnPaint(PaintEventArgs e){ if (brushFore.Color != ForeColor){ brushFore.Color = ForeColor; brushHover.Color = Color.FromArgb(128, ForeColor); brushOverlap.Color = Color.FromArgb(80+ForeColor.R*11/16, 80+ForeColor.G*11/16, 80+ForeColor.B*11/16); } Rectangle rect = e.ClipRectangle; Point cursor = PointToClient(Cursor.Position); int width = rect.Width; int progress = (int)(width*((double)Value/Maximum)); rect.Width = progress; e.Graphics.FillRectangle(brushFore, rect); if (cursor.X >= 0 && cursor.Y >= 0 && cursor.X <= width && cursor.Y <= rect.Height){ if (progress >= cursor.X){ rect.Width = cursor.X; e.Graphics.FillRectangle(brushOverlap, rect); } else{ rect.X = progress; rect.Width = cursor.X-rect.X; e.Graphics.FillRectangle(brushHover, rect); } } } protected override void Dispose(bool disposing){ base.Dispose(disposing); if (disposing){ brushFore.Dispose(); brushHover.Dispose(); brushOverlap.Dispose(); } } } } ```
8dd35e2f-62a6-46b8-a45d-4bedc6afc3be
{ "language": "C#" }
```c# using System; using System.Diagnostics; using NUnit.Framework; using Rhino.Mocks; namespace NServiceKit.Logging.Tests.Support { public class TestBase { private MockRepository mocks; protected virtual MockRepository Mocks { get { return mocks; } } [SetUp] protected virtual void SetUp() { mocks = new MockRepository(); } [TearDown] protected virtual void TearDown() { mocks = null; } protected virtual void ReplayAll() { Mocks.ReplayAll(); } protected virtual void VerifyAll() { try { Mocks.VerifyAll(); } catch (InvalidOperationException ex) { Debug.Print("InvalidOperationException thrown: {0}", ex.Message); } } } }``` Reset the mocks before disposing
```c# using System; using System.Diagnostics; using NUnit.Framework; using Rhino.Mocks; namespace NServiceKit.Logging.Tests.Support { public class TestBase { private MockRepository mocks; protected virtual MockRepository Mocks { get { return mocks; } } [SetUp] protected virtual void SetUp() { mocks = new MockRepository(); } [TearDown] protected virtual void TearDown() { mocks.BackToRecordAll(); mocks = null; } protected virtual void ReplayAll() { Mocks.ReplayAll(); } protected virtual void VerifyAll() { try { Mocks.VerifyAll(); } catch (InvalidOperationException ex) { Debug.Print("InvalidOperationException thrown: {0}", ex.Message); } } } }```
95faef24-e879-47d2-9975-5a872fe4e0c9
{ "language": "C#" }
```c# using System.IO; using BruTile.MbTiles; using Mapsui.Layers; using Mapsui.UI; using SQLite; namespace Mapsui.Samples.Common.Maps { public class MbTilesSample : ISample { // This is a hack used for iOS/Android deployment public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles"; public string Name => "1 MbTiles"; public string Category => "Data"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(CreateMbTilesLayer(Path.Combine(MbTilesLocation, "world.mbtiles"), "regular")); return map; } public static TileLayer CreateMbTilesLayer(string path, string name) { var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true)); var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name}; return mbTilesLayer; } } }``` Replace SQLite path for MBTiles files with full path, so that doesn't throw an exception on UWP
```c# using System.IO; using BruTile.MbTiles; using Mapsui.Layers; using Mapsui.UI; using SQLite; namespace Mapsui.Samples.Common.Maps { public class MbTilesSample : ISample { // This is a hack used for iOS/Android deployment public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles"; public string Name => "1 MbTiles"; public string Category => "Data"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(CreateMbTilesLayer(Path.GetFullPath(Path.Combine(MbTilesLocation, "world.mbtiles")), "regular")); return map; } public static TileLayer CreateMbTilesLayer(string path, string name) { var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true)); var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name}; return mbTilesLayer; } } }```
4929b3e3-3c77-4c92-9372-80256c851421
{ "language": "C#" }
```c# // Copyright 2019 Google LLC // // 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 // // https://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; namespace Google.Cloud.Redis.V1Beta1.SmokeTests { public class CloudRedisClientSmokeTest { public static int Main(string[] args) { var client = CloudRedisClient.Create(); var locationName = new LocationName(args[0], "-"); var instances = client.ListInstances(locationName); foreach (var instance in instances) { Console.WriteLine(instance.Name); } // Success Console.WriteLine("Smoke test passed OK"); return 0; } } } ``` Fix smoke test to use common LocationName
```c# // Copyright 2019 Google LLC // // 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 // // https://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; using Google.Api.Gax.ResourceNames; namespace Google.Cloud.Redis.V1Beta1.SmokeTests { public class CloudRedisClientSmokeTest { public static int Main(string[] args) { var client = CloudRedisClient.Create(); var locationName = new LocationName(args[0], "-"); var instances = client.ListInstances(locationName); foreach (var instance in instances) { Console.WriteLine(instance.Name); } // Success Console.WriteLine("Smoke test passed OK"); return 0; } } } ```
45e873c7-0f3b-4c75-b341-33f7ad582b51
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.ServerSelectionScreen)] [SceneTypeCreate(GameSceneType.PreShipSelectionScene)] [SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen. public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable { private IConnectionService ConnectionService { get; } private IGameConnectionEndpointDetails ConnectionDetails { get; } private ILog Logger { get; } /// <inheritdoc /> public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger) { ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService)); ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <inheritdoc /> public Task OnGameInitialized() { if(Logger.IsInfoEnabled) Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}"); //This initializable actually just //connects a IConnectionService with the provided game details. return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port); } } } ``` Enable auto-connection on pre-block bursting screen
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; namespace Booma.Proxy { [SceneTypeCreate(GameSceneType.PreBlockBurstingScene)] [SceneTypeCreate(GameSceneType.ServerSelectionScreen)] [SceneTypeCreate(GameSceneType.PreShipSelectionScene)] [SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen. public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable { private IConnectionService ConnectionService { get; } private IGameConnectionEndpointDetails ConnectionDetails { get; } private ILog Logger { get; } /// <inheritdoc /> public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger) { ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService)); ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <inheritdoc /> public Task OnGameInitialized() { if(Logger.IsInfoEnabled) Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}"); //This initializable actually just //connects a IConnectionService with the provided game details. return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port); } } } ```
0770f9fe-99e8-4ac6-9369-d0d36abffc56
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); } DrawDefaultInspector(); } } ``` Set MicrogameCollection dirty in editor update
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } } ```
96f0e22a-422b-4b7b-940c-cac125a9c833
{ "language": "C#" }
```c# @using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> @Html.SubmitButton("Submit", "Click here to be taken to our payment site") </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div> ``` Add a link on Credit card registrations that have not paid
```c# @using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div> ```
ac562005-39f6-469b-9e3f-2126d185b6a1
{ "language": "C#" }
```c# namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details { using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nini; using Nini.Config; using Nini.Ini; using Nini.Util; using NLog; using Reaper; using Reaper.SharpBattleNet; using Reaper.SharpBattleNet.Framework; using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer; internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer { private readonly IConfigSource _configuration = null; private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public DiabloIIRealmServer(IConfigSource configuration) { _configuration = configuration; return; } public async Task Start(string[] commandArguments) { return; } public async Task Stop() { return; } } } ``` Update D2RS to handle new networking infrastructure.
```c# namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details { using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nini; using Nini.Config; using Nini.Ini; using Nini.Util; using NLog; using Reaper; using Reaper.SharpBattleNet; using Reaper.SharpBattleNet.Framework; using Reaper.SharpBattleNet.Framework.Networking; using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer; internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer { private readonly IConfigSource _configuration = null; private readonly INetworkManager _networkManager = null; private readonly Logger _logger = LogManager.GetCurrentClassLogger(); public DiabloIIRealmServer(IConfigSource configuration, INetworkManager networkManager) { _configuration = configuration; _networkManager = networkManager; return; } public async Task Start(string[] commandArguments) { await _networkManager.StartNetworking(); return; } public async Task Stop() { await _networkManager.StopNetworking(); return; } } } ```
44ebdb1d-1237-4612-a133-e997cd2da13c
{ "language": "C#" }
```c# @model LETS.ViewModels.MemberNoticesViewModel <h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1> @if (Model.Notices.Count().Equals(0)) { <p>@T("This member doesn't have any active notices")</p> } @foreach (var notice in Model.Notices) { @Display(notice) } @{ <div id="archivedNotices"> <h2>@T("Archived notices")</h2> <p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p> <p>@T("Notices can also be archived if you don't want to delete them yet")</p> @if (Model.ArchivedNotices.Any()) { foreach (var archivedNotice in Model.ArchivedNotices) { @Display(archivedNotice) } } </div> } ``` Add edit links to noitces admin
```c# @using LETS.Helpers; @model LETS.ViewModels.MemberNoticesViewModel <h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1> @if (Model.Notices.Count().Equals(0)) { <p>@T("This member doesn't have any active notices")</p> } @foreach (var notice in Model.Notices) { var id = notice.ContentItem.Id; @Display(notice) @Html.ActionLink(T("Edit").ToString(), "Edit", "Notice", new { area = "LETS", id = id }, new { @class = "edit" }) @:| @Html.ActionLink(T("Delete").ToString(), "Delete", "Notice", new { area = "LETS", id = id }, new { @class = "edit", itemprop = "UnsafeUrl RemoveUrl" }) @:| @*var published = Helpers.IsPublished(notice.ContentPart.Id); if (published) { @Html.Link(T("Archive").Text, Url.Action("Unpublish", "Notice", new { area = "LETS", id = notice.Id }), new { @class = "edit", itemprop = "UnsafeUrl ArchiveUrl" }) } else { @Html.ActionLink(T("Publish").ToString(), "Publish", "Notice", new { area = "LETS", id = notice.Id }, new { @class = "edit", itemprop = "UnsafeUrl" }) }*@ } @{ <div id="archivedNotices"> <h2>@T("Archived notices")</h2> <p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p> <p>@T("Notices can also be archived if you don't want to delete them yet")</p> @if (Model.ArchivedNotices.Any()) { foreach (var archivedNotice in Model.ArchivedNotices) { @Display(archivedNotice) } } </div> } @Html.AntiForgeryTokenOrchard() ```