doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
6b798028-c4f0-4c32-8fbc-5816afdd789f
{ "language": "C#" }
```c#  @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--inline"> <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p> ``` Apply new css class for displaying long email addresses and other data in panel
```c#  @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--table-narrow"> <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p> ```
75b4ac89-ffe4-4213-ac56-708b2c1d57c8
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.VisualStudio.TestTools.UnitTesting; using Slp.Evi.Storage; using Slp.Evi.Storage.Bootstrap; using Slp.Evi.Storage.Database; using Slp.Evi.Storage.Database.Vendor.MsSql; namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db { [TestClass] public class MSSQLDb : TestSuite { private static Dictionary<string, EviQueryableStorage> _storages; [ClassInitialize] public static void TestSuiteInitialization(TestContext context) { _storages = new Dictionary<string, EviQueryableStorage>(); foreach (var dataset in StorageNames) { var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory()); _storages.Add(dataset, storage); } } private static ISqlDatabase GetSqlDb() { var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString; return (new MsSqlDbFactory()).CreateSqlDb(connectionString); } private static IEviQueryableStorageFactory GetStorageFactory() { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.Trace); loggerFactory.AddDebug(LogLevel.Trace); return new DefaultEviQueryableStorageFactory(loggerFactory); } protected override EviQueryableStorage GetStorage(string storageName) { return _storages[storageName]; } } } ``` Disable test debug logging in appveyor.
```c# using System; using System.Collections.Generic; using System.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.VisualStudio.TestTools.UnitTesting; using Slp.Evi.Storage; using Slp.Evi.Storage.Bootstrap; using Slp.Evi.Storage.Database; using Slp.Evi.Storage.Database.Vendor.MsSql; namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db { [TestClass] public class MSSQLDb : TestSuite { private static Dictionary<string, EviQueryableStorage> _storages; [ClassInitialize] public static void TestSuiteInitialization(TestContext context) { _storages = new Dictionary<string, EviQueryableStorage>(); foreach (var dataset in StorageNames) { var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory()); _storages.Add(dataset, storage); } } private static ISqlDatabase GetSqlDb() { var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString; return (new MsSqlDbFactory()).CreateSqlDb(connectionString); } private static IEviQueryableStorageFactory GetStorageFactory() { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.Trace); if (Environment.GetEnvironmentVariable("APPVEYOR") != "True") { loggerFactory.AddDebug(LogLevel.Trace); } return new DefaultEviQueryableStorageFactory(loggerFactory); } protected override EviQueryableStorage GetStorage(string storageName) { return _storages[storageName]; } } } ```
1e88e7f4-5c08-4fd6-8761-0e34cb2bcbab
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC"> // Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Diffbot.Client.Tests { using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DiffbotClientTest { private const string ValidApiKey = "<your api key>"; private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194"; [TestMethod, TestCategory("Integration")] public async Task DiffbotClient_GetArticle_Should_Return_an_Article() { // Arrange var client = new DiffbotClient(ValidApiKey); // Act var article = await client.GetArticle( "http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/"); // Assert Assert.IsNotNull(article); Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title); } } } ``` Add one more unit test
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC"> // Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Diffbot.Client.Tests { using System.Net.Http; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DiffbotClientTest { private const string ValidApiKey = "<your api key>"; private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194"; private const string WebPageUrl1 = "http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/"; [TestMethod, TestCategory("Integration")] public async Task DiffbotClient_GetArticle_Should_Return_an_Article() { // Arrange var client = new DiffbotClient(ValidApiKey); // Act var article = await client.GetArticle(WebPageUrl1); // Assert Assert.IsNotNull(article); Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title); } [TestMethod, TestCategory("Integration"), ExpectedException(typeof(HttpRequestException))] public async Task DiffbotClient_GetArticle_Should_Throw_an_Exception() { // Arrange var client = new DiffbotClient(InvalidApiKey); // Act await client.GetArticle(WebPageUrl1); } } } ```
4294b612-5e3f-452e-9033-7c9adb627a44
{ "language": "C#" }
```c# using System; using System.Numerics; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface IVectorProvider { Vector3 NextVector(); } public class LiteralVectorProvider : IVectorProvider { private readonly Vector3 value; public LiteralVectorProvider(Vector3 value) { this.value = value; } public LiteralVectorProvider(double[] value) { this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]); } public Vector3 NextVector() => value; } public static class IVectorProviderExtensions { public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType")) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PVEC_TYPE_LITERAL": return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); default: throw new InvalidCastException($"Could not create vector provider of type {type}."); } } return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName)); } } } ``` Support all particle vector providers that have m_vLiteralValue
```c# using System; using System.Numerics; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface IVectorProvider { Vector3 NextVector(); } public class LiteralVectorProvider : IVectorProvider { private readonly Vector3 value; public LiteralVectorProvider(Vector3 value) { this.value = value; } public LiteralVectorProvider(double[] value) { this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]); } public Vector3 NextVector() => value; } public static class IVectorProviderExtensions { public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType")) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PVEC_TYPE_LITERAL": return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); default: if (numberProviderParameters.ContainsKey("m_vLiteralValue")) { Console.Error.WriteLine($"Vector provider of type {type} is not directly supported, but it has m_vLiteralValue."); return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); } throw new InvalidCastException($"Could not create vector provider of type {type}."); } } return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName)); } } } ```
63b5cf18-6277-4240-8129-301c43eab633
{ "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; 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 & y positions, used to invalidate } } ``` Fix bug where drawn objects are also transparent, and add pen variable.
```c# using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { private Pen pen = new Pen(Color.Red, 5); public TransparentForm() { InitializeComponent(); DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); TransparencyKey = BackColor; ShowInTaskbar = false; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(pen, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & y positions, used to invalidate } } ```
1247dc57-5c92-4207-9591-c68da1b49f68
{ "language": "C#" }
```c# using System.ComponentModel.DataAnnotations; namespace LibrarySystem.Models { public class Subject { public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } } }``` Add journals and self relations.
```c# // <copyright file="Subject.cs" company="YAGNI"> // All rights reserved. // </copyright> // <summary>Holds implementation of Book model.</summary> using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace LibrarySystem.Models { /// <summary> /// Represent a <see cref="Subject"/> entity model. /// </summary> public class Subject { /// <summary> /// Child nodes of the <see cref="Subject"/> entity. /// </summary> private ICollection<Subject> subSubjects; /// <summary> /// Journal of the <see cref="Subject"/> entity. /// </summary> private ICollection<Journal> journals; /// <summary> /// Initializes a new instance of the <see cref="Subject"/> class. /// </summary> public Subject() { this.subSubjects = new HashSet<Subject>(); this.journals = new HashSet<Journal>(); } /// <summary> /// Gets or sets the primary key of the <see cref="Subject"/> entity. /// </summary> /// <value>Primary key of the <see cref="Subject"/> entity.</value> [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } /// <summary> /// Gets or sets the name of the <see cref="Subject"/> entity. /// </summary> /// <value>Name of the <see cref="Subject"/> entity.</value> [Required] [StringLength(50, ErrorMessage = "Subject Name Invalid Length", MinimumLength = 1)] public string Name { get; set; } /// <summary> /// Gets or sets foreign key of the parent node of the <see cref="Subject"/> entity. /// </summary> /// <value>Primary key of the parent node of the <see cref="Subject"/> entity.</value> public int? SuperSubjectId { get; set; } /// <summary> /// Gets or sets the parent node of the <see cref="Subject"/> entity. /// </summary> /// <value>Parent node of the <see cref="Subject"/> entity.</value> public virtual Subject SuperSubject { get; set; } /// <summary> /// Gets or sets the child nodes of the <see cref="Subject"/> entity. /// </summary> /// <value>Initial collection of child nodes of the <see cref="Subject"/> entity.</value> public virtual ICollection<Subject> SubSubjects { get { return this.subSubjects; } set { this.subSubjects = value; } } /// <summary> /// Gets or sets the journals related to the <see cref="Subject"/> entity. /// </summary> /// <value>Initial collection of journals related to the <see cref="Subject"/> entity.</value> public virtual ICollection<Journal> Journals { get { return this.journals; } set { this.journals = value; } } } }```
69ccdc7e-379c-46cc-86bc-16bc8906c280
{ "language": "C#" }
```c# using System; using System.ComponentModel.Composition; using NQuery.Syntax; namespace NQuery.Authoring.QuickInfo { [Export(typeof(IQuickInfoModelProvider))] internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax> { protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node) { if (node.Alias == null) return null; var symbol = semanticModel.GetDeclaredSymbol(node); return symbol == null ? null : QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol); } } } ``` Fix bug in IQuickInfoModelProvider for SELECT column aliases
```c# using System; using System.ComponentModel.Composition; using NQuery.Syntax; namespace NQuery.Authoring.QuickInfo { [Export(typeof(IQuickInfoModelProvider))] internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax> { protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node) { if (node.Alias == null || !node.Alias.Span.Contains(position)) return null; var symbol = semanticModel.GetDeclaredSymbol(node); return symbol == null ? null : QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol); } } } ```
f051b176-1576-4996-92a5-474c3fd4e873
{ "language": "C#" }
```c#  using System; namespace SparklrLib.Objects.Responses.Work { public class Username : IEquatable<Username> { public string username { get; set; } public string displayname { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + displayname + " (@" + username + ")"; } public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. Username u = obj as Username; if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(Username u) { // If parameter is null return false: if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(int newid) { // If parameter is null return false: if ((object)newid == null) { return false; } // Return true if the fields match: return id == newid; } } }``` Add hash code to work/username
```c#  using System; namespace SparklrLib.Objects.Responses.Work { public class Username : IEquatable<Username> { public string username { get; set; } public string displayname { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + displayname + " (@" + username + ")"; } public override int GetHashCode() { return id; } public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. Username u = obj as Username; if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(Username u) { // If parameter is null return false: if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(int newid) { // If parameter is null return false: if ((object)newid == null) { return false; } // Return true if the fields match: return id == newid; } } }```
6c5fbe59-378c-4bab-8ad5-f5c6c81cc0cf
{ "language": "C#" }
```c# using System; using System.Globalization; namespace MultiMiner.Win.Extensions { public static class DateTimeExtensions { public static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateString = dateTime.ToShortDateString(); //year could be at beginning (JP) or end (EN) string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator; string value1 = dateTime.Year + dateSeparator; string value2 = dateSeparator + dateTime.Year; return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty); } public static string ToReallyShortDateTimeString(this DateTime dateTime) { return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString()); } } } ``` Update test suite for latest changes
```c# using System; using System.Globalization; namespace MultiMiner.Win.Extensions { public static class DateTimeExtensions { private static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateString = dateTime.ToShortDateString(); //year could be at beginning (JP) or end (EN) string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator; string value1 = dateTime.Year + dateSeparator; string value2 = dateSeparator + dateTime.Year; return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty); } public static string ToReallyShortDateTimeString(this DateTime dateTime) { return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString()); } } } ```
4fa2e9d4-cc3c-4089-bc87-ce4d7095d78b
{ "language": "C#" }
```c# using WootzJs.Web; namespace WootzJs.Mvc.Views { public class AutocompleteTextBox<T> : Control { private Control content; private Control overlay; private Element contentNode; private Element overlayContainer; private DropDownAlignment alignment; private T selectedItem; protected override Element CreateNode() { contentNode = Browser.Document.CreateElement("input"); contentNode.SetAttribute("type", "text"); contentNode.Style.Height = "100%"; var dropdown = Browser.Document.CreateElement(""); overlayContainer = Browser.Document.CreateElement("div"); overlayContainer.Style.Position = "absolute"; overlayContainer.Style.Display = "none"; overlayContainer.AppendChild(overlay.Node); Add(overlay); var overlayAnchor = Browser.Document.CreateElement("div"); overlayAnchor.Style.Position = "relative"; overlayAnchor.AppendChild(overlayContainer); var result = Browser.Document.CreateElement("div"); result.AppendChild(contentNode); result.AppendChild(overlayAnchor); return result; } } }``` Remove dead line from autocomplete
```c# using WootzJs.Web; namespace WootzJs.Mvc.Views { public class AutocompleteTextBox<T> : Control { private Control content; private Control overlay; private Element contentNode; private Element overlayContainer; private DropDownAlignment alignment; private T selectedItem; protected override Element CreateNode() { contentNode = Browser.Document.CreateElement("input"); contentNode.SetAttribute("type", "text"); contentNode.Style.Height = "100%"; overlayContainer = Browser.Document.CreateElement("div"); overlayContainer.Style.Position = "absolute"; overlayContainer.Style.Display = "none"; overlayContainer.AppendChild(overlay.Node); Add(overlay); var overlayAnchor = Browser.Document.CreateElement("div"); overlayAnchor.Style.Position = "relative"; overlayAnchor.AppendChild(overlayContainer); var result = Browser.Document.CreateElement("div"); result.AppendChild(contentNode); result.AppendChild(overlayAnchor); return result; } } }```
78f2e77a-ebdd-417a-9d19-d3b201084bbc
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V4.App; using Android.Views; using Android.Widget; using ReactiveUI.Routing.Android; using ReactiveUI.Routing.Presentation; using ReactiveUI.Routing.UseCases.Common.ViewModels; using Splat; namespace ReactiveUI.Routing.UseCases.Android { [Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)] public class MainActivity : FragmentActivity, IActivatable { protected override void OnCreate(Bundle savedInstanceState) { Locator.CurrentMutable.InitializeRoutingAndroid(this); this.WhenActivated(d => { Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager); PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container) .DisposeWith(d); Locator.Current.GetService<IAppPresenter>() .PresentPage(new LoginViewModel()) .Subscribe() .DisposeWith(d); }); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); } } }``` Fix app always showing the login page after orientation change
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V4.App; using Android.Views; using Android.Widget; using ReactiveUI.Routing.Android; using ReactiveUI.Routing.Presentation; using ReactiveUI.Routing.UseCases.Common.ViewModels; using Splat; namespace ReactiveUI.Routing.UseCases.Android { [Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)] public class MainActivity : FragmentActivity, IActivatable { protected override void OnCreate(Bundle savedInstanceState) { Locator.CurrentMutable.InitializeRoutingAndroid(this); this.WhenActivated(d => { Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager); PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container) .DisposeWith(d); var presenter = Locator.Current.GetService<IAppPresenter>(); if (!presenter.ActiveViews.Any()) { presenter.PresentPage(new LoginViewModel()) .Subscribe() .DisposeWith(d); } }); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); } } }```
c0a18e5d-6704-48b5-83bf-d9d3a297ceac
{ "language": "C#" }
```c# namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } } ``` Add filter property to popular movies request.
```c# namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internet TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } } ```
052de503-4326-4091-b7ac-36480069a697
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Radosgw.AdminAPI { public class User { [JsonProperty(PropertyName = "display_name")] public string DisplayName { get; set; } [JsonProperty(PropertyName = "user_id")] public string UserId { get; set; } [JsonProperty(PropertyName = "tenant")] public string Tenant { get; set; } [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "max_buckets")] public uint MaxBuckets { get; set; } [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "suspended")] public bool Suspended { get; set; } [JsonProperty(PropertyName="keys")] public List<Key> Keys { get; set; } public override string ToString() { return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]", DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys))); } public User() { } } } ``` Fix exception if Keys is null
```c# using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Radosgw.AdminAPI { public class User { [JsonProperty(PropertyName = "display_name")] public string DisplayName { get; set; } [JsonProperty(PropertyName = "user_id")] public string UserId { get; set; } [JsonProperty(PropertyName = "tenant")] public string Tenant { get; set; } [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "max_buckets")] public uint MaxBuckets { get; set; } [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "suspended")] public bool Suspended { get; set; } [JsonProperty(PropertyName="keys")] public List<Key> Keys { get; set; } public override string ToString() { return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]", DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys ?? new List<Key>()))); } public User() { } } } ```
54bb74a5-4326-49d7-873e-4df8d5db8524
{ "language": "C#" }
```c# using Jbe.NewsReader.Applications.ViewModels; using Jbe.NewsReader.Applications.Views; namespace Jbe.NewsReader.Presentation.DesignData { public class SampleFeedItemListViewModel : FeedItemListViewModel { public SampleFeedItemListViewModel() : base(new MockFeedItemListView(), null) { } private class MockFeedItemListView : IFeedItemListView { public object DataContext { get; set; } } } } ``` Add comment that design time data does not work with {x:Bind}
```c# using Jbe.NewsReader.Applications.ViewModels; using Jbe.NewsReader.Applications.Views; namespace Jbe.NewsReader.Presentation.DesignData { public class SampleFeedItemListViewModel : FeedItemListViewModel { public SampleFeedItemListViewModel() : base(new MockFeedItemListView(), null) { // Note: Design time data does not work with {x:Bind} } private class MockFeedItemListView : IFeedItemListView { public object DataContext { get; set; } } } } ```
2878ee7b-24f5-418a-8b32-838821ddaad6
{ "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; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { public class FollowPoint : Container { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new Container { Masking = true, AutoSizeAxes = Axes.Both, CornerRadius = width / 2, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }, confineMode: ConfineMode.NoScaling); } } } ``` Fix follow point transforms not working after rewind
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { public class FollowPoint : Container { private const float width = 8; public override bool RemoveWhenNotAlive => false; public override bool RemoveCompletedTransforms => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new Container { Masking = true, AutoSizeAxes = Axes.Both, CornerRadius = width / 2, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }, confineMode: ConfineMode.NoScaling); } } } ```
4b419206-1129-4bc4-b602-ea9d56fa1c7e
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace Verdeler { internal class ConcurrencyLimiter<TSubject> { private readonly Func<TSubject, object> _subjectReductionMap; private readonly int _concurrencyLimit; private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores = new ConcurrentDictionary<object, SemaphoreSlim>(); public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit) { if (concurrencyLimit <= 0) { throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit)); } _subjectReductionMap = subjectReductionMap; _concurrencyLimit = concurrencyLimit; } public async Task WaitFor(TSubject subject) { var semaphore = GetSemaphoreForReduction(subject); await semaphore.WaitAsync(); } public void Release(TSubject subject) { var semaphore = GetSemaphoreForReduction(subject); semaphore.Release(); } private SemaphoreSlim GetSemaphoreForReduction(TSubject subject) { var reducedSubject = _subjectReductionMap.Invoke(subject); var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit)); return semaphore; } } } ``` Rename method to get semaphore
```c# using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace Verdeler { internal class ConcurrencyLimiter<TSubject> { private readonly Func<TSubject, object> _subjectReductionMap; private readonly int _concurrencyLimit; private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores = new ConcurrentDictionary<object, SemaphoreSlim>(); public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit) { if (concurrencyLimit <= 0) { throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit)); } _subjectReductionMap = subjectReductionMap; _concurrencyLimit = concurrencyLimit; } public async Task WaitFor(TSubject subject) { var semaphore = GetSemaphoreForReducedSubject(subject); await semaphore.WaitAsync(); } public void Release(TSubject subject) { var semaphore = GetSemaphoreForReducedSubject(subject); semaphore.Release(); } private SemaphoreSlim GetSemaphoreForReducedSubject(TSubject subject) { var reducedSubject = _subjectReductionMap.Invoke(subject); var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit)); return semaphore; } } } ```
284bcbfa-66a3-4178-beb7-0b3d4d240776
{ "language": "C#" }
```c# using Glimpse; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System.Collections.Generic; namespace Glimpse { public class GlimpseServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Discovery & Reflection. // yield return describe.Transient<ITypeActivator, DefaultTypeActivator>(); yield return describe.Transient<ITypeSelector, DefaultTypeSelector>(); yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>(); yield return describe.Transient<ITypeService, DefaultTypeService>(); yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>)); } } }``` Add registration to the serive
```c# using Glimpse; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System.Collections.Generic; namespace Glimpse { public class GlimpseServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Discovery & Reflection. // yield return describe.Transient<ITypeActivator, DefaultTypeActivator>(); yield return describe.Transient<ITypeSelector, DefaultTypeSelector>(); yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>(); yield return describe.Transient<ITypeService, DefaultTypeService>(); yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>)); // // Broker // yield return describe.Singleton<IMessageBus, DefaultMessageBus>(); } } }```
e9c61d8a-a27d-40b3-b6a9-fe74914647e2
{ "language": "C#" }
```c# using ArduinoUploader; namespace ArduinoSketchUploader { /// <summary> /// The ArduinoLibCSharp SketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino. /// </summary> internal class Program { private static void Main(string[] args) { var commandLineOptions = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return; var options = new ArduinoSketchUploaderOptions { PortName = commandLineOptions.PortName, FileName = commandLineOptions.FileName, ArduinoModel = commandLineOptions.ArduinoModel }; var uploader = new ArduinoUploader.ArduinoSketchUploader(options); uploader.UploadSketch(); } } } ``` Remove reference to old library name.
```c# using ArduinoUploader; namespace ArduinoSketchUploader { /// <summary> /// The ArduinoSketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino. /// </summary> internal class Program { private static void Main(string[] args) { var commandLineOptions = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return; var options = new ArduinoSketchUploaderOptions { PortName = commandLineOptions.PortName, FileName = commandLineOptions.FileName, ArduinoModel = commandLineOptions.ArduinoModel }; var uploader = new ArduinoUploader.ArduinoSketchUploader(options); uploader.UploadSketch(); } } } ```
a11eefe0-3762-4d7a-b3f8-d471088f4403
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; using PolarisServer.Models; namespace PolarisServer.Models { public struct PacketHeader { public UInt32 Size; public byte Type; public byte Subtype; public byte Flags1; public byte Flags2; public PacketHeader(int size, byte type, byte subtype, byte flags1, byte flags2) { this.Size = (uint)size; this.Type = type; this.Subtype = subtype; this.Flags1 = flags1; this.Flags2 = flags2; } public PacketHeader(byte type, byte subtype) : this(type, subtype, (byte)0) { } public PacketHeader(byte type, byte subtype, byte flags1) : this(0, type, subtype, flags1, 0) { } public PacketHeader(byte type, byte subtype, PacketFlags packetFlags) : this(type, subtype, (byte)packetFlags) { } } [Flags] public enum PacketFlags : byte { NONE, STREAM_PACKED = 0x4, FLAG_10 = 0x10, ENTITY_HEADER = 0x40 } } ``` Add flag 0x20 to PacketFlags
```c# using System; using System.Runtime.InteropServices; using PolarisServer.Models; namespace PolarisServer.Models { public struct PacketHeader { public UInt32 Size; public byte Type; public byte Subtype; public byte Flags1; public byte Flags2; public PacketHeader(int size, byte type, byte subtype, byte flags1, byte flags2) { this.Size = (uint)size; this.Type = type; this.Subtype = subtype; this.Flags1 = flags1; this.Flags2 = flags2; } public PacketHeader(byte type, byte subtype) : this(type, subtype, (byte)0) { } public PacketHeader(byte type, byte subtype, byte flags1) : this(0, type, subtype, flags1, 0) { } public PacketHeader(byte type, byte subtype, PacketFlags packetFlags) : this(type, subtype, (byte)packetFlags) { } } [Flags] public enum PacketFlags : byte { NONE, STREAM_PACKED = 0x4, FLAG_10 = 0x10, FULL_MOVEMENT = 0x20, ENTITY_HEADER = 0x40 } } ```
59a8c4a1-dffc-4743-8b12-6b315d289f90
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Provision.AspNet.Identity.PlainSql")] [assembly: AssemblyDescription("ASP.NET Identity provider for SQL databases")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Provision Data Systems Inc.")] [assembly: AssemblyProduct("Provision.AspNet.Identity.PlainSql")] [assembly: AssemblyCopyright("Copyright © 2016 Provision Data Systems Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("EN-us")] [assembly: ComVisible(false)] [assembly: Guid("9248deff-4947-481f-ba7c-09e9925e62d2")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] ``` Remove EN-us culture from assembly attributes.
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Provision.AspNet.Identity.PlainSql")] [assembly: AssemblyDescription("ASP.NET Identity provider for SQL databases")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Provision Data Systems Inc.")] [assembly: AssemblyProduct("Provision.AspNet.Identity.PlainSql")] [assembly: AssemblyCopyright("Copyright © 2016 Provision Data Systems Inc.")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9248deff-4947-481f-ba7c-09e9925e62d2")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] ```
400aa2e1-8d7d-4e86-b3d2-c374c3e1b8fa
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #if WINDOWS_UWP using Microsoft.MixedReality.Toolkit.Windows.Utilities; using System; using System.Collections.Generic; using UnityEngine.XR.WSA.Input; using Windows.Foundation; using Windows.Perception; using Windows.Storage.Streams; using Windows.UI.Input.Spatial; #endif namespace Microsoft.MixedReality.Toolkit.Windows.Input { /// <summary> /// Extensions for the InteractionSource class to expose the renderable model. /// </summary> public static class InteractionSourceExtensions { #if WINDOWS_UWP public static IAsyncOperation<IRandomAccessStreamWithContentType> TryGetRenderableModelAsync(this InteractionSource interactionSource) { IAsyncOperation<IRandomAccessStreamWithContentType> returnValue = null; if (WindowsApiChecker.UniversalApiContractV5_IsAvailable) { UnityEngine.WSA.Application.InvokeOnUIThread(() => { IReadOnlyList<SpatialInteractionSourceState> sources = SpatialInteractionManager.GetForCurrentView()?.GetDetectedSourcesAtTimestamp(PerceptionTimestampHelper.FromHistoricalTargetTime(DateTimeOffset.Now)); for (var i = 0; i < sources.Count; i++) { if (sources[i].Source.Id.Equals(interactionSource.id)) { returnValue = sources[i].Source.Controller.TryGetRenderableModelAsync(); } } }, true); } return returnValue; } #endif // WINDOWS_UWP } } ``` Rework extension to spend less time on UI thread
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #if WINDOWS_UWP using Microsoft.MixedReality.Toolkit.Windows.Utilities; using System; using System.Collections.Generic; using UnityEngine.XR.WSA.Input; using Windows.Foundation; using Windows.Perception; using Windows.Storage.Streams; using Windows.UI.Input.Spatial; #endif namespace Microsoft.MixedReality.Toolkit.Windows.Input { /// <summary> /// Extensions for the InteractionSource class to expose the renderable model. /// </summary> public static class InteractionSourceExtensions { #if WINDOWS_UWP public static IAsyncOperation<IRandomAccessStreamWithContentType> TryGetRenderableModelAsync(this InteractionSource interactionSource) { IAsyncOperation<IRandomAccessStreamWithContentType> returnValue = null; if (WindowsApiChecker.UniversalApiContractV5_IsAvailable) { IReadOnlyList<SpatialInteractionSourceState> sources = null; UnityEngine.WSA.Application.InvokeOnUIThread(() => { sources = SpatialInteractionManager.GetForCurrentView()?.GetDetectedSourcesAtTimestamp(PerceptionTimestampHelper.FromHistoricalTargetTime(DateTimeOffset.Now)); }, true); for (var i = 0; i < sources?.Count; i++) { if (sources[i].Source.Id.Equals(interactionSource.id)) { returnValue = sources[i].Source.Controller.TryGetRenderableModelAsync(); } } } return returnValue; } #endif // WINDOWS_UWP } } ```
07494d07-4a96-4c8f-a775-f2cd3ab60f4b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hl7.Fhir.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; using Spark.Engine.Extensions; namespace Spark.Engine.Test.Extensions { [TestClass] public class OperationOutcomeInnerErrorsTest { [TestMethod] public void AddAllInnerErrorsTest() { OperationOutcome outcome; try { try { try { throw new Exception("Third error level"); } catch (Exception e3) { throw new Exception("Second error level", e3); } } catch (Exception e2) { throw new Exception("First error level", e2); } } catch (Exception e1) { outcome = new OperationOutcome().AddAllInnerErrors(e1); } Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: First error level")), "No info about first error"); Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: Second error level")), "No info about second error"); Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: Third error level")), "No info about third error"); } } } ``` Make sure Issues are at correct index
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hl7.Fhir.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; using Spark.Engine.Extensions; namespace Spark.Engine.Test.Extensions { [TestClass] public class OperationOutcomeInnerErrorsTest { [TestMethod] public void AddAllInnerErrorsTest() { OperationOutcome outcome; try { try { try { throw new Exception("Third error level"); } catch (Exception e3) { throw new Exception("Second error level", e3); } } catch (Exception e2) { throw new Exception("First error level", e2); } } catch (Exception e1) { outcome = new OperationOutcome().AddAllInnerErrors(e1); } Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: First error level")) == 0, "First error level should be at index 0"); Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: Second error level")) == 1, "Second error level should be at index 1"); Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: Third error level")) == 2, "Third error level should be at index 2"); } } } ```
d68b206c-51e2-438e-8d56-6892a331c127
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; namespace Arkivverket.Arkade.Core.Addml.Definitions.DataTypes { public class DateDataType : DataType { private readonly string _dateTimeFormat; private readonly string _fieldFormat; public DateDataType(string fieldFormat) : this(fieldFormat, null) { } public DateDataType(string fieldFormat, List<string> nullValues) : base(nullValues) { _fieldFormat = fieldFormat; _dateTimeFormat = ConvertToDateTimeFormat(_fieldFormat); } public DateDataType() { throw new NotImplementedException(); } private string ConvertToDateTimeFormat(string fieldFormat) { // TODO: Do we have to convert ADDML data fieldFormat til .NET format? return fieldFormat; } public DateTimeOffset Parse(string dateTimeString) { DateTimeOffset dto = DateTimeOffset.ParseExact (dateTimeString, _dateTimeFormat, CultureInfo.InvariantCulture); return dto; } protected bool Equals(DateDataType other) { return string.Equals(_fieldFormat, other._fieldFormat); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((DateDataType) obj); } public override int GetHashCode() { return _fieldFormat?.GetHashCode() ?? 0; } public override bool IsValid(string s) { try { Parse(s); return true; } catch (FormatException e) { return false; } } } }``` Use TryParseExact instead of ParseExact. Better performance.
```c# using System; using System.Collections.Generic; using System.Globalization; namespace Arkivverket.Arkade.Core.Addml.Definitions.DataTypes { public class DateDataType : DataType { private readonly string _dateTimeFormat; private readonly string _fieldFormat; public DateDataType(string fieldFormat) : this(fieldFormat, null) { } public DateDataType(string fieldFormat, List<string> nullValues) : base(nullValues) { _fieldFormat = fieldFormat; _dateTimeFormat = ConvertToDateTimeFormat(_fieldFormat); } private string ConvertToDateTimeFormat(string fieldFormat) { return fieldFormat; } public DateTimeOffset Parse(string dateTimeString) { DateTimeOffset dto = DateTimeOffset.ParseExact (dateTimeString, _dateTimeFormat, CultureInfo.InvariantCulture); return dto; } protected bool Equals(DateDataType other) { return string.Equals(_fieldFormat, other._fieldFormat); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((DateDataType) obj); } public override int GetHashCode() { return _fieldFormat?.GetHashCode() ?? 0; } public override bool IsValid(string s) { DateTimeOffset res; return DateTimeOffset.TryParseExact(s, _dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out res); } } }```
ed527985-0e28-4451-a5a3-a5c6de27f98c
{ "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.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Game.Audio; namespace osu.Game.Skinning { public class DefaultSkin : Skin { public DefaultSkin() : base(SkinInfo.Default) { Configuration = new DefaultSkinConfiguration(); } public override Drawable GetDrawableComponent(ISkinComponent component) => null; public override Texture GetTexture(string componentName) => null; public override SampleChannel GetSample(ISampleInfo sampleInfo) => null; public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => null; } } ``` Fix fallback to default combo colours not working
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osu.Game.Audio; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultSkin : Skin { public DefaultSkin() : base(SkinInfo.Default) { Configuration = new DefaultSkinConfiguration(); } public override Drawable GetDrawableComponent(ISkinComponent component) => null; public override Texture GetTexture(string componentName) => null; public override SampleChannel GetSample(ISampleInfo sampleInfo) => null; public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) { switch (lookup) { case GlobalSkinConfiguration global: switch (global) { case GlobalSkinConfiguration.ComboColours: return SkinUtils.As<TValue>(new Bindable<List<Color4>>(Configuration.ComboColours)); } break; } return null; } } } ```
e171f040-66f0-46ed-bfa3-23f5f7767c86
{ "language": "C#" }
```c# @model AtomicChessPuzzles.HttpErrors.HttpError <h1>@Model.StatusCode - @Model.StatusText</h1> <p>@Model.Description</p>``` Add a HTML title to error view
```c# @model AtomicChessPuzzles.HttpErrors.HttpError @section Title{@Model.StatusCode @Model.StatusText} <h1>@Model.StatusCode - @Model.StatusText</h1> <p>@Model.Description</p>```
43aa1a68-db89-4f7a-b4a5-4e60eeb296e2
{ "language": "C#" }
```c# using System; using System.IO; namespace Flirper { public class ImageListEntry { public string uri; public string title; public string author; public string extraInfo; public ImageListEntry (string uri, string title, string author, string extraInfo) { this.uri = uri; this.title = title; this.author = author; this.extraInfo = extraInfo; } public bool isHTTP { get { return this.uri.ToLower ().StartsWith ("http:") || this.uri.ToLower ().StartsWith ("https:"); } } public bool isFile { get { if (isHTTP || isLatestSaveGame) return false; return !System.IO.Directory.Exists(@uri) && System.IO.File.Exists(@uri); } } public bool isDirectory { get { if (isHTTP || isLatestSaveGame || isFile) return false; FileAttributes attr = System.IO.File.GetAttributes (@uri); return (attr & FileAttributes.Directory) == FileAttributes.Directory; } } public bool isLatestSaveGame { get { return this.uri.ToLower ().StartsWith ("savegame"); } } public bool isValidPath { get { if(isHTTP || isLatestSaveGame) return true; try { FileInfo fi = new System.IO.FileInfo(@uri); FileAttributes attr = System.IO.File.GetAttributes (@uri); } catch (Exception ex) { ex.ToString(); return false; } return true; } } } }``` Modify case handling of entry types
```c# using System; using System.IO; namespace Flirper { public class ImageListEntry { public string uri; public string title; public string author; public string extraInfo; public ImageListEntry (string uri, string title, string author, string extraInfo) { this.uri = uri; this.title = title; this.author = author; this.extraInfo = extraInfo; } public bool isHTTP { get { return this.uri.ToLower ().StartsWith ("http:") || this.uri.ToLower ().StartsWith ("https:"); } } public bool isFile { get { return isLocal && !System.IO.Directory.Exists(@uri) && System.IO.File.Exists(@uri); } } public bool isDirectory { get { if (!isLocal || isFile) return false; FileAttributes attr = System.IO.File.GetAttributes (@uri); return (attr & FileAttributes.Directory) == FileAttributes.Directory; } } public bool isLatestSaveGame { get { return this.uri.ToLower ().StartsWith ("savegame"); } } private bool isLocal { get { return !(isHTTP || isLatestSaveGame); } } public bool isValidPath { get { if(!isLocal) return true; try { FileInfo fi = new System.IO.FileInfo(@uri); FileAttributes attr = System.IO.File.GetAttributes (@uri); } catch (Exception ex) { ex.ToString(); return false; } return true; } } } }```
f7f17b9b-1428-4236-8e35-5a0079e0244e
{ "language": "C#" }
```c# using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!"); } } } ``` Add Bigsby Gates was here
```c# using System; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!"); Console.WriteLine("Bigsby Gates was here!"); } } } ```
35475a2e-0f27-496c-88a0-5a0cb3964e8b
{ "language": "C#" }
```c# using System.Data.Entity; using System.Threading.Tasks; using JoinRpg.Web.Helpers; using Microsoft.Owin.Security.OAuth; namespace JoinRpg.Web { internal class ApiSignInProvider : OAuthAuthorizationServerProvider { private ApplicationUserManager Manager { get; } public ApiSignInProvider(ApplicationUserManager manager) { Manager = manager; } /// <inheritdoc /> public override Task ValidateClientAuthentication( OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult(0); } public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); var user = await Manager.FindByEmailAsync(context.UserName); if (!await Manager.CheckPasswordAsync(user, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType); context.Validated(x); } } }``` Return 400 instead of 500 if no login/password
```c# using System.Threading.Tasks; using JoinRpg.Web.Helpers; using Microsoft.Owin.Security.OAuth; namespace JoinRpg.Web { internal class ApiSignInProvider : OAuthAuthorizationServerProvider { private ApplicationUserManager Manager { get; } public ApiSignInProvider(ApplicationUserManager manager) { Manager = manager; } /// <inheritdoc /> public override Task ValidateClientAuthentication( OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult(0); } public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); if (string.IsNullOrWhiteSpace(context.UserName) || string.IsNullOrWhiteSpace(context.Password)) { context.SetError("invalid_grant", "Please supply susername and password."); return; } var user = await Manager.FindByEmailAsync(context.UserName); if (!await Manager.CheckPasswordAsync(user, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType); context.Validated(x); } } }```
9cb17e93-5262-4319-b1b7-5788fb2eb591
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Interactivity; using MahApps.Metro.Controls; namespace MahApps.Metro.Behaviours { public class GlowWindowBehavior : Behavior<Window> { private GlowWindow left, right, top, bottom; protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.Loaded += (sender, e) => { left = new GlowWindow(this.AssociatedObject, GlowDirection.Left); right = new GlowWindow(this.AssociatedObject, GlowDirection.Right); top = new GlowWindow(this.AssociatedObject, GlowDirection.Top); bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom); Show(); left.Update(); right.Update(); top.Update(); bottom.Update(); }; this.AssociatedObject.Closed += (sender, args) => { if (left != null) left.Close(); if (right != null) right.Close(); if (top != null) top.Close(); if (bottom != null) bottom.Close(); }; } public void Hide() { left.Hide(); right.Hide(); bottom.Hide(); top.Hide(); } public void Show() { left.Show(); right.Show(); top.Show(); bottom.Show(); } } } ``` Fix The GlowWindow in the taskmanager
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Interactivity; using MahApps.Metro.Controls; namespace MahApps.Metro.Behaviours { public class GlowWindowBehavior : Behavior<Window> { private GlowWindow left, right, top, bottom; protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.Loaded += (sender, e) => { left = new GlowWindow(this.AssociatedObject, GlowDirection.Left); right = new GlowWindow(this.AssociatedObject, GlowDirection.Right); top = new GlowWindow(this.AssociatedObject, GlowDirection.Top); bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom); left.Owner = (MetroWindow)sender; right.Owner = (MetroWindow)sender; top.Owner = (MetroWindow)sender; bottom.Owner = (MetroWindow)sender; Show(); left.Update(); right.Update(); top.Update(); bottom.Update(); }; this.AssociatedObject.Closed += (sender, args) => { if (left != null) left.Close(); if (right != null) right.Close(); if (top != null) top.Close(); if (bottom != null) bottom.Close(); }; } public void Hide() { left.Hide(); right.Hide(); bottom.Hide(); top.Hide(); } public void Show() { left.Show(); right.Show(); top.Show(); bottom.Show(); } } } ```
f104656d-6455-4291-b7b3-eb73e2f735dc
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; namespace WebPlayer.Mobile { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string origUrl = Request.QueryString.Get("origUrl"); int queryPos = origUrl.IndexOf("Play.aspx?"); if (queryPos != -1) { var origUrlValues = HttpUtility.ParseQueryString(origUrl.Substring(origUrl.IndexOf("?"))); string id = origUrlValues.Get("id"); Response.Redirect("Play.aspx?id=" + id); return; } Response.Clear(); Response.StatusCode = 404; Response.End(); } } }``` Fix broken redirect when restoring game on mobile
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; namespace WebPlayer.Mobile { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string origUrl = Request.QueryString.Get("origUrl"); int queryPos = origUrl.IndexOf("Play.aspx?"); if (queryPos != -1) { var origUrlValues = HttpUtility.ParseQueryString(origUrl.Substring(origUrl.IndexOf("?"))); string id = origUrlValues.Get("id"); if (!string.IsNullOrEmpty(id)) { Response.Redirect("Play.aspx?id=" + id); return; } string load = origUrlValues.Get("load"); if (!string.IsNullOrEmpty(load)) { Response.Redirect("Play.aspx?load=" + load); return; } } Response.Clear(); Response.StatusCode = 404; Response.End(); } } }```
3aed1b3a-c56a-4697-a151-cdcb2b235751
{ "language": "C#" }
```c# using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; using NUnit.Framework; namespace SeleniumTasksProject1._1 { [TestFixture] public class InternetExplorer { private IWebDriver driver; private WebDriverWait wait; [SetUp] public void start() { driver = new InternetExplorerDriver(); wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); } [Test] public void LoginTestInInternetExplorer() { driver.Url = "http://localhost:8082/litecart/admin/"; } [TearDown] public void stop() { driver.Quit(); driver = null; } } } ``` Revert "Revert "LoginTest is completed""
```c# using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; using NUnit.Framework; namespace SeleniumTasksProject1._1 { [TestFixture] public class InternetExplorer { private IWebDriver driver; private WebDriverWait wait; [SetUp] public void start() { driver = new InternetExplorerDriver(); wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); } [Test] public void LoginTestInInternetExplorer() { driver.Url = "http://localhost:8082/litecart/admin/"; driver.FindElement(By.Name("username")).SendKeys("admin"); driver.FindElement(By.Name("password")).SendKeys("admin"); driver.FindElement(By.Name("login")).Click(); //wait.Until(ExpectedConditions.TitleIs("My Store")); } [TearDown] public void stop() { driver.Quit(); driver = null; } } } ```
a6fb8a96-c82d-4b27-9e0d-326e2d475cb8
{ "language": "C#" }
```c# /* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using System.Windows; using System.Windows.Interactivity; namespace Cube.Xui.Behaviors { /* --------------------------------------------------------------------- */ /// /// DisposeAction /// /// <summary> /// DataContext の開放処理を実行する TriggerAction です。 /// </summary> /// /* --------------------------------------------------------------------- */ public class DisposeAction : TriggerAction<FrameworkElement> { /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// 処理を実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ protected override void Invoke(object notused) { if (AssociatedObject.DataContext is IDisposable dc) dc.Dispose(); AssociatedObject.DataContext = null; } } } ``` Fix for disposing DataContext object.
```c# /* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using System.Windows; using System.Windows.Interactivity; namespace Cube.Xui.Behaviors { /* --------------------------------------------------------------------- */ /// /// DisposeAction /// /// <summary> /// DataContext の開放処理を実行する TriggerAction です。 /// </summary> /// /* --------------------------------------------------------------------- */ public class DisposeAction : TriggerAction<FrameworkElement> { /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// 処理を実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ protected override void Invoke(object notused) { var dc = AssociatedObject.DataContext as IDisposable; AssociatedObject.DataContext = null; dc?.Dispose(); } } } ```
ab21d451-680b-4623-9c61-275265daee98
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Payload that tells the server we've finsihed loading/bursting/warping. /// We should have sent a warp request to the server before this so it should know where we /// were going. /// </summary> [WireDataContract] [SubCommand60Client(SubCommand60OperationCode.EnterFreshlyWrappedZoneCommand)] public sealed class Sub60FinishedWarpingBurstingPayload : BlockNetworkCommandEventClientPayload { //Packet is empty. Just tells the server we bursted/warped finished. public Sub60FinishedWarpingBurstingPayload() { } } } ``` Add missing field to FinishedWarp
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Payload that tells the server we've finsihed loading/bursting/warping. /// We should have sent a warp request to the server before this so it should know where we /// were going. /// </summary> [WireDataContract] [SubCommand60Client(SubCommand60OperationCode.EnterFreshlyWrappedZoneCommand)] public sealed class Sub60FinishedWarpingBurstingPayload : BlockNetworkCommandEventClientPayload { //Packet is empty. Just tells the server we bursted/warped finished. //TODO: Is this client id? [WireMember(1)] private short unk { get; } public Sub60FinishedWarpingBurstingPayload() { } } } ```
776d44ec-dac9-4f19-8d21-cae5325a5d8b
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")] ``` Increase project version number to 0.8
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")] ```
50a31614-9571-43e3-a080-3c3bc5bdc33d
{ "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.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { public class MultiplayerPlaylistTabControl : OsuTabControl<MultiplayerPlaylistDisplayMode> { public readonly IBindableList<PlaylistItem> QueueItems = new BindableList<PlaylistItem>(); protected override TabItem<MultiplayerPlaylistDisplayMode> CreateTabItem(MultiplayerPlaylistDisplayMode value) { if (value == MultiplayerPlaylistDisplayMode.Queue) return new QueueTabItem { QueueItems = { BindTarget = QueueItems } }; return base.CreateTabItem(value); } private class QueueTabItem : OsuTabItem { public readonly IBindableList<PlaylistItem> QueueItems = new BindableList<PlaylistItem>(); public QueueTabItem() : base(MultiplayerPlaylistDisplayMode.Queue) { } protected override void LoadComplete() { base.LoadComplete(); QueueItems.BindCollectionChanged((_,__) => { Text.Text = $"Queue"; if (QueueItems.Count != 0) Text.Text += $" ({QueueItems.Count})"; }, true); } } } } ``` Simplify queue count text logic
```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.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { public class MultiplayerPlaylistTabControl : OsuTabControl<MultiplayerPlaylistDisplayMode> { public readonly IBindableList<PlaylistItem> QueueItems = new BindableList<PlaylistItem>(); protected override TabItem<MultiplayerPlaylistDisplayMode> CreateTabItem(MultiplayerPlaylistDisplayMode value) { if (value == MultiplayerPlaylistDisplayMode.Queue) return new QueueTabItem { QueueItems = { BindTarget = QueueItems } }; return base.CreateTabItem(value); } private class QueueTabItem : OsuTabItem { public readonly IBindableList<PlaylistItem> QueueItems = new BindableList<PlaylistItem>(); public QueueTabItem() : base(MultiplayerPlaylistDisplayMode.Queue) { } protected override void LoadComplete() { base.LoadComplete(); QueueItems.BindCollectionChanged((_, __) => Text.Text = QueueItems.Count > 0 ? $"Queue ({QueueItems.Count})" : "Queue", true); } } } } ```
61657bc7-00bf-45d5-a608-a1b772467dc0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; public class Enumerator { public Enumerator() { } public int Current { get; private set; } = 10; public bool MoveNext() { Current--; return Current > 0; } public void Dispose() { Console.WriteLine("Hi!"); } } public class Enumerable { public Enumerable() { } public Enumerator GetEnumerator() { return new Enumerator(); } } public static class Program { public static Enumerable StaticEnumerable = new Enumerable(); public static void Main(string[] Args) { var col = Args; foreach (var item in col) Console.WriteLine(item); foreach (var item in new List<string>(Args)) Console.WriteLine(item); foreach (var item in StaticEnumerable) Console.WriteLine(item); } } ``` Add a foreach induction variable cast test
```c# using System; using System.Collections.Generic; public class Enumerator { public Enumerator() { } public int Current { get; private set; } = 10; public bool MoveNext() { Current--; return Current > 0; } public void Dispose() { Console.WriteLine("Hi!"); } } public class Enumerable { public Enumerable() { } public Enumerator GetEnumerator() { return new Enumerator(); } } public static class Program { public static Enumerable StaticEnumerable = new Enumerable(); public static void Main(string[] Args) { var col = Args; foreach (var item in col) Console.WriteLine(item); foreach (var item in new List<string>(Args)) Console.WriteLine(item); foreach (var item in StaticEnumerable) Console.WriteLine(item); foreach (string item in new List<object>()) Console.WriteLine(item); } } ```
3b9ef198-2568-4ed0-a318-76991e0ee875
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// A hitcircle which is at the end of a slider path (either repeat or final tail). /// </summary> public abstract class SliderEndCircle : HitCircle { public int RepeatIndex { get; set; } public double SpanDuration { get; set; } protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); // Out preempt should be one span early to give the user ample warning. TimePreempt += SpanDuration; // We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders // we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time. if (RepeatIndex > 0) TimePreempt = Math.Min(SpanDuration * 2, TimePreempt); } protected override HitWindows CreateHitWindows() => HitWindows.Empty; } } ``` Adjust repeat/tail fade in to match stable closer
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// A hitcircle which is at the end of a slider path (either repeat or final tail). /// </summary> public abstract class SliderEndCircle : HitCircle { public int RepeatIndex { get; set; } public double SpanDuration { get; set; } protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); if (RepeatIndex > 0) { // Repeat points after the first span should appear behind the still-visible one. TimeFadeIn = 0; // The next end circle should appear exactly after the previous circle (on the same end) is hit. TimePreempt = SpanDuration * 2; } } protected override HitWindows CreateHitWindows() => HitWindows.Empty; } } ```
fd5f70f5-13a3-4113-80f6-e00cb7cf24a8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using SFA.DAS.Payments.AcceptanceTests.Contexts; using SFA.DAS.Payments.AcceptanceTests.ReferenceDataModels; using SFA.DAS.Payments.AcceptanceTests.ResultsDataModels; namespace SFA.DAS.Payments.AcceptanceTests.Assertions.TransactionTypeRules { public abstract class TransactionTypeRuleBase { public virtual void AssertPeriodValues(IEnumerable<PeriodValue> periodValues, LearnerResults[] submissionResults, EmployerAccountContext employerAccountContext) { foreach (var period in periodValues) { var payments = FilterPayments(period, submissionResults, employerAccountContext); var paidInPeriod = payments.Sum(p => p.Amount); if (period.Value != paidInPeriod) { throw new Exception(FormatAssertionFailureMessage(period, paidInPeriod)); } } } protected abstract IEnumerable<PaymentResult> FilterPayments(PeriodValue period, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext); protected abstract string FormatAssertionFailureMessage(PeriodValue period, decimal actualPaymentInPeriod); } } ``` Fix issue with precision in assertions
```c# using System; using System.Collections.Generic; using System.Linq; using SFA.DAS.Payments.AcceptanceTests.Contexts; using SFA.DAS.Payments.AcceptanceTests.ReferenceDataModels; using SFA.DAS.Payments.AcceptanceTests.ResultsDataModels; namespace SFA.DAS.Payments.AcceptanceTests.Assertions.TransactionTypeRules { public abstract class TransactionTypeRuleBase { public virtual void AssertPeriodValues(IEnumerable<PeriodValue> periodValues, LearnerResults[] submissionResults, EmployerAccountContext employerAccountContext) { foreach (var period in periodValues) { var payments = FilterPayments(period, submissionResults, employerAccountContext); var paidInPeriod = payments.Sum(p => p.Amount); if(Math.Round(paidInPeriod, 2) != Math.Round(period.Value, 2)) { throw new Exception(FormatAssertionFailureMessage(period, paidInPeriod)); } } } protected abstract IEnumerable<PaymentResult> FilterPayments(PeriodValue period, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext); protected abstract string FormatAssertionFailureMessage(PeriodValue period, decimal actualPaymentInPeriod); } } ```
b7192f2f-f722-4ca0-8ae7-13062920f7f2
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuatiuons to a scheduler instance. /// </summary> internal class SchedulerSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public SchedulerSynchronizationContext(Scheduler scheduler) { this.scheduler = scheduler; } public override void Send(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), false); public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), true); } } ``` Fix `SynchronizationContext` to match correctly implementation structure
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuatiuons to a scheduler instance. /// </summary> internal class SchedulerSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public SchedulerSynchronizationContext(Scheduler scheduler) { this.scheduler = scheduler; } public override void Send(SendOrPostCallback d, object? state) { var del = scheduler.Add(() => d(state)); Debug.Assert(del != null); while (del.State == ScheduledDelegate.RunState.Waiting) scheduler.Update(); } public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state)); } } ```
3947e612-75a5-4c35-8c92-71952f77672d
{ "language": "C#" }
```c# namespace Boilerplate.Templates.Test { using System; using System.IO; using System.Threading.Tasks; public static class TempDirectoryExtensions { public static async Task<Project> DotnetNew( this TempDirectory tempDirectory, string templateName, string name = null, TimeSpan? timeout = null) { await ProcessAssert.AssertStart(tempDirectory.DirectoryPath, "dotnet", $"new {templateName} --name \"{name}\"", timeout ?? TimeSpan.FromSeconds(20)); var projectDirectoryPath = Path.Combine(tempDirectory.DirectoryPath, name); var projectFilePath = Path.Combine(projectDirectoryPath, name + ".csproj"); var publishDirectoryPath = Path.Combine(projectDirectoryPath, "Publish"); return new Project(name, projectFilePath, projectDirectoryPath, publishDirectoryPath); } } } ``` Add optional dotnet new arguments
```c# namespace Boilerplate.Templates.Test { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; public static class TempDirectoryExtensions { public static async Task<Project> DotnetNew( this TempDirectory tempDirectory, string templateName, string name, IDictionary<string, string> arguments = null, TimeSpan? timeout = null) { var stringBuilder = new StringBuilder($"new {templateName} --name \"{name}\""); if (arguments != null) { foreach (var argument in arguments) { stringBuilder.Append($" --{argument.Key} \"{argument.Value}\""); } } await ProcessAssert.AssertStart( tempDirectory.DirectoryPath, "dotnet", stringBuilder.ToString(), timeout ?? TimeSpan.FromSeconds(20)); var projectDirectoryPath = Path.Combine(tempDirectory.DirectoryPath, name); var projectFilePath = Path.Combine(projectDirectoryPath, name + ".csproj"); var publishDirectoryPath = Path.Combine(projectDirectoryPath, "Publish"); return new Project(name, projectFilePath, projectDirectoryPath, publishDirectoryPath); } } } ```
94bbcf29-08b5-457f-b14c-915bb507107c
{ "language": "C#" }
```c# using System; using System.IO; namespace MiniCover.HitServices { public static class HitService { public static MethodContext EnterMethod( string hitsPath, string assemblyName, string className, string methodName) { return new MethodContext(hitsPath, assemblyName, className, methodName); } public class MethodContext : IDisposable { private readonly string _hitsPath; private readonly HitContext _hitContext; private readonly bool _saveHitContext; public MethodContext( string hitsPath, string assemblyName, string className, string methodName) { _hitsPath = hitsPath; if (HitContext.Current == null) { _hitContext = new HitContext(assemblyName, className, methodName); HitContext.Current = _hitContext; _saveHitContext = true; } else { _hitContext = HitContext.Current; } } public void HitInstruction(int id) { _hitContext.RecordHit(id); } public void Dispose() { if (_saveHitContext) { Directory.CreateDirectory(_hitsPath); var filePath = Path.Combine(_hitsPath, $"{Guid.NewGuid()}.hits"); using (var fileStream = File.Open(filePath, FileMode.CreateNew)) { _hitContext.Serialize(fileStream); fileStream.Flush(); } HitContext.Current = null; } } } } }``` Create only 1 hit file per running process
```c# using System; using System.Collections.Concurrent; using System.IO; namespace MiniCover.HitServices { public static class HitService { public static MethodContext EnterMethod( string hitsPath, string assemblyName, string className, string methodName) { return new MethodContext(hitsPath, assemblyName, className, methodName); } public class MethodContext : IDisposable { private static ConcurrentDictionary<string, Stream> _filesStream = new ConcurrentDictionary<string, Stream>(); private readonly string _hitsPath; private readonly HitContext _hitContext; private readonly bool _saveHitContext; public MethodContext( string hitsPath, string assemblyName, string className, string methodName) { _hitsPath = hitsPath; if (HitContext.Current == null) { _hitContext = new HitContext(assemblyName, className, methodName); HitContext.Current = _hitContext; _saveHitContext = true; } else { _hitContext = HitContext.Current; } } public void HitInstruction(int id) { _hitContext.RecordHit(id); } public void Dispose() { if (_saveHitContext) { var fileStream = _filesStream.GetOrAdd(_hitsPath, CreateOutputFile); lock (fileStream) { _hitContext.Serialize(fileStream); fileStream.Flush(); } HitContext.Current = null; } } private static FileStream CreateOutputFile(string hitsPath) { Directory.CreateDirectory(hitsPath); var filePath = Path.Combine(hitsPath, $"{Guid.NewGuid()}.hits"); return File.Open(filePath, FileMode.CreateNew); } } } }```
fe54d887-dc72-41ea-a081-296df455ddd4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CompetitionPlatform.Data.BlogCategory { public class BlogCategoriesRepository : IBlogCategoriesRepository { public List<string> GetCategories() { return new List<string> { "News", "Results", "Winners", "Success stories", "Videos", "About" }; } } } ``` Add tutorials to blog categories.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CompetitionPlatform.Data.BlogCategory { public class BlogCategoriesRepository : IBlogCategoriesRepository { public List<string> GetCategories() { return new List<string> { "News", "Results", "Winners", "Success stories", "Videos", "About", "Tutorials" }; } } } ```
494861e7-f601-4953-9e64-09d6262708a7
{ "language": "C#" }
```c# using System; namespace LibGit2Sharp.Core { /// <summary> /// Provides helper methods to help converting between Epoch (unix timestamp) and <see cref="DateTimeOffset"/>. /// </summary> internal static class Epoch { private static readonly DateTimeOffset epochDateTimeOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); /// <summary> /// Builds a <see cref="DateTimeOffset"/> from a Unix timestamp and a timezone offset. /// </summary> /// <param name="secondsSinceEpoch">The number of seconds since 00:00:00 UTC on 1 January 1970.</param> /// <param name="timeZoneOffsetInMinutes">The number of minutes from UTC in a timezone.</param> /// <returns>A <see cref="DateTimeOffset"/> representing this instant.</returns> public static DateTimeOffset ToDateTimeOffset(long secondsSinceEpoch, int timeZoneOffsetInMinutes) { DateTimeOffset utcDateTime = epochDateTimeOffset.AddSeconds(secondsSinceEpoch); TimeSpan offset = TimeSpan.FromMinutes(timeZoneOffsetInMinutes); return new DateTimeOffset(utcDateTime.DateTime.Add(offset), offset); } /// <summary> /// Converts the<see cref="DateTimeOffset.UtcDateTime"/> part of a <see cref="DateTimeOffset"/> into a Unix timestamp. /// </summary> /// <param name="date">The <see cref="DateTimeOffset"/> to convert.</param> /// <returns>The number of seconds since 00:00:00 UTC on 1 January 1970.</returns> public static Int32 ToSecondsSinceEpoch(this DateTimeOffset date) { DateTimeOffset utcDate = date.ToUniversalTime(); return (Int32)utcDate.Subtract(epochDateTimeOffset).TotalSeconds; } } } ``` Replace helper implementation with DateOffset members
```c# using System; namespace LibGit2Sharp.Core { /// <summary> /// Provides helper methods to help converting between Epoch (unix timestamp) and <see cref="DateTimeOffset"/>. /// </summary> internal static class Epoch { /// <summary> /// Builds a <see cref="DateTimeOffset"/> from a Unix timestamp and a timezone offset. /// </summary> /// <param name="secondsSinceEpoch">The number of seconds since 00:00:00 UTC on 1 January 1970.</param> /// <param name="timeZoneOffsetInMinutes">The number of minutes from UTC in a timezone.</param> /// <returns>A <see cref="DateTimeOffset"/> representing this instant.</returns> public static DateTimeOffset ToDateTimeOffset(long secondsSinceEpoch, int timeZoneOffsetInMinutes) => DateTimeOffset.FromUnixTimeSeconds(secondsSinceEpoch).ToOffset(TimeSpan.FromMinutes(timeZoneOffsetInMinutes)); /// <summary> /// Converts the<see cref="DateTimeOffset.UtcDateTime"/> part of a <see cref="DateTimeOffset"/> into a Unix timestamp. /// </summary> /// <param name="date">The <see cref="DateTimeOffset"/> to convert.</param> /// <returns>The number of seconds since 00:00:00 UTC on 1 January 1970.</returns> public static Int32 ToSecondsSinceEpoch(this DateTimeOffset date) => (int)date.ToUnixTimeSeconds(); } } ```
3fb07bbb-07a5-46a0-8891-0517a0f4d72a
{ "language": "C#" }
```c# using System; namespace Views { [System.ComponentModel.ToolboxItem(true)] public partial class BooleanRadioButton : Gtk.Bin, IEditable { String[] labels; bool isEditable; public BooleanRadioButton () { this.Build (); } public String[] Labels { get { return this.labels; } set { labels = value; radiobutton_true.Label = labels[0]; radiobutton_false.Label = labels[1]; } } public bool Value () { if (radiobutton_true.Active) return true; else return false; } public bool IsEditable { get { return this.isEditable; } set { isEditable = value; radiobutton_true.Visible = value; radiobutton_false.Visible = value; text.Visible = !value; text.Text = radiobutton_true.Active ? labels[0] : labels[1]; } } public new bool Activate { get { return Value (); } set { bool state = value; if (state) radiobutton_true.Activate (); else radiobutton_false.Activate (); } } } }``` Fix RadioButtons, need to use Active insted of Activate.
```c# using System; namespace Views { [System.ComponentModel.ToolboxItem(true)] public partial class BooleanRadioButton : Gtk.Bin, IEditable { String[] labels; bool isEditable; public BooleanRadioButton () { this.Build (); } public String[] Labels { get { return this.labels; } set { labels = value; radiobutton_true.Label = labels[0]; radiobutton_false.Label = labels[1]; } } public bool Value () { if (radiobutton_true.Active) return true; else return false; } public bool IsEditable { get { return this.isEditable; } set { isEditable = value; radiobutton_true.Visible = value; radiobutton_false.Visible = value; text.Visible = !value; text.Text = radiobutton_true.Active ? labels[0] : labels[1]; } } public new bool Activate { get { return Value (); } set { bool state = value; if (state) { radiobutton_true.Active = true; } else { radiobutton_false.Active = true; } } } } }```
0e7f3b96-1664-485d-af33-8e175e3e236e
{ "language": "C#" }
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ``` Update server side API for single multiple answer question
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } } ```
a7bea8d4-1478-4db5-8522-a10779d5d908
{ "language": "C#" }
```c# <article id="cookies-disabled-panel" class="panel-inverse"> <h1>Cookies are disabled</h1> <section> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </section> </br> </br> </article> ``` Use localized content for cookies disabled message
```c# <article id="cookies-disabled-panel" class="panel-inverse"> <h1>@Text.Content.CookiesDisabledHeading</h1> <section> @Text.Content.CookiesDisabledDetails </section> </br> </br> </article> ```
2fb12a0e-602c-4cc9-9360-5b655188eee3
{ "language": "C#" }
```c# using System; using System.IO; namespace GitHub.Unity { class DefaultEnvironment : IEnvironment { public string GetSpecialFolder(Environment.SpecialFolder folder) { return Environment.GetFolderPath(folder); } public string ExpandEnvironmentVariables(string name) { return Environment.ExpandEnvironmentVariables(name); } public string GetEnvironmentVariable(string variable) { return Environment.GetEnvironmentVariable(variable); } public string UserProfilePath { get { return Environment.GetEnvironmentVariable("USERPROFILE"); } } public string Path { get { return Environment.GetEnvironmentVariable("PATH"); } } public string NewLine { get { return Environment.NewLine; } } public string GitInstallPath { get; set; } public bool IsWindows { get { return !IsLinux && !IsMac; } } public bool IsLinux { get { return Environment.OSVersion.Platform == PlatformID.Unix && Directory.Exists("/proc"); } } public bool IsMac { get { // most likely it'll return the proper id but just to be on the safe side, have a fallback return Environment.OSVersion.Platform == PlatformID.MacOSX || (Environment.OSVersion.Platform == PlatformID.Unix && !Directory.Exists("/proc")); } } } }``` Optimize windows platform detection code
```c# using System; using System.IO; namespace GitHub.Unity { class DefaultEnvironment : IEnvironment { public string GetSpecialFolder(Environment.SpecialFolder folder) { return Environment.GetFolderPath(folder); } public string ExpandEnvironmentVariables(string name) { return Environment.ExpandEnvironmentVariables(name); } public string GetEnvironmentVariable(string variable) { return Environment.GetEnvironmentVariable(variable); } public string UserProfilePath { get { return Environment.GetEnvironmentVariable("USERPROFILE"); } } public string Path { get { return Environment.GetEnvironmentVariable("PATH"); } } public string NewLine { get { return Environment.NewLine; } } public string GitInstallPath { get; set; } public bool IsWindows { get { return Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX; } } public bool IsLinux { get { return Environment.OSVersion.Platform == PlatformID.Unix && Directory.Exists("/proc"); } } public bool IsMac { get { // most likely it'll return the proper id but just to be on the safe side, have a fallback return Environment.OSVersion.Platform == PlatformID.MacOSX || (Environment.OSVersion.Platform == PlatformID.Unix && !Directory.Exists("/proc")); } } } }```
c35cd754-a5ea-4675-b644-d76c03fb4f69
{ "language": "C#" }
```c# using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.AspNetCore.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]``` Make project comvisible explicitly set to false to meet compliance requirements.
```c# using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.AspNetCore.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: ComVisible(false)]```
5a1d1b26-12ca-48d0-b4ba-07a44e43f042
{ "language": "C#" }
```c# namespace Stripe.Issuing { using System.Collections.Generic; using Newtonsoft.Json; public class AuthorizationControls : StripeEntity { [JsonProperty("allowed_categories")] public List<string> AllowedCategories { get; set; } [JsonProperty("blocked_categories")] public List<string> BlockedCategories { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("max_amount")] public long MaxAmount { get; set; } [JsonProperty("max_approvals")] public long MaxApprovals { get; set; } } } ``` Support nullable properties on authorization_controls
```c# namespace Stripe.Issuing { using System.Collections.Generic; using Newtonsoft.Json; public class AuthorizationControls : StripeEntity { [JsonProperty("allowed_categories")] public List<string> AllowedCategories { get; set; } [JsonProperty("blocked_categories")] public List<string> BlockedCategories { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("max_amount")] public long? MaxAmount { get; set; } [JsonProperty("max_approvals")] public long? MaxApprovals { get; set; } } } ```
a9d22b11-49e3-4f79-ab2b-bbb1c3fe3f66
{ "language": "C#" }
```c# @using System.Web.Mvc.Html @using Sitecore.Feature.FAQ.Repositories @using Sitecore.Feature.FAQ @using Sitecore.Data.Items @model Sitecore.Mvc.Presentation.RenderingModel @{ var elements = GroupMemberRepository.Get(Model.Item).ToArray(); int i = 1; } @foreach (Item item in elements) { var ID = Guid.NewGuid().ToString(); <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#@ID"> @Html.Sitecore().Field(Templates.Faq.Fields.Question_FieldName, item) </a> </h4> </div> <div id=@ID class="panel-collapse collapse"> <div class="panel-body"> @Html.Sitecore().Field(Templates.Faq.Fields.Answer_FieldName,item) </div> </div> </div> <!-- /.panel --> </div> } @if (Sitecore.Context.PageMode.IsPageEditor) { <script> $('.panel-collapse').toggle(); </script> }``` Change the HTML according to the new Habitat theming
```c# @using System.Web.Mvc.Html @using Sitecore.Feature.FAQ.Repositories @using Sitecore.Feature.FAQ @using Sitecore.Data.Items @model Sitecore.Mvc.Presentation.RenderingModel @{ var elements = GroupMemberRepository.Get(Model.Item).ToArray(); } @foreach (Item item in elements) { var ID = Guid.NewGuid().ToString(); <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingcollapse0"> <h4 class="panel-title"> <a role="button" class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#@ID"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> @Html.Sitecore().Field(Templates.Faq.Fields.Question_FieldName, item) </a> </h4> </div> <div id=@ID class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingcollapse0"> <div class="panel-body"> @Html.Sitecore().Field(Templates.Faq.Fields.Answer_FieldName,item) </div> </div> </div> <!-- /.panel --> </div> } @if (Sitecore.Context.PageMode.IsPageEditor) { <script> $('.panel-collapse').toggle(); </script> }```
69ae5912-7e11-458a-9d53-7c04a1de8972
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Wcf")] [assembly: AssemblyDescription("")] ``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Wcf")] ```
c7d769ad-8cf7-4328-a5f8-bbd5a9bf2228
{ "language": "C#" }
```c# using System; using NUnit.Framework; using DevTyr.Gullap; namespace DevTyr.Gullap.Tests.With_Converter.For_SetParser { [TestFixture] public class When_argument_is_null { [Test] public void Should_throw_argument_exception () { var converter = new Converter (new ConverterOptions { SitePath = "any" }); Assert.Throws<ArgumentException> (() => converter.SetParser (null)); } [Test] public void Should_throw_exception_with_proper_message () { var converter = new Converter (new ConverterOptions { SitePath = "any" }); Assert.Throws<ArgumentException> (() => converter.SetParser (null), "No valid parser given"); } } } ``` Change exception type for null argument to ArgumentNullException.
```c# using System; using NUnit.Framework; using DevTyr.Gullap; namespace DevTyr.Gullap.Tests.With_Converter.For_SetParser { [TestFixture] public class When_argument_is_null { [Test] public void Should_throw_argument_null_exception () { var converter = new Converter (new ConverterOptions { SitePath = "any" }); Assert.Throws<ArgumentNullException> (() => converter.SetParser (null)); } [Test] public void Should_throw_exception_with_proper_message () { var converter = new Converter (new ConverterOptions { SitePath = "any" }); Assert.Throws<ArgumentNullException> (() => converter.SetParser (null), "No valid parser given"); } } } ```
fef4d734-2eac-4815-bb4e-f0dd3a29e717
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Avalonia.Data.Converters; using Avalonia.Media; using AvalonStudio.Extensibility.Theme; using WalletWasabi.Models; namespace WalletWasabi.Gui.Converters { public class StatusColorConvertor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool isTor = Enum.TryParse(value.ToString(), out TorStatus tor); if (isTor && tor == TorStatus.NotRunning) { return Brushes.Red; } bool isBackend = Enum.TryParse(value.ToString(), out BackendStatus backend); if (isBackend && backend == BackendStatus.NotConnected) { return Brushes.Red; } return ColorTheme.CurrentTheme.Foreground; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } } ``` Change statusbar errors to yellow
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Avalonia.Data.Converters; using Avalonia.Media; using AvalonStudio.Extensibility.Theme; using WalletWasabi.Models; namespace WalletWasabi.Gui.Converters { public class StatusColorConvertor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool isTor = Enum.TryParse(value.ToString(), out TorStatus tor); if (isTor && tor == TorStatus.NotRunning) { return Brushes.Yellow; } bool isBackend = Enum.TryParse(value.ToString(), out BackendStatus backend); if (isBackend && backend == BackendStatus.NotConnected) { return Brushes.Yellow; } return ColorTheme.CurrentTheme.Foreground; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } } ```
f0553a18-d59a-4747-9efa-746cd15b4cde
{ "language": "C#" }
```c# // <copyright file="TextFilePropertyStoreOptions.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> namespace FubarDev.WebDavServer.Props.Store.TextFile { public class TextFilePropertyStoreOptions { public int EstimatedCost { get; set; } public string RootFolder { get; set; } public bool StoreInTargetFileSystem { get; set; } } } ``` Increase the estinated cost for the text file property store to 10 to avoid fetching all dead properties
```c# // <copyright file="TextFilePropertyStoreOptions.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> namespace FubarDev.WebDavServer.Props.Store.TextFile { public class TextFilePropertyStoreOptions { public int EstimatedCost { get; set; } = 10; public string RootFolder { get; set; } public bool StoreInTargetFileSystem { get; set; } } } ```
5d82bf3a-88f2-4c4f-b3e3-fff9250d6cd9
{ "language": "C#" }
```c# using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [PropertyValueType(typeof(decimal))] [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) { return Constants.PropertyEditors.DecimalAlias.Equals(propertyType.PropertyEditorAlias); } public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { if (source == null) return 0M; // in XML a decimal is a string var sourceString = source as string; if (sourceString != null) { decimal d; return (decimal.TryParse(sourceString, out d)) ? d : 0M; } // in the database an a decimal is an a decimal // default value is zero return (source is decimal) ? source : 0M; } } } ``` Fix decimal property value converter to work on non EN-US cultures
```c# using System.Globalization; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [PropertyValueType(typeof(decimal))] [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) { return Constants.PropertyEditors.DecimalAlias.Equals(propertyType.PropertyEditorAlias); } public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { if (source == null) return 0M; // in XML a decimal is a string var sourceString = source as string; if (sourceString != null) { decimal d; return (decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) ? d : 0M; } // in the database an a decimal is an a decimal // default value is zero return (source is decimal) ? source : 0M; } } } ```
bcfcf1e0-95a6-4342-aef9-07c150b3f22f
{ "language": "C#" }
```c# namespace TAUtil.Gdi.Bitmap { using System.Drawing; using System.Drawing.Imaging; using System.IO; using TAUtil.Gdi.Palette; /// <summary> /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data. /// The mapping from color to index is done according to the given /// reverse palette lookup. /// </summary> public class BitmapSerializer { private readonly IPalette palette; public BitmapSerializer(IPalette palette) { this.palette = palette; } public byte[] ToBytes(Bitmap bitmap) { int length = bitmap.Width * bitmap.Height; byte[] output = new byte[length]; this.Serialize(new MemoryStream(output, true), bitmap); return output; } public void Serialize(Stream output, Bitmap bitmap) { Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat); int length = bitmap.Width * bitmap.Height; unsafe { int* pointer = (int*)data.Scan0; for (int i = 0; i < length; i++) { Color c = Color.FromArgb(pointer[i]); output.WriteByte((byte)this.palette.LookUp(c)); } } bitmap.UnlockBits(data); } } }``` Fix bitmap serialization with indexed format bitmaps
```c# namespace TAUtil.Gdi.Bitmap { using System.Drawing; using System.Drawing.Imaging; using System.IO; using TAUtil.Gdi.Palette; /// <summary> /// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data. /// The mapping from color to index is done according to the given /// reverse palette lookup. /// </summary> public class BitmapSerializer { private readonly IPalette palette; public BitmapSerializer(IPalette palette) { this.palette = palette; } public byte[] ToBytes(Bitmap bitmap) { int length = bitmap.Width * bitmap.Height; byte[] output = new byte[length]; this.Serialize(new MemoryStream(output, true), bitmap); return output; } public void Serialize(Stream output, Bitmap bitmap) { Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int length = bitmap.Width * bitmap.Height; unsafe { int* pointer = (int*)data.Scan0; for (int i = 0; i < length; i++) { Color c = Color.FromArgb(pointer[i]); output.WriteByte((byte)this.palette.LookUp(c)); } } bitmap.UnlockBits(data); } } }```
82984b09-0e9b-4e2b-8183-2abdebfa26a3
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using FilterLists.Agent.AppSettings; using FilterLists.Agent.Extensions; using FilterLists.Agent.Features.Lists; using FilterLists.Agent.Features.Urls; using FilterLists.Agent.Features.Urls.Models.DataFileUrls; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FilterLists.Agent { public static class Program { private static IServiceProvider _serviceProvider; public static async Task Main() { BuildServiceProvider(); var mediator = _serviceProvider.GetService<IOptions<GitHub>>().Value; Console.WriteLine(mediator.ProductHeaderValue); //await mediator.Send(new CaptureLists.Command()); //await mediator.Send(new ValidateAllUrls.Command()); } private static void BuildServiceProvider() { var serviceCollection = new ServiceCollection(); serviceCollection.RegisterAgentServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); } } }``` Revert "TEMP: test env vars on prod"
```c# using System; using System.Threading.Tasks; using FilterLists.Agent.Extensions; using FilterLists.Agent.Features.Lists; using FilterLists.Agent.Features.Urls; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace FilterLists.Agent { public static class Program { private static IServiceProvider _serviceProvider; public static async Task Main() { BuildServiceProvider(); var mediator = _serviceProvider.GetService<IMediator>(); await mediator.Send(new CaptureLists.Command()); await mediator.Send(new ValidateAllUrls.Command()); } private static void BuildServiceProvider() { var serviceCollection = new ServiceCollection(); serviceCollection.RegisterAgentServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); } } }```
3c5fb21b-48fd-4eea-9a69-b673e5d20a94
{ "language": "C#" }
```c# using System.ComponentModel.DataAnnotations; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Models { /// <inheritdoc /> public sealed class RepositorySettings : Api.Models.Internal.RepositorySettings { /// <summary> /// The row Id /// </summary> public long Id { get; set; } /// <summary> /// The instance <see cref="EntityId.Id"/> /// </summary> public long InstanceId { get; set; } /// <summary> /// The parent <see cref="Models.Instance"/> /// </summary> [Required] public Instance Instance { get; set; } /// <summary> /// Convert the <see cref="Repository"/> to it's API form /// </summary> /// <returns>A new <see cref="Repository"/></returns> public Repository ToApi() => new Repository { // AccessToken = AccessToken, // never show this AccessUser = AccessUser, AutoUpdatesKeepTestMerges = AutoUpdatesKeepTestMerges, AutoUpdatesSynchronize = AutoUpdatesSynchronize, CommitterEmail = CommitterEmail, CommitterName = CommitterName, PushTestMergeCommits = PushTestMergeCommits, ShowTestMergeCommitters = ShowTestMergeCommitters, PostTestMergeComment = PostTestMergeComment // revision information and the rest retrieved by controller }; } } ``` Fix Repository's `createGitHubDeployments` not being returned in API responses
```c# using System.ComponentModel.DataAnnotations; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Models { /// <inheritdoc /> public sealed class RepositorySettings : Api.Models.Internal.RepositorySettings { /// <summary> /// The row Id /// </summary> public long Id { get; set; } /// <summary> /// The instance <see cref="EntityId.Id"/> /// </summary> public long InstanceId { get; set; } /// <summary> /// The parent <see cref="Models.Instance"/> /// </summary> [Required] public Instance Instance { get; set; } /// <summary> /// Convert the <see cref="Repository"/> to it's API form /// </summary> /// <returns>A new <see cref="Repository"/></returns> public Repository ToApi() => new Repository { // AccessToken = AccessToken, // never show this AccessUser = AccessUser, AutoUpdatesKeepTestMerges = AutoUpdatesKeepTestMerges, AutoUpdatesSynchronize = AutoUpdatesSynchronize, CommitterEmail = CommitterEmail, CommitterName = CommitterName, PushTestMergeCommits = PushTestMergeCommits, ShowTestMergeCommitters = ShowTestMergeCommitters, PostTestMergeComment = PostTestMergeComment, CreateGitHubDeployments = CreateGitHubDeployments, // revision information and the rest retrieved by controller }; } } ```
af2cfb80-69bc-43be-98ea-2c799cfb98bd
{ "language": "C#" }
```c# // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.3.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.3.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")] #endif``` Update OData assembly versions to 5.3.1.0
```c# // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.3.1.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.3.1.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")] #endif```
ad632ada-ceae-4e39-b5e1-70b3636543ae
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Birdy : MonoBehaviour { public bool IsAlive; public float DropDeadTime = 0.5f; public MoveForward Mover; public ScriptSwitch FlyToFallSwitch; public FallDown FallDown; public MonoBehaviour[] Feeders; // Use this for initialization void Start () { FallDown.Time = DropDeadTime; } // Update is called once per frame void Update () { } public void DropDead() { if (!IsAlive) { return; } Mover.Speed = Random.Range(5/DropDeadTime, 10/DropDeadTime); FlyToFallSwitch.Switch(); LeanTween.delayedCall(gameObject, DropDeadTime, TurnOffMover); IsAlive = false; } private void TurnOffMover() { this.IsDown = true; this.Mover.enabled = false; foreach (var monoBehaviour in this.Feeders) { monoBehaviour.enabled = true; } } public bool IsDown { get; set; } } ``` Stop bird animation on drop down
```c# using UnityEngine; using System.Collections; public class Birdy : MonoBehaviour { public bool IsAlive; public float DropDeadTime = 0.5f; public MoveForward Mover; public ScriptSwitch FlyToFallSwitch; public FallDown FallDown; public MonoBehaviour[] Feeders; // Use this for initialization void Start () { FallDown.Time = DropDeadTime; } // Update is called once per frame void Update () { } public void DropDead() { if (!IsAlive) { return; } Mover.Speed = Random.Range(5/DropDeadTime, 10/DropDeadTime); this.GetComponentInChildren<Animator>().enabled = false; FlyToFallSwitch.Switch(); LeanTween.delayedCall(gameObject, DropDeadTime, TurnOffMover); this.transform.GetChild(0).tag = "Food"; IsAlive = false; } private void TurnOffMover() { this.IsDown = true; this.Mover.enabled = false; foreach (var monoBehaviour in this.Feeders) { monoBehaviour.enabled = true; } } public bool IsDown { get; set; } } ```
bdc852b6-250f-43de-9aa5-6293a02c621d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BrightstarDB.ReadWriteBenchmark { internal class Program { private static void Main(string[] args) { var opts = new BenchmarkArgs(); if (CommandLine.Parser.ParseArgumentsWithUsage(args, opts)) { if (!string.IsNullOrEmpty(opts.LogFilePath)) { BenchmarkLogging.EnableFileLogging(opts.LogFilePath); } } else { var usage = CommandLine.Parser.ArgumentsUsage(typeof (BenchmarkArgs)); Console.WriteLine(usage); } var runner = new BenchmarkRunner(opts); runner.Run(); BenchmarkLogging.Close(); } } } ``` Write BrightstarDB log output if a log file is specified
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BrightstarDB.ReadWriteBenchmark { internal class Program { public static TraceListener BrightstarListener; private static void Main(string[] args) { var opts = new BenchmarkArgs(); if (CommandLine.Parser.ParseArgumentsWithUsage(args, opts)) { if (!string.IsNullOrEmpty(opts.LogFilePath)) { BenchmarkLogging.EnableFileLogging(opts.LogFilePath); var logStream = new FileStream(opts.LogFilePath + ".bslog", FileMode.Create); BrightstarListener = new TextWriterTraceListener(logStream); BrightstarDB.Logging.BrightstarTraceSource.Listeners.Add(BrightstarListener); BrightstarDB.Logging.BrightstarTraceSource.Switch.Level = SourceLevels.All; } } else { var usage = CommandLine.Parser.ArgumentsUsage(typeof (BenchmarkArgs)); Console.WriteLine(usage); } var runner = new BenchmarkRunner(opts); runner.Run(); BenchmarkLogging.Close(); BrightstarDB.Logging.BrightstarTraceSource.Close(); } } } ```
a9065b1d-db5c-4a86-9b1c-d0f169a5c798
{ "language": "C#" }
```c# using System; using System.Linq; using System.Reflection; using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap { internal class AspNetConstructorSelector : IConstructorSelector { // ASP.NET expects registered services to be considered when selecting a ctor, SM doesn't by default. public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) { var constructors = from constructor in pluggedType.GetConstructors() select new { Constructor = constructor, Parameters = constructor.GetParameters(), }; var satisfiable = from constructor in constructors where constructor.Parameters.All(parameter => ParameterIsRegistered(parameter, dependencies, graph)) orderby constructor.Parameters.Length descending select constructor.Constructor; return satisfiable.FirstOrDefault(); } private static bool ParameterIsRegistered(ParameterInfo parameter, DependencyCollection dependencies, PluginGraph graph) { return graph.HasFamily(parameter.ParameterType) || dependencies.Any(dependency => dependency.Type == parameter.ParameterType); } } } ``` Revert to method LINQ syntax.
```c# using System; using System.Linq; using System.Reflection; using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap { internal class AspNetConstructorSelector : IConstructorSelector { // ASP.NET expects registered services to be considered when selecting a ctor, SM doesn't by default. public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) => pluggedType.GetTypeInfo() .DeclaredConstructors .Select(ctor => new { Constructor = ctor, Parameters = ctor.GetParameters() }) .Where(x => x.Parameters.All(param => graph.HasFamily(param.ParameterType) || dependencies.Any(dep => dep.Type == param.ParameterType))) .OrderByDescending(x => x.Parameters.Length) .Select(x => x.Constructor) .FirstOrDefault(); } } ```
3a8b657b-b237-4c7a-8f84-ed8b0a2e6f94
{ "language": "C#" }
```c# // Copyright (c) 2015 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Linq; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Core.Clusters; namespace LfMerge { public class LanguageDepotProject { public LanguageDepotProject(string lfProjectCode) { var client = new MongoClient("mongodb://" + LfMergeSettings.Current.MongoDbHostNameAndPort); var database = client.GetDatabase("languageforge"); var collection = database.GetCollection<BsonDocument>("projects"); var filter = new BsonDocument("projectCode", lfProjectCode); var list = collection.Find(filter).ToListAsync(); list.Wait(); var project = list.Result.FirstOrDefault(); if (project == null) throw new ArgumentException("Can't find project code", "lfProjectCode"); BsonValue value; if (project.TryGetValue("ldUsername", out value)) Username = value.AsString; if (project.TryGetValue("ldPassword", out value)) Password = value.AsString; if (project.TryGetValue("ldProjectCode", out value)) ProjectCode = value.AsString; } public string Username { get; private set; } public string Password { get; private set; } public string ProjectCode { get; private set; } } } ``` Use scriptureforge database to get project data
```c# // Copyright (c) 2015 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Linq; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Core.Clusters; namespace LfMerge { public class LanguageDepotProject { public LanguageDepotProject(string lfProjectCode) { var client = new MongoClient("mongodb://" + LfMergeSettings.Current.MongoDbHostNameAndPort); var database = client.GetDatabase("scriptureforge"); var projectCollection = database.GetCollection<BsonDocument>("projects"); //var userCollection = database.GetCollection<BsonDocument>("users"); var projectFilter = new BsonDocument("projectCode", lfProjectCode); var list = projectCollection.Find(projectFilter).ToListAsync(); list.Wait(); var project = list.Result.FirstOrDefault(); if (project == null) throw new ArgumentException("Can't find project code", "lfProjectCode"); BsonValue value; if (project.TryGetValue("ldProjectCode", out value)) ProjectCode = value.AsString; // TODO: need to get S/R server (language depot public, language depot private, custom, etc). // TODO: ldUsername and ldPassword should come from the users collection if (project.TryGetValue("ldUsername", out value)) Username = value.AsString; if (project.TryGetValue("ldPassword", out value)) Password = value.AsString; } public string Username { get; private set; } public string Password { get; private set; } public string ProjectCode { get; private set; } } } ```
093cf2fd-dc0b-4882-b968-0d09d329430d
{ "language": "C#" }
```c# using LiteNetLib; using LiteNetLib.Utils; using LiteNetLibManager; public static class LiteNetLibPacketSender { public static readonly NetDataWriter Writer = new NetDataWriter(); public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer) { writer.Reset(); writer.Put(msgType); serializer(writer); peer.Send(writer, options); } public static void SendPacket(SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer) { SendPacket(Writer, options, peer, msgType, serializer); } public static void SendPacket<T>(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage { SendPacket(writer, options, peer, msgType, messageData.Serialize); } public static void SendPacket<T>(SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage { SendPacket(Writer, options, peer, msgType, messageData); } public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType) { writer.Reset(); writer.Put(msgType); peer.Send(writer, options); } public static void SendPacket(SendOptions options, NetPeer peer, short msgType) { SendPacket(Writer, options, peer, msgType); } } ``` Improve packet sender seralize codes
```c# using LiteNetLib; using LiteNetLib.Utils; using LiteNetLibManager; public static class LiteNetLibPacketSender { public static readonly NetDataWriter Writer = new NetDataWriter(); public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer) { writer.Reset(); writer.Put(msgType); if (serializer != null) serializer(writer); peer.Send(writer, options); } public static void SendPacket(SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer) { SendPacket(Writer, options, peer, msgType, serializer); } public static void SendPacket<T>(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage { SendPacket(writer, options, peer, msgType, messageData.Serialize); } public static void SendPacket<T>(SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage { SendPacket(Writer, options, peer, msgType, messageData); } public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType) { SendPacket(writer, options, peer, msgType, null); } public static void SendPacket(SendOptions options, NetPeer peer, short msgType) { SendPacket(Writer, options, peer, msgType); } } ```
2bcfe959-a371-4d4c-b54a-4fbad9e04375
{ "language": "C#" }
```c# using System; using System.Net; using System.Net.Http; using Knapcode.SocketToMe.Http; using Knapcode.SocketToMe.Socks; namespace Knapcode.SocketToMe.Sandbox { public class Program { private static void Main() { var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150); var client = new Socks5Client(); var socket = client.ConnectToServer(endpoint); socket = client.ConnectToDestination(socket, "icanhazip.com", 80); var httpClient = new HttpClient(new NetworkHandler(socket)); var response = httpClient.GetAsync("http://icanhazip.com/").Result; Console.WriteLine(response.Content.ReadAsStringAsync().Result); } } }``` Make the sandbox example even more complex
```c# using System; using System.Net; using System.Net.Http; using Knapcode.SocketToMe.Http; using Knapcode.SocketToMe.Socks; namespace Knapcode.SocketToMe.Sandbox { public class Program { private static void Main() { var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150); var client = new Socks5Client(); var socket = client.ConnectToServer(endpoint); socket = client.ConnectToDestination(socket, "icanhazip.com", 443); var httpClient = new HttpClient(new NetworkHandler(socket)); var response = httpClient.GetAsync("https://icanhazip.com/").Result; Console.WriteLine(response.Content.ReadAsStringAsync().Result); } } }```
d8b8b602-0c91-4e3d-8511-0215222a4df0
{ "language": "C#" }
```c# using System; using System.Diagnostics.Tracing; namespace tracelogging { public sealed class MySource : EventSource { MySource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { } public static MySource Logger = new MySource(); } class Program { static void Main(string[] args) { MySource.Logger.Write("TestEvent", new { field1 = "Hello", field2 = 3, field3 = 6 }); MySource.Logger.Write("TestEvent1", new { field1 = "Hello", field2 = 3, }); MySource.Logger.Write("TestEvent2", new { field1 = "Hello" }); MySource.Logger.Write("TestEvent3", new { field1 = new byte[10] }); } } } ``` Add event method to TraceLogging test.
```c# using System; using System.Diagnostics.Tracing; namespace tracelogging { public sealed class MySource : EventSource { MySource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { } [Event(1)] public void TestEventMethod(int i, string s) { WriteEvent(1, i, s); } public static MySource Logger = new MySource(); } class Program { static void Main(string[] args) { MySource.Logger.TestEventMethod(1, "Hello World!"); MySource.Logger.Write("TestEvent", new { field1 = "Hello", field2 = 3, field3 = 6 }); MySource.Logger.Write("TestEvent1", new { field1 = "Hello", field2 = 3, }); MySource.Logger.Write("TestEvent2", new { field1 = "Hello" }); MySource.Logger.Write("TestEvent3", new { field1 = new byte[10] }); } } } ```
ee8eb333-1d26-4b86-ab4e-4938937f076a
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Text; namespace osu.Framework.Benchmarks { public class BenchmarkTextBuilder { private readonly ITexturedGlyphLookupStore store = new TestStore(); private TextBuilder textBuilder; [Benchmark] public void AddCharacters() => initialiseBuilder(false); [Benchmark] public void RemoveLastCharacter() { initialiseBuilder(false); textBuilder.RemoveLastCharacter(); } private void initialiseBuilder(bool allDifferentBaselines) { textBuilder = new TextBuilder(store, FontUsage.Default); char different = 'B'; for (int i = 0; i < 100; i++) textBuilder.AddCharacter(i % (allDifferentBaselines ? 1 : 10) == 0 ? different++ : 'A'); } private class TestStore : ITexturedGlyphLookupStore { public ITexturedCharacterGlyph Get(string fontName, char character) => new TexturedCharacterGlyph(new CharacterGlyph(character, character, character, character, null), Texture.WhitePixel); public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => Task.Run(() => Get(fontName, character)); } } } ``` Update benchmark and add worst case scenario
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Text; namespace osu.Framework.Benchmarks { public class BenchmarkTextBuilder { private readonly ITexturedGlyphLookupStore store = new TestStore(); private TextBuilder textBuilder; [Benchmark] public void AddCharacters() => initialiseBuilder(false); [Benchmark] public void AddCharactersWithDifferentBaselines() => initialiseBuilder(true); [Benchmark] public void RemoveLastCharacter() { initialiseBuilder(false); textBuilder.RemoveLastCharacter(); } [Benchmark] public void RemoveLastCharacterWithDifferentBaselines() { initialiseBuilder(true); textBuilder.RemoveLastCharacter(); } private void initialiseBuilder(bool withDifferentBaselines) { textBuilder = new TextBuilder(store, FontUsage.Default); char different = 'B'; for (int i = 0; i < 100; i++) textBuilder.AddCharacter(withDifferentBaselines && (i % 10 == 0) ? different++ : 'A'); } private class TestStore : ITexturedGlyphLookupStore { public ITexturedCharacterGlyph Get(string fontName, char character) => new TexturedCharacterGlyph(new CharacterGlyph(character, character, character, character, character, null), Texture.WhitePixel); public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => Task.Run(() => Get(fontName, character)); } } } ```
888ee85b-97d7-46a4-8d9e-aab76f2eec22
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lezen.Core.Entity { public class Document { public Document() { this.Authors = new HashSet<Author>(); } public int ID { get; set; } public string Title { get; set; } public virtual ICollection<Author> Authors { get; private set; } } } ``` Change private setter to public.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lezen.Core.Entity { public class Document { public Document() { this.Authors = new HashSet<Author>(); } public int ID { get; set; } public string Title { get; set; } public virtual ICollection<Author> Authors { get; set; } } } ```
87e18a4e-2fd0-48bf-9294-f989a8c6584e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CardsAgainstIRC3.Game.Bots { [Bot("rando")] public class Rando : IBot { public GameManager Manager { get; private set; } public GameUser User { get; private set; } public Rando(GameManager manager) { Manager = manager; } public void RegisteredToUser(GameUser user) { User = user; } public Card[] ResponseToCard(Card blackCard) { return Manager.TakeWhiteCards(blackCard.Parts.Length - 1).ToArray(); } } } ``` Fix wrong method name, causing a build error
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CardsAgainstIRC3.Game.Bots { [Bot("rando")] public class Rando : IBot { public GameManager Manager { get; private set; } public GameUser User { get; private set; } public Rando(GameManager manager) { Manager = manager; } public void LinkedToUser(GameUser user) { User = user; } public Card[] ResponseToCard(Card blackCard) { return Manager.TakeWhiteCards(blackCard.Parts.Length - 1).ToArray(); } } } ```
f95e0a53-afac-489b-bc3d-93ef2d0f2484
{ "language": "C#" }
```c# using System.Text.RegularExpressions; using System.Windows.Forms; namespace Subtle.UI.Controls { public class ImdbTextBox : TextBox { // ReSharper disable once InconsistentNaming private const int WM_PASTE = 0x0302; private static readonly Regex ImdbRegex = new Regex(@"tt(\d{7})"); /// <summary> /// Handles paste event and tries to extract IMDb ID. /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { if (m.Msg != WM_PASTE) { base.WndProc(ref m); return; } var match = ImdbRegex.Match(Clipboard.GetText()); if (match.Success) { Text = match.Groups[1].Value; } } } }``` Correct default paste behaviour for IMDb textbox
```c# using System.Text.RegularExpressions; using System.Windows.Forms; namespace Subtle.UI.Controls { public class ImdbTextBox : TextBox { // ReSharper disable once InconsistentNaming private const int WM_PASTE = 0x0302; private static readonly Regex ImdbRegex = new Regex(@"tt(\d{7})"); /// <summary> /// Handles paste event and tries to extract IMDb ID. /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { if (m.Msg != WM_PASTE) { base.WndProc(ref m); return; } var match = ImdbRegex.Match(Clipboard.GetText()); if (match.Success) { Text = match.Groups[1].Value; } else { base.WndProc(ref m); } } } }```
1acd3701-cd24-4115-ae36-84dfc96881a6
{ "language": "C#" }
```c# @model JoinRpg.Web.Models.CheckIn.CheckInIndexViewModel @{ ViewBag.Title = "Регистрация"; } <h2>Регистрация</h2> @using (Html.BeginForm()) { @Html.HiddenFor(model => model.ProjectId) @Html.AntiForgeryToken() @Html.SearchableDropdownFor(model => model.ClaimId, Model.Claims.Select( claim => new ImprovedSelectListItem() { Value = claim.ClaimId.ToString(), Text = claim.CharacterName, ExtraSearch = claim.OtherNicks, Subtext = "<br />" + claim.NickName + " (" + claim.Fullname + " )" })) <input type="submit" class="btn btn-success" value="Зарегистрировать"/> } <hr/> @Html.ActionLink("Статистика по регистрации", "Stat", new {Model.ProjectId}) ``` Remove <br> from select in checkin
```c# @model JoinRpg.Web.Models.CheckIn.CheckInIndexViewModel @{ ViewBag.Title = "Регистрация"; } <h2>Регистрация</h2> @using (Html.BeginForm()) { @Html.HiddenFor(model => model.ProjectId) @Html.AntiForgeryToken() @Html.SearchableDropdownFor(model => model.ClaimId, Model.Claims.Select( claim => new ImprovedSelectListItem() { Value = claim.ClaimId.ToString(), Text = claim.CharacterName, ExtraSearch = claim.OtherNicks, Subtext = claim.NickName + " (" + claim.Fullname + " )" })) <input type="submit" class="btn btn-success" value="Зарегистрировать"/> } <hr/> @Html.ActionLink("Статистика по регистрации", "Stat", new {Model.ProjectId}) ```
26af8753-d6f2-49d7-8dd1-42a4598e75da
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Net; using System.Threading; namespace Syndll2 { public class SynelServer : IDisposable { private readonly IConnection _connection; private bool _disposed; private SynelServer(IConnection connection) { _connection = connection; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) _connection.Dispose(); _disposed = true; } public static SynelServer Listen(Action<PushNotification> action) { return Listen(3734, action); } public static SynelServer Listen(int port, Action<PushNotification> action) { var connection = NetworkConnection.Listen(port, (stream, socket) => { var history = new List<string>(); var receiver = new Receiver(stream); var signal = new SemaphoreSlim(1); receiver.MessageHandler += message => { if (!history.Contains(message.RawResponse)) { history.Add(message.RawResponse); Util.Log(string.Format("Received: {0}", message.RawResponse)); if (message.Response != null) { var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint); action(notification); } } signal.Release(); }; receiver.WatchStream(); while (stream.CanRead) signal.Wait(); }); return new SynelServer(connection); } } } ``` Improve server wait and disconnect after each msg
```c# using System; using System.Collections.Generic; using System.Net; using System.Threading; namespace Syndll2 { public class SynelServer : IDisposable { private readonly IConnection _connection; private bool _disposed; private SynelServer(IConnection connection) { _connection = connection; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) _connection.Dispose(); _disposed = true; } public static SynelServer Listen(Action<PushNotification> action) { return Listen(3734, action); } public static SynelServer Listen(int port, Action<PushNotification> action) { var connection = NetworkConnection.Listen(port, (stream, socket) => { var history = new List<string>(); var receiver = new Receiver(stream); var signal = new ManualResetEvent(false); receiver.MessageHandler = message => { if (!history.Contains(message.RawResponse)) { history.Add(message.RawResponse); Util.Log(string.Format("Received: {0}", message.RawResponse)); if (message.Response != null) { var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint); action(notification); } } signal.Set(); }; receiver.WatchStream(); // Wait until a message is received while (stream.CanRead && socket.Connected) if (signal.WaitOne(100)) break; }); return new SynelServer(connection); } } } ```
c2f333b0-fb9e-494c-9c65-4e1e34c9fcc9
{ "language": "C#" }
```c# namespace ForecastPCL.Test { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } } } ``` Add test to check that Unicode languages work (testing Chinese).
```c# namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; private const double MumbaiLatitude = 18.975; private const double MumbaiLongitude = 72.825833; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async void UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } } ```
6e20e97a-fa99-44c2-81fc-fd4c6266984f
{ "language": "C#" }
```c# using System; using System.Diagnostics; using Basics.Algorithms.Sorts; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Basics.Algorithms.Tests { [TestClass] public class SortingPerformanceTests { private const int size = 10000; private class SortInfo { public string Name { get; set; } public Action<int[]> Act { get; set; } } [TestMethod] public void SortingPerformanceTest() { var stopwatch = new Stopwatch(); var sortedArray = new int[size]; for (int i = 0; i < size; i++) { sortedArray[i] = i; } var sorts = new SortInfo[] { new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array) }, new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array) }, new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array) }, new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array) }, new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array) } }; foreach (var sort in sorts) { sortedArray.Shuffle(); stopwatch.Restart(); sort.Act(sortedArray); stopwatch.Stop(); Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks); } } } } ``` Implement Enabled flag to be able to run sorts separately
```c# using System; using System.Diagnostics; using System.Linq; using Basics.Algorithms.Sorts; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Basics.Algorithms.Tests { [TestClass] public class SortingPerformanceTests { private const int size = 1000000; private class SortInfo { public string Name { get; set; } public Action<int[]> Act { get; set; } public bool Enabled { get; set; } } [TestMethod] public void SortingPerformanceTest() { var stopwatch = new Stopwatch(); var sortedArray = new int[size]; for (int i = 0; i < size; i++) { sortedArray[i] = i; } var sorts = new SortInfo[] { new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array), Enabled = false }, new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array), Enabled = false }, new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array), Enabled = false }, new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array), Enabled = true }, new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array), Enabled = true } }; foreach (var sort in sorts.Where(s => s.Enabled)) { sortedArray.Shuffle(); stopwatch.Restart(); sort.Act(sortedArray); stopwatch.Stop(); Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks); } } } } ```
0111b861-5905-4523-87b9-09e08d4307b9
{ "language": "C#" }
```c# using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new RecentTimeEntriesAdapter (); } } } ``` Add continue time entry on recent list view click.
```c# using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class RecentTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new RecentTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as RecentTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } } ```
394fe7e6-b69c-4c6a-b1d5-418f66af8fcb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace PrepareLanding.Filters { public enum FilterHeaviness { Light = 0, Medium = 1, Heavy = 2 } public interface ITileFilter { string SubjectThingDef { get; } string RunningDescription { get; } string AttachedProperty { get; } Action<PrepareLandingUserData, List<int>> FilterAction { get; } FilterHeaviness Heaviness { get; } List<int> FilteredTiles { get; } void Filter(PrepareLandingUserData userData, List<int> inputList); } } ``` Add IsFilterActive; remove unneeded parameters to filter (pass it on ctor)
```c# using System; using System.Collections.Generic; namespace PrepareLanding.Filters { public enum FilterHeaviness { Light = 0, Medium = 1, Heavy = 2 } public interface ITileFilter { string SubjectThingDef { get; } string RunningDescription { get; } string AttachedProperty { get; } Action<List<int>> FilterAction { get; } FilterHeaviness Heaviness { get; } List<int> FilteredTiles { get; } void Filter(List<int> inputList); bool IsFilterActive { get; } } } ```
b77399fd-b81d-486a-b691-90c889e3f88b
{ "language": "C#" }
```c# using Microsoft.ServiceFabric.Actors; using Microsoft.VisualStudio.TestTools.UnitTesting; using SoCreate.ServiceFabric.PubSub.Events; using SoCreate.ServiceFabric.PubSub.State; using System.Collections.Generic; using System.Threading.Tasks; namespace SoCreate.ServiceFabric.PubSub.Tests { [TestClass] public class GivenDefaultBrokerEventsManager { [TestMethod] public async Task WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly() { int callCount = 0; var manager = new DefaultBrokerEventsManager(); manager.Subscribed += (s, e, t) => { lock (manager) { callCount++; } return Task.CompletedTask; }; const int attempts = 20; var tasks = new List<Task>(attempts); for (int i = 0; i < attempts; i++) { var actorReference = new ActorReference{ ActorId = ActorId.CreateRandom() }; tasks.Add(manager.OnSubscribedAsync("Key", new ActorReferenceWrapper(actorReference), "MessageType")); } await Task.WhenAll(tasks); Assert.AreEqual(attempts, callCount); } } } ``` Change test code to repro issue in old code and prove new code doesn't crash
```c# using Microsoft.ServiceFabric.Actors; using Microsoft.VisualStudio.TestTools.UnitTesting; using SoCreate.ServiceFabric.PubSub.Events; using SoCreate.ServiceFabric.PubSub.State; using System; using System.Threading; using System.Threading.Tasks; namespace SoCreate.ServiceFabric.PubSub.Tests { [TestClass] public class GivenDefaultBrokerEventsManager { [TestMethod] public void WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly() { bool hasCrashed = false; var manager = new DefaultBrokerEventsManager(); ManualResetEvent mr = new ManualResetEvent(false); ManualResetEvent mr2 = new ManualResetEvent(false); manager.Subscribed += (s, e, t) => { mr.WaitOne(); return Task.CompletedTask; }; const int attempts = 2000; for (int i = 0; i < attempts; i++) { ThreadPool.QueueUserWorkItem(async j => { var actorReference = new ActorReference { ActorId = ActorId.CreateRandom() }; try { await manager.OnSubscribedAsync("Key" + (int) j % 5, new ActorReferenceWrapper(actorReference), "MessageType"); } catch (NullReferenceException) { hasCrashed = true; } catch (IndexOutOfRangeException) { hasCrashed = true; } finally { if ((int)j == attempts - 1) { mr2.Set(); } } }, i); } mr.Set(); Assert.IsTrue(mr2.WaitOne(TimeSpan.FromSeconds(10)), "Failed to run within time limits."); Assert.IsFalse(hasCrashed, "Should not crash."); } } } ```
49108617-7314-4337-acfd-d84788c0f1cd
{ "language": "C#" }
```c# using System; using System.Collections; using NHibernate.Type; namespace NHibernate.Cfg { [Serializable] internal class EmptyInterceptor : IInterceptor { public EmptyInterceptor() { } public void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { } public bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types ) { return false; } public bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { return false; } public bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { return false; } public void OnPostFlush( object entity, object id, object[ ] currentState, string[ ] propertyNames, IType[ ] types ) { } public void PostFlush( ICollection entities ) { } public void PreFlush( ICollection entitites ) { } public object IsUnsaved( object entity ) { return null; } public object Instantiate( System.Type clazz, object id ) { return null; } public int[ ] FindDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types ) { return null; } } } ``` Make class public and all methods virtual so that it can be used as a base class for interceptors.
```c# using System; using System.Collections; using NHibernate.Type; namespace NHibernate.Cfg { [Serializable] public class EmptyInterceptor : IInterceptor { public virtual void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { } public virtual bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types ) { return false; } public virtual bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { return false; } public virtual bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types ) { return false; } public virtual void PostFlush( ICollection entities ) { } public virtual void PreFlush( ICollection entitites ) { } public virtual object IsUnsaved( object entity ) { return null; } public virtual object Instantiate( System.Type clazz, object id ) { return null; } public virtual int[] FindDirty( object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types ) { return null; } } } ```
a8164c97-a2de-4dd1-99f2-250a50bbb052
{ "language": "C#" }
```c# <div ng-app="GVA.Manage" ng-controller="ConfirmRegistrationController"> <div class="manage-area centered"> <h2> Thank you for registering! </h2> <p class="text-centered"> You should receive an Email confirmation shortly. </p> <p class="text-centered"> If not, ensure you check any spam filters you may have running. </p> <div class="flexbox"> <button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email"</button> </div> </div> </div>``` Fix for resend confirmation button
```c# <div ng-app="GVA.Manage" ng-controller="ConfirmRegistrationController"> <div class="manage-area centered"> <h2> Thank you for registering! </h2> <p class="text-centered"> You should receive an Email confirmation shortly. </p> <p class="text-centered"> If not, ensure you check any spam filters you may have running. </p> <div class="flexbox"> <button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email</button> </div> </div> </div>```
8c78c0d5-ea65-4728-86e6-571e831696f8
{ "language": "C#" }
```c#  namespace Glimpse.Agent.AspNet.Mvc.Messages { public class BeforeActionMessage : IActionRouteFoundMessage { public string ActionId { get; set; } public string DisplayName { get; set; } public RouteData RouteData { get; set; } public string ActionName { get; set; } public string ControllerName { get; set; } } }``` Move ordering if types around
```c#  namespace Glimpse.Agent.AspNet.Mvc.Messages { public class BeforeActionMessage : IActionRouteFoundMessage { public string ActionId { get; set; } public string DisplayName { get; set; } public string ActionName { get; set; } public string ControllerName { get; set; } public RouteData RouteData { get; set; } } }```
e0cdc7e0-08c5-496a-bc0c-caa348f4afc1
{ "language": "C#" }
```c# <h1>Counter</h1> <p>Current count: <MessageComponent Message=@currentCount.ToString() /></p> <button @onclick(IncrementCount)>Click me</button> @functions { int currentCount = 0; void IncrementCount() { currentCount++; } } ``` Cover case-insensitive child component parameter names in E2E test
```c# <h1>Counter</h1> <!-- Note: passing 'Message' parameter with lowercase name to show it's case insensitive --> <p>Current count: <MessageComponent message=@currentCount.ToString() /></p> <button @onclick(IncrementCount)>Click me</button> @functions { int currentCount = 0; void IncrementCount() { currentCount++; } } ```
065f5a96-0e56-4046-816f-19c14071d10a
{ "language": "C#" }
```c# using Moq; using SFA.DAS.EAS.TestCommon.DbCleanup; using SFA.DAS.EAS.TestCommon.DependencyResolution; using SFA.DAS.EAS.Web; using SFA.DAS.EAS.Web.Authentication; using SFA.DAS.Messaging; using StructureMap; using TechTalk.SpecFlow; namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps { [Binding] public static class GlobalTestSteps { private static Mock<IMessagePublisher> _messagePublisher; private static Mock<IOwinWrapper> _owinWrapper; private static Container _container; private static Mock<ICookieService> _cookieService; [AfterTestRun()] public static void Arrange() { _messagePublisher = new Mock<IMessagePublisher>(); _owinWrapper = new Mock<IOwinWrapper>(); _cookieService = new Mock<ICookieService>(); _container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService); var cleanDownDb = _container.GetInstance<ICleanDatabase>(); cleanDownDb.Execute().Wait(); } } } ``` Add cleandatabase call in global steps
```c# using Moq; using SFA.DAS.EAS.TestCommon.DbCleanup; using SFA.DAS.EAS.TestCommon.DependencyResolution; using SFA.DAS.EAS.Web; using SFA.DAS.EAS.Web.Authentication; using SFA.DAS.Messaging; using StructureMap; using TechTalk.SpecFlow; namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps { [Binding] public static class GlobalTestSteps { private static Mock<IMessagePublisher> _messagePublisher; private static Mock<IOwinWrapper> _owinWrapper; private static Container _container; private static Mock<ICookieService> _cookieService; [AfterTestRun()] public static void Arrange() { _messagePublisher = new Mock<IMessagePublisher>(); _owinWrapper = new Mock<IOwinWrapper>(); _cookieService = new Mock<ICookieService>(); _container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService); var cleanDownDb = _container.GetInstance<ICleanDatabase>(); cleanDownDb.Execute().Wait(); var cleanDownTransactionDb = _container.GetInstance<ICleanTransactionsDatabase>(); cleanDownTransactionDb.Execute().Wait(); } } } ```
451015a9-5534-4849-a250-8b289da3a3dc
{ "language": "C#" }
```c# namespace SEEK.AdPostingApi.Client.Models { public enum AdditionalPropertyType { ResidentsOnly = 1 } } ``` Add graduate flag as additional property
```c# namespace SEEK.AdPostingApi.Client.Models { public enum AdditionalPropertyType { ResidentsOnly = 1, Graduate } }```
b5f7dd35-56e9-4f66-bb34-bba80987bc93
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Mef")] [assembly: AssemblyDescription("Autofac MEF Integration")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mef, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)] ``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Mef")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mef, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)] ```
c8e7fe14-ab88-45b1-8f7c-1c4695c5e7cf
{ "language": "C#" }
```c# using Template10.Mvvm; using Template10.Services.SettingsService; namespace Zermelo.App.UWP.Services { public class SettingsService : BindableBase, ISettingsService { ISettingsHelper _helper; public SettingsService(ISettingsHelper settingsHelper) { _helper = settingsHelper; } private T Read<T>(string key, T otherwise = default(T)) => _helper.Read<T>(key, otherwise, SettingsStrategies.Roam); private void Write<T>(string key, T value) => _helper.Write(key, value, SettingsStrategies.Roam); //Account public string School { get => Read<string>("Host"); set { Write("Host", value); RaisePropertyChanged(); } } public string Token { get => Read<string>("Token"); set { Write("Token", value); RaisePropertyChanged(); } } } } ``` Store settings as plain strings, without SettingsHelper
```c# using Template10.Mvvm; using Template10.Services.SettingsService; using Windows.Storage; namespace Zermelo.App.UWP.Services { public class SettingsService : BindableBase, ISettingsService { ApplicationDataContainer _settings; public SettingsService() { _settings = ApplicationData.Current.RoamingSettings; } private T Read<T>(string key) => (T)_settings.Values[key]; private void Write<T>(string key, T value) => _settings.Values[key] = value; //Account public string School { get => Read<string>("Host"); set { Write("Host", value); RaisePropertyChanged(); } } public string Token { get => Read<string>("Token"); set { Write("Token", value); RaisePropertyChanged(); } } } } ```
0d45ac9c-905d-4b3b-8529-b03b2619f481
{ "language": "C#" }
```c# // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. namespace ServiceStack.IntroSpec.Services { using System.Linq; using DTO; public class ApiSpecMetadataService : IService { private readonly IApiDocumentationProvider documentationProvider; public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider) { documentationProvider.ThrowIfNull(nameof(documentationProvider)); this.documentationProvider = documentationProvider; } public object Get(SpecMetadataRequest request) { var documentation = documentationProvider.GetApiDocumentation(); return SpecMetadataResponse.Create( documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(), documentation.Resources.Select(r => r.Category).Distinct().ToArray(), documentation.Resources.SelectMany(r => r.Tags).Distinct().ToArray() ); } } } ``` Handle null/missing category and tags
```c# // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. namespace ServiceStack.IntroSpec.Services { using System.Linq; using DTO; public class ApiSpecMetadataService : IService { private readonly IApiDocumentationProvider documentationProvider; public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider) { documentationProvider.ThrowIfNull(nameof(documentationProvider)); this.documentationProvider = documentationProvider; } public object Get(SpecMetadataRequest request) { var documentation = documentationProvider.GetApiDocumentation(); return SpecMetadataResponse.Create( documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(), documentation.Resources.Select(r => r.Category).Where(c => !string.IsNullOrEmpty(c)).Distinct().ToArray(), documentation.Resources.SelectMany(r => r.Tags ?? new string[0]).Distinct().ToArray() ); } } } ```
691565a4-6577-4c40-9b98-447fa8cff03c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StrangerData.Utils { internal static class RandomValues { public static object ForColumn(TableColumnInfo columnInfo) { switch (columnInfo.ColumnType) { case ColumnType.String: // generates a random string return Any.String(columnInfo.MaxLength); case ColumnType.Int: // generates a random integer long maxValue = 10 ^ columnInfo.Precision - 1; if (maxValue > int.MaxValue) { return Any.Long(1, columnInfo.Precision - 1); } return Any.Int(1, 10 ^ columnInfo.Precision - 1); case ColumnType.Decimal: // generates a random decimal return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Double: // generates a random double return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Long: // generates a random long return Any.Long(1, 10 ^ columnInfo.Precision - 1); case ColumnType.Boolean: // generates a random boolean return Any.Boolean(); case ColumnType.Guid: // generates a random guid return Guid.NewGuid(); case ColumnType.Date: // generates a random date return Any.DateTime().Date; case ColumnType.Datetime: // generates a random DateTime return Any.DateTime(); default: return null; } } } } ``` Fix evaluation of max values for random int and long
```c# using System; namespace StrangerData.Utils { internal static class RandomValues { public static object ForColumn(TableColumnInfo columnInfo) { switch (columnInfo.ColumnType) { case ColumnType.String: // generates a random string return Any.String(columnInfo.MaxLength); case ColumnType.Int: // generates a random integer long maxValue = (int)Math.Pow(10, columnInfo.Precision - 1); if (maxValue > int.MaxValue) { return Any.Long(1, maxValue); } return Any.Int(1, (int)maxValue); case ColumnType.Decimal: // generates a random decimal return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Double: // generates a random double return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Long: // generates a random long return Any.Long(1, (int)Math.Pow(10, columnInfo.Precision - 1)); case ColumnType.Boolean: // generates a random boolean return Any.Boolean(); case ColumnType.Guid: // generates a random guid return Guid.NewGuid(); case ColumnType.Date: // generates a random date return Any.DateTime().Date; case ColumnType.Datetime: // generates a random DateTime return Any.DateTime(); default: return null; } } } } ```
421f6629-8c80-44a1-a93d-eb2a1d2c026b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using NDesk.Options; namespace LessMsi.Cli { internal class OpenGuiCommand : LessMsiCommand { public override void Run(List<string> args) { if (args.Count < 2) throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o"); ShowGui(args); } public static void ShowGui(List<string> args) { var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe"); if (File.Exists(guiExe)) { //should we wait for exit? if (args.Count > 0) Process.Start(guiExe, args[1]); else Process.Start(guiExe); } } private static string AppPath { get { var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase); var local = Path.GetDirectoryName(codeBase.LocalPath); return local; } } } } ``` Make CLI work with paths containing spaces.
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using NDesk.Options; namespace LessMsi.Cli { internal class OpenGuiCommand : LessMsiCommand { public override void Run(List<string> args) { if (args.Count < 2) throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o"); ShowGui(args); } public static void ShowGui(List<string> args) { var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe"); if (File.Exists(guiExe)) { var p = new Process(); p.StartInfo.FileName = guiExe; if (args.Count > 0) { // We add double quotes to support paths with spaces, for ex: "E:\Downloads and Sofware\potato.msi". p.StartInfo.Arguments = string.Format("\"{0}\"", args[1]); p.Start(); } else p.Start(); } } private static string AppPath { get { var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase); var local = Path.GetDirectoryName(codeBase.LocalPath); return local; } } } } ```
d3523b78-3aaf-4ba7-9d90-f2156b6434d2
{ "language": "C#" }
```c# // Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using Nuke.Common.IO; namespace Nuke.Common.Execution { [AttributeUsage(AttributeTargets.Class)] internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo { public void OnBeforeLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { var completionItems = new SortedDictionary<string, string[]>(); var targetNames = build.ExecutableTargets.Select(x => x.Name).OrderBy(x => x).ToList(); completionItems[Constants.InvokedTargetsParameterName] = targetNames.ToArray(); completionItems[Constants.SkippedTargetsParameterName] = targetNames.ToArray(); var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false); foreach (var parameter in parameters) { var parameterName = ParameterService.GetParameterMemberName(parameter); if (completionItems.ContainsKey(parameterName)) continue; var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text); completionItems[parameterName] = subItems?.ToArray(); } SerializationTasks.YamlSerializeToFile(completionItems, Constants.GetCompletionFile(NukeBuild.RootDirectory)); if (EnvironmentInfo.GetParameter<bool>(Constants.CompletionParameterName)) Environment.Exit(exitCode: 0); } } } ``` Fix shell-completion.yml to exclude unlisted targets for invocation
```c# // Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using Nuke.Common.IO; using static Nuke.Common.Constants; namespace Nuke.Common.Execution { [AttributeUsage(AttributeTargets.Class)] internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo { public void OnBeforeLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { var completionItems = new SortedDictionary<string, string[]>(); var targets = build.ExecutableTargets.OrderBy(x => x.Name).ToList(); completionItems[InvokedTargetsParameterName] = targets.Where(x => x.Listed).Select(x => x.Name).ToArray(); completionItems[SkippedTargetsParameterName] = targets.Select(x => x.Name).ToArray(); var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false); foreach (var parameter in parameters) { var parameterName = ParameterService.GetParameterMemberName(parameter); if (completionItems.ContainsKey(parameterName)) continue; var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text); completionItems[parameterName] = subItems?.ToArray(); } SerializationTasks.YamlSerializeToFile(completionItems, GetCompletionFile(NukeBuild.RootDirectory)); if (EnvironmentInfo.GetParameter<bool>(CompletionParameterName)) Environment.Exit(exitCode: 0); } } } ```
3c74c709-8844-41e0-be53-8fa7a77b1fb1
{ "language": "C#" }
```c# using NUnit.Framework; using Shouldly.DifferenceHighlighting2; using System; namespace Shouldly.Tests.InternalTests { [TestFixture] public static class StringDiffHighlighterTests { private static IStringDifferenceHighlighter _sut; [SetUp] public static void Setup() { _sut = new StringDifferenceHighlighter(null, 0); } [Test] [ExpectedException(typeof(ArgumentNullException))] public static void Should_throw_exception_when_expected_arg_is_null() { _sut.HighlightDifferences("not null", null); } [Test] [ExpectedException(typeof(ArgumentNullException))] public static void Should_throw_exception_when_actual_arg_is_null() { _sut.HighlightDifferences(null, "not null"); } } } ``` Correct order of params in diff highlighter tests
```c# using NUnit.Framework; using Shouldly.DifferenceHighlighting2; using System; namespace Shouldly.Tests.InternalTests { [TestFixture] public static class StringDiffHighlighterTests { private static IStringDifferenceHighlighter _sut; [SetUp] public static void Setup() { _sut = new StringDifferenceHighlighter(null, 0); } [Test] [ExpectedException(typeof(ArgumentNullException))] public static void Should_throw_exception_when_expected_arg_is_null() { _sut.HighlightDifferences(null, "not null"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public static void Should_throw_exception_when_actual_arg_is_null() { _sut.HighlightDifferences("not null", null); } } } ```
7611c715-367b-4478-905e-8ba2ab2ff0ca
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tracer; namespace Tester { class SingleThreadTest : ITest { private ITracer tracer = new Tracer.Tracer(); public void Run() { tracer.StartTrace(); RunCycle(204800000); tracer.StopTrace(); TraceResult result = tracer.GetTraceResult(); result.PrintToConsole(); } private void RunCycle(int repeatAmount) { ITracer tracer = new Tracer.Tracer(); tracer.StartTrace(); for (int i = 0; i < repeatAmount; i++) { int a = 1; a += i; } tracer.StopTrace(); TraceResult result = tracer.GetTraceResult(); result.PrintToConsole(); } } } ``` Update Tester class implementation due to the recent changes in Tester implementation
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tracer; using System.Threading; namespace Tester { class SingleThreadTest : ITest { private ITracer tracer = new Tracer.Tracer(); public void Run() { tracer.StartTrace(); Thread.Sleep(500); RunCycle(500); tracer.StopTrace(); PrintTestResults(); } private void RunCycle(int sleepTime) { tracer.StartTrace(); Thread.Sleep(sleepTime); tracer.StopTrace(); } private void PrintTestResults() { var traceResult = tracer.GetTraceResult(); foreach (TraceResultItem analyzedItem in traceResult) { analyzedItem.PrintToConsole(); } } } } ```
b6b5cf51-5693-4f69-a71c-81b563d06ecc
{ "language": "C#" }
```c# using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Taxjar.Tests { public class TaxjarFixture { public static string GetJSON(string fixturePath) { using (StreamReader file = File.OpenText(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "../../../", "Fixtures", fixturePath))) using (JsonTextReader reader = new JsonTextReader(file)) { JObject response = (JObject)JToken.ReadFrom(reader); var resString = response.ToString(Formatting.None).Replace(@"\", ""); return response.ToString(Formatting.None).Replace(@"\", ""); } } } } ``` Update fixture path for specs
```c# using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Taxjar.Tests { public class TaxjarFixture { public static string GetJSON(string fixturePath) { using (StreamReader file = File.OpenText(Path.Combine("../../../", "Fixtures", fixturePath))) using (JsonTextReader reader = new JsonTextReader(file)) { JObject response = (JObject)JToken.ReadFrom(reader); var resString = response.ToString(Formatting.None).Replace(@"\", ""); return response.ToString(Formatting.None).Replace(@"\", ""); } } } } ```
3491f75a-bac0-47ad-ab79-f65dbc933cc5
{ "language": "C#" }
```c# using System.Threading.Tasks; namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; private const double MumbaiLatitude = 18.975; private const double MumbaiLongitude = 72.825833; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } } ``` Clean up unused lat/long coordinates in language tests.
```c# using System.Threading.Tasks; namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } } ```
9a869ad1-fd2e-483c-807c-70389c0f3ab2
{ "language": "C#" }
```c# using Microsoft.Extensions.DependencyInjection; using ISTS.Application.Rooms; using ISTS.Application.Studios; using ISTS.Domain.Rooms; using ISTS.Domain.Studios; using ISTS.Infrastructure.Repository; namespace ISTS.Api { public static class DependencyInjectionConfiguration { public static void Configure(IServiceCollection services) { services.AddSingleton<IStudioRepository, StudioRepository>(); services.AddSingleton<IRoomRepository, RoomRepository>(); services.AddSingleton<IStudioService, StudioService>(); services.AddSingleton<IRoomService, RoomService>(); } } }``` Fix stackoverflow error caused by navigation property in Session model
```c# using Microsoft.Extensions.DependencyInjection; using ISTS.Application.Rooms; using ISTS.Application.Schedules; using ISTS.Application.Studios; using ISTS.Domain.Rooms; using ISTS.Domain.Schedules; using ISTS.Domain.Studios; using ISTS.Infrastructure.Repository; namespace ISTS.Api { public static class DependencyInjectionConfiguration { public static void Configure(IServiceCollection services) { services.AddSingleton<ISessionScheduleValidator, SessionScheduleValidator>(); services.AddSingleton<IStudioRepository, StudioRepository>(); services.AddSingleton<IRoomRepository, RoomRepository>(); services.AddSingleton<IStudioService, StudioService>(); services.AddSingleton<IRoomService, RoomService>(); } } }```
42cfb339-b777-462e-9915-a8ee582eb346
{ "language": "C#" }
```c# using UnityEditor; using UnityEngine; namespace Alensia.Core.UI { public static class ComponentFactory { [MenuItem("GameObject/UI/Alensia/Button", false, 10)] public static Button CreateButton(MenuCommand command) { var button = Button.CreateInstance(); GameObjectUtility.SetParentAndAlign(button.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(button, "Create " + button.name); Selection.activeObject = button; return button; } [MenuItem("GameObject/UI/Alensia/Label", false, 10)] public static Label CreateLabel(MenuCommand command) { var label = Label.CreateInstance(); GameObjectUtility.SetParentAndAlign(label.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(label, "Create " + label.name); Selection.activeObject = label; return label; } [MenuItem("GameObject/UI/Alensia/Panel", false, 10)] public static Panel CreatePanel(MenuCommand command) { var panel = Panel.CreateInstance(); GameObjectUtility.SetParentAndAlign(panel.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(panel, "Create " + panel.name); Selection.activeObject = panel; return panel; } } }``` Simplify component factory with generics
```c# using System; using UnityEditor; using UnityEngine; namespace Alensia.Core.UI { public static class ComponentFactory { [MenuItem("GameObject/UI/Alensia/Button", false, 10)] public static Button CreateButton(MenuCommand command) => CreateComponent(command, Button.CreateInstance); [MenuItem("GameObject/UI/Alensia/Label", false, 10)] public static Label CreateLabel(MenuCommand command) => CreateComponent(command, Label.CreateInstance); [MenuItem("GameObject/UI/Alensia/Panel", false, 10)] public static Panel CreatePanel(MenuCommand command) => CreateComponent(command, Panel.CreateInstance); private static T CreateComponent<T>( MenuCommand command, Func<T> factory) where T : UIComponent { var component = factory.Invoke(); GameObjectUtility.SetParentAndAlign( component.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(component, "Create " + component.name); Selection.activeObject = component; return component; } } }```
e9d5f52a-4166-4ddb-950d-659d8f152409
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // 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")] ``` Modify the enode project assembly.cs file
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")] ```
1529ff73-c7f3-479a-9e88-7251c59838e9
{ "language": "C#" }
```c# <section class="container"> <div id="our-jumbotron" class="jumbotron"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p> <p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p> </div> </section> ``` Remove the non-active button from the jumbotron.
```c# <section class="container"> <div id="our-jumbotron" class="jumbotron"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around.</p> </div> </section> ```
84b2dc43-c0df-4e0e-9685-08f64a9434b8
{ "language": "C#" }
```c#  // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.PowerShell.Common; namespace Google.PowerShell.Dns { /// <summary> /// Base class for Google DNS-based cmdlets. /// </summary> public abstract class GcdCmdlet : GCloudCmdlet { // The Service for the Google DNS API public DnsService Service { get; } protected GcdCmdlet() : this(null) { } protected GcdCmdlet(DnsService service) { Service = service ?? new DnsService(GetBaseClientServiceInitializer()); } } } ``` Revert "Newline at end of file missing, added."
```c#  // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.PowerShell.Common; namespace Google.PowerShell.Dns { /// <summary> /// Base class for Google DNS-based cmdlets. /// </summary> public abstract class GcdCmdlet : GCloudCmdlet { // The Service for the Google DNS API public DnsService Service { get; } protected GcdCmdlet() : this(null) { } protected GcdCmdlet(DnsService service) { Service = service ?? new DnsService(GetBaseClientServiceInitializer()); } } }```
0836c116-26a0-44fd-8445-d61e45d21bc2
{ "language": "C#" }
```c# // Copyright 2015-2017 Directive Games Limited - All Rights Reserved using UnrealBuildTool; public class RapidJson : ModuleRules { public RapidJson(TargetInfo Target) { bFasterWithoutUnity = true; PCHUsage = PCHUsageMode.NoSharedPCHs; PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { // ... add other public dependencies that you statically link with here ... "Core", "HTTP", } ); PrivateDependencyModuleNames.AddRange( new string[] { // ... add private dependencies that you statically link with here ... } ); } } ``` Fix build error in VS2015
```c# // Copyright 2015-2017 Directive Games Limited - All Rights Reserved using UnrealBuildTool; public class RapidJson : ModuleRules { public RapidJson(TargetInfo Target) { bFasterWithoutUnity = true; PCHUsage = PCHUsageMode.NoSharedPCHs; PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { // ... add other public dependencies that you statically link with here ... "Core", "HTTP", } ); PrivateDependencyModuleNames.AddRange( new string[] { // ... add private dependencies that you statically link with here ... } ); if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.PS4)) { Definitions.Add("RAPIDJSON_HAS_CXX11_RVALUE_REFS=1"); } } } ```
868318e0-3d67-4956-a9b3-ba46c56e1a9f
{ "language": "C#" }
```c# using KeePassLib; using System; using System.Linq; namespace HaveIBeenPwned { public static class PwEntryExtension { public static DateTime GetPasswordLastModified(this PwEntry entry) { if(entry.History != null && entry.History.Any()) { var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime); foreach(var historyEntry in sortedEntries) { if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString()) { return historyEntry.LastModificationTime; } } return sortedEntries.Last().LastModificationTime; } return entry.LastModificationTime; } } } ``` Add extension method for working out if an entry is deleted or not.
```c# using KeePass.Plugins; using KeePassLib; using System; using System.Linq; namespace HaveIBeenPwned { public static class PwEntryExtension { public static DateTime GetPasswordLastModified(this PwEntry entry) { if(entry.History != null && entry.History.Any()) { var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime); foreach(var historyEntry in sortedEntries) { if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString()) { return historyEntry.LastModificationTime; } } return sortedEntries.Last().LastModificationTime; } return entry.LastModificationTime; } public static bool IsDeleted(this PwEntry entry, IPluginHost pluginHost) { return entry.ParentGroup.Uuid.CompareTo(pluginHost.Database.RecycleBinUuid) == 0; } } } ```