doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
6d753d06-030c-4a82-8254-2d60ebd7c13e
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, HitObjects = original.HitObjects.SelectMany(converter.Convert).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } } ``` Fix out of range exceptions due to out-of-order hitobjects.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, // We need to sort here, because the converter generates patterns HitObjects = original.HitObjects.SelectMany(converter.Convert).OrderBy(h => h.StartTime).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } } ```
9f934ca6-acc0-4046-b052-840a91bd2b1f
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace HouseCannith_Frontend { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseUrls("https://localhost:5001") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } } ``` Add comment explaining UseUrls usage
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace HouseCannith_Frontend { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() // This URL is only applicable to Development - when run behind a reverse-proxy IIS // instance (like Azure App Service does in production), this is overriden .UseUrls("https://localhost:5001") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } } ```
766d25ed-8087-44e4-840f-24283e17b7a8
{ "language": "C#" }
```c# using System; namespace XeroApi.Model { public class Payment : EndpointModelBase { [ItemId] public Guid? PaymentID { get; set; } public DateTime Date { get; set; } public decimal Amount { get; set; } public string Reference { get; set; } public decimal? CurrencyRate { get; set; } public string PaymentType { get; set; } public string Status { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public Account Account { get; set; } public Invoice Invoice { get; set; } } public class Payments : ModelList<Payment> { } }``` Allow payments to be marked as reconciled
```c# using System; namespace XeroApi.Model { public class Payment : EndpointModelBase { [ItemId] public Guid? PaymentID { get; set; } public DateTime Date { get; set; } public decimal Amount { get; set; } public string Reference { get; set; } public decimal? CurrencyRate { get; set; } public string PaymentType { get; set; } public string Status { get; set; } public bool IsReconciled { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public Account Account { get; set; } public Invoice Invoice { get; set; } } public class Payments : ModelList<Payment> { } } ```
587c2898-c8b7-4e89-a3ba-39cace31c2c0
{ "language": "C#" }
```c# using System; using System.IO; namespace LibSassGen { public partial class CodeGenerator { private const string DefaultIncludeDir = @"../../../../../libsass/include"; private const string DefaultOutputFilePath = @"../../../../SharpScss/LibSass.Generated.cs"; private const int IndentMultiplier = 4; private int _indentLevel; private TextWriter _writer; private TextWriter _writerBody; private TextWriter _writerGlobal; public bool OutputToConsole { get; set; } public void Run() { var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath); outputFilePath = Path.GetFullPath(outputFilePath); _writerGlobal = new StringWriter(); _writerBody = new StringWriter(); ParseAndWrite(); var finalWriter = OutputToConsole ? Console.Out : new StreamWriter(outputFilePath); finalWriter.Write(_writerGlobal); if (!OutputToConsole) { finalWriter.Flush(); finalWriter.Dispose(); finalWriter = null; } } } } ``` Update code generator relative filepath
```c# using System; using System.IO; namespace LibSassGen { public partial class CodeGenerator { private const string DefaultIncludeDir = @"../../../../libsass/include"; private const string DefaultOutputFilePath = @"../../../SharpScss/LibSass.Generated.cs"; private const int IndentMultiplier = 4; private int _indentLevel; private TextWriter _writer; private TextWriter _writerBody; private TextWriter _writerGlobal; public bool OutputToConsole { get; set; } public void Run() { var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath); outputFilePath = Path.GetFullPath(outputFilePath); _writerGlobal = new StringWriter(); _writerBody = new StringWriter(); ParseAndWrite(); var finalWriter = OutputToConsole ? Console.Out : new StreamWriter(outputFilePath); finalWriter.Write(_writerGlobal); if (!OutputToConsole) { finalWriter.Flush(); finalWriter.Dispose(); finalWriter = null; } } } } ```
dcf6180f-8396-426b-8c66-7689829b5acc
{ "language": "C#" }
```c# using System; using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } Console.WriteLine(onion + " " + ++count); } } } } ``` Make main program class static
```c# using System; using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { static class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } Console.WriteLine(onion + " " + ++count); } } } } ```
dc0bc607-3463-4113-8589-c978961412c5
{ "language": "C#" }
```c# using System; using System.Resources; using System.Windows.Data; namespace GoldenAnvil.Utility.Windows { public sealed class EnumToDisplayStringConverter : IValueConverter { public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!(parameter is ResourceManager resources)) throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager."); var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString"); var generic = method.MakeGenericMethod(value.GetType()); return generic.Invoke(null, new [] { resources, value }); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } ``` Fix crash when clearing resetting template
```c# using System; using System.Resources; using System.Windows.Data; namespace GoldenAnvil.Utility.Windows { public sealed class EnumToDisplayStringConverter : IValueConverter { public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (!(parameter is ResourceManager resources)) throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager."); // sometimes an empty string can be passed instead of a null value if (value is string stringValue) { if (stringValue == "") return null; } var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString"); var generic = method.MakeGenericMethod(value.GetType()); return generic.Invoke(null, new [] { resources, value }); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } ```
4f653d10-62df-4472-a4dc-702d749024cc
{ "language": "C#" }
```c# using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public interface IDbFactory { /// <summary> /// Creates an instance of your ISession expanded interface /// </summary> /// <typeparam name="T"></typeparam> /// <returns>ISession</returns> T Create<T>() where T : class, ISession; [Obsolete] T CreateSession<T>() where T : class, ISession; TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession; T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork; void Release(IDisposable instance); } } ``` Remove obsolete methods and add sumary texts.
```c# using System; using System.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public interface IDbFactory { /// <summary> /// Creates an instance of your ISession expanded interface /// </summary> /// <typeparam name="T"></typeparam> /// <returns>ISession</returns> T Create<T>() where T : class, ISession; /// <summary> /// Creates a UnitOfWork and Session at same time. The session has the same scope as the unit of work. /// </summary> /// <param name="isolationLevel"></param> /// <typeparam name="TUnitOfWork"></typeparam> /// <typeparam name="TSession"></typeparam> /// <returns></returns> TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession; /// <summary> /// Used for Session base to create UnitOfWork. Not recommeded to use in other code /// </summary> /// <param name="factory"></param> /// <param name="session"></param> /// <param name="isolationLevel"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork; /// <summary> /// Release the component. Done by Sessnion and UnitOfWork on there own. /// </summary> /// <param name="instance"></param> void Release(IDisposable instance); } } ```
4d70d069-90ad-4960-9576-2b8d629a5148
{ "language": "C#" }
```c# using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Remove("disable-gpu"); } if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Remove("disable-gpu-compositing"); } settings.CefCommandLineArgs.Add("disable-gpu", "1"); settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } } ``` Change default user agent for web views
```c# using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Remove("disable-gpu"); } if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Remove("disable-gpu-compositing"); } settings.CefCommandLineArgs.Add("disable-gpu", "1"); settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); settings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0"; IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } } ```
54dc41bb-eb64-4354-9306-a0c81488a3f3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace TirkxDownloader.Framework { public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } public TFirst First { get { return first; } } public TSecond Second { get { return second; } } public override bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(first, other.first) && EqualityComparer<TSecond>.Default.Equals(second, other.second); } public override int GetHashCode() { return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 + EqualityComparer<TSecond>.Default.GetHashCode(second); } } } ``` Delete override keyword from Equals method to indicate that this method implement interface
```c# using System; using System.Collections.Generic; namespace TirkxDownloader.Framework { public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } public TFirst First { get { return first; } } public TSecond Second { get { return second; } } public bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(first, other.first) && EqualityComparer<TSecond>.Default.Equals(second, other.second); } public override int GetHashCode() { return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 + EqualityComparer<TSecond>.Default.GetHashCode(second); } } } ```
651b06cd-c492-40cd-9a45-bb157466855f
{ "language": "C#" }
```c# using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using NUnit.Framework; namespace SharpBrake.Tests { public class AirbrakeValidator { public static void ValidateSchema(string xml) { var schema = GetXmlSchema(); XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, }; var errorBuffer = new StringBuilder(); settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message); settings.Schemas.Add(schema); using (var reader = new StringReader(xml)) { using (var xmlReader = new XmlTextReader(reader)) { using (var validator = XmlReader.Create(xmlReader, settings)) { while (validator.Read()) { } } } } if (errorBuffer.Length > 0) Assert.Fail(errorBuffer.ToString()); } private static XmlSchema GetXmlSchema() { const string xsd = "hoptoad_2_1.xsd"; Type clientType = typeof(AirbrakeClient); XmlSchema schema; using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd)) { if (schemaStream == null) Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd); schema = XmlSchema.Read(schemaStream, (sender, args) => { }); } return schema; } } }``` Return instead of using a variable.
```c# using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using NUnit.Framework; namespace SharpBrake.Tests { public class AirbrakeValidator { public static void ValidateSchema(string xml) { var schema = GetXmlSchema(); XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, }; var errorBuffer = new StringBuilder(); settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message); settings.Schemas.Add(schema); using (var reader = new StringReader(xml)) { using (var xmlReader = new XmlTextReader(reader)) { using (var validator = XmlReader.Create(xmlReader, settings)) { while (validator.Read()) { } } } } if (errorBuffer.Length > 0) Assert.Fail(errorBuffer.ToString()); } private static XmlSchema GetXmlSchema() { Type clientType = typeof(AirbrakeClient); const string xsd = "hoptoad_2_1.xsd"; using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd)) { if (schemaStream == null) Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd); return XmlSchema.Read(schemaStream, (sender, args) => { }); } } } }```
dcef4011-a982-485a-b58a-4d7fd1e5e222
{ "language": "C#" }
```c# using Alexa.NET.Management.Vendors; using Refit; namespace Alexa.NET.Management { [Headers("Authorization: Bearer")] public interface IVendorApi { [Get("/vendors")] Vendor[] Get(); } } ``` Update vendor api to ensure task returned
```c# using System.Threading.Tasks; using Alexa.NET.Management.Vendors; using Refit; namespace Alexa.NET.Management { [Headers("Authorization: Bearer")] public interface IVendorApi { [Get("/vendors")] Task<Vendor[]> Get(); } } ```
ecd06029-fc00-4ef5-894b-402349203141
{ "language": "C#" }
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EOLib.DependencyInjection; using Microsoft.Practices.Unity; using Microsoft.Xna.Framework; namespace EndlessClient { public class XNAControlsDependencyContainer : IInitializableContainer { public void RegisterDependencies(IUnityContainer container) { } public void InitializeDependencies(IUnityContainer container) { var game = (Game)container.Resolve<IEndlessGame>(); XNAControls.GameRepository.SetGame(game); //todo: remove this once converted to new XNAControls code XNAControls.Old.XNAControls.Initialize(game); XNAControls.Old.XNAControls.IgnoreEnterForDialogs = true; XNAControls.Old.XNAControls.IgnoreEscForDialogs = true; } } } ``` Remove old XNAControls code from initialization. Crash & burn if old XNAControls are used.
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EndlessClient.GameExecution; using EOLib.DependencyInjection; using Microsoft.Practices.Unity; using Microsoft.Xna.Framework; namespace EndlessClient { public class XNAControlsDependencyContainer : IInitializableContainer { public void RegisterDependencies(IUnityContainer container) { } public void InitializeDependencies(IUnityContainer container) { var game = (Game)container.Resolve<IEndlessGame>(); XNAControls.GameRepository.SetGame(game); } } } ```
ce962815-ffa8-4ac1-bacd-69a33de519c7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Prism.API; namespace Prism.Mods.Hooks { class ModDefHooks : IHookManager { IEnumerable<Action> onAllModsLoaded, onUnload , preUpdate , postUpdate ; public void Create() { onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded"); onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" ); preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" ); postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" ); } public void Clear () { onAllModsLoaded = null; onUnload = null; postUpdate = null; } public void OnAllModsLoaded() { HookManager.Call(onAllModsLoaded); } public void OnUnload () { HookManager.Call(onUnload); } public void PreUpdate () { HookManager.Call(preUpdate); } public void PostUpdate () { HookManager.Call(postUpdate); } } } ``` Set preUpdate to null with the rest of the hooks.
```c# using System; using System.Collections.Generic; using System.Linq; using Prism.API; namespace Prism.Mods.Hooks { class ModDefHooks : IHookManager { IEnumerable<Action> onAllModsLoaded, onUnload , preUpdate , postUpdate ; public void Create() { onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded"); onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" ); preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" ); postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" ); } public void Clear () { onAllModsLoaded = null; onUnload = null; preUpdate = null; postUpdate = null; } public void OnAllModsLoaded() { HookManager.Call(onAllModsLoaded); } public void OnUnload () { HookManager.Call(onUnload); } public void PreUpdate () { HookManager.Call(preUpdate); } public void PostUpdate () { HookManager.Call(postUpdate); } } } ```
24c8e058-9e60-49cc-ae15-ed97f495e7fe
{ "language": "C#" }
```c# using System; namespace Umbraco.Web.PublishedCache { public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor { private readonly IUmbracoContextAccessor _umbracoContextAccessor; public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor) { _umbracoContextAccessor = umbracoContextAccessor; } public IPublishedSnapshot PublishedSnapshot { get { var umbracoContext = _umbracoContextAccessor.UmbracoContext; if (umbracoContext == null) throw new Exception("The IUmbracoContextAccessor could not provide an UmbracoContext."); return umbracoContext.PublishedSnapshot; } set { throw new NotSupportedException(); // not ok to set } } } } ``` Fix PublishedSnapshotAccessor to not throw but return null
```c# using System; namespace Umbraco.Web.PublishedCache { public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor { private readonly IUmbracoContextAccessor _umbracoContextAccessor; public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor) { _umbracoContextAccessor = umbracoContextAccessor; } public IPublishedSnapshot PublishedSnapshot { get { var umbracoContext = _umbracoContextAccessor.UmbracoContext; return umbracoContext?.PublishedSnapshot; } set => throw new NotSupportedException(); // not ok to set } } } ```
c989e0e1-ce38-46c0-95b5-287cb4f967de
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; namespace MICore { internal class NativeMethods { // TODO: It would be better to route these to the correct .so files directly rather than pasing through system.native. [DllImport("System.Native", SetLastError = true)] internal static extern int Kill(int pid, int mode); [DllImport("System.Native", SetLastError = true)] internal static extern int MkFifo(string name, int mode); [DllImport("System.Native", SetLastError = true)] internal static extern uint GetEUid(); } } ``` Change interop calls to directly pinvoke.
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; namespace MICore { internal class NativeMethods { private const string Libc = "libc"; [DllImport(Libc, EntryPoint = "kill", SetLastError = true)] internal static extern int Kill(int pid, int mode); [DllImport(Libc, EntryPoint = "mkfifo", SetLastError = true)] internal static extern int MkFifo(string name, int mode); [DllImport(Libc, EntryPoint = "geteuid", SetLastError = true)] internal static extern uint GetEUid(); } } ```
e8720922-e6fd-4fbd-98a2-b14facb23190
{ "language": "C#" }
```c# using System; using System.Text; namespace Python.Runtime { using static Runtime; [Obsolete("Only to be used from within Python")] static class Loader { public unsafe static int Initialize(IntPtr data, int size) { try { var dllPath = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (!string.IsNullOrEmpty(dllPath)) { PythonDLL = dllPath; } else { PythonDLL = null; } var gs = PyGILState_Ensure(); try { // Console.WriteLine("Startup thread"); PythonEngine.InitExt(); // Console.WriteLine("Startup finished"); } finally { PyGILState_Release(gs); } } catch (Exception exc) { Console.Error.Write( $"Failed to initialize pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } public unsafe static int Shutdown(IntPtr data, int size) { try { var command = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (command == "full_shutdown") { var gs = PyGILState_Ensure(); try { PythonEngine.Shutdown(); } finally { PyGILState_Release(gs); } } } catch (Exception exc) { Console.Error.Write( $"Failed to shutdown pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } } } ``` Use Py.GIL directly, now that it doesn't try to init anymore
```c# using System; using System.Text; namespace Python.Runtime { using static Runtime; [Obsolete("Only to be used from within Python")] static class Loader { public unsafe static int Initialize(IntPtr data, int size) { try { var dllPath = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (!string.IsNullOrEmpty(dllPath)) { PythonDLL = dllPath; } else { PythonDLL = null; } using var _ = Py.GIL(); PythonEngine.InitExt(); } catch (Exception exc) { Console.Error.Write( $"Failed to initialize pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } public unsafe static int Shutdown(IntPtr data, int size) { try { var command = Encoding.UTF8.GetString((byte*)data.ToPointer(), size); if (command == "full_shutdown") { using var _ = Py.GIL(); PythonEngine.Shutdown(); } } catch (Exception exc) { Console.Error.Write( $"Failed to shutdown pythonnet: {exc}\n{exc.StackTrace}" ); return 1; } return 0; } } } ```
7b43a904-37f9-4334-8569-c1e76a9770ab
{ "language": "C#" }
```c# using System; using GitHubSharp.Models; using System.Collections.Generic; namespace GitHubSharp.Controllers { public class CommitsController : Controller { public RepositoryController RepositoryController { get; private set; } public CommitController this[string key] { get { return new CommitController(Client, RepositoryController, key); } } public CommitsController(Client client, RepositoryController repo) : base(client) { RepositoryController = repo; } public GitHubRequest<List<CommitModel>> GetAll(string sha = null) { if (sha == null) return GitHubRequest.Get<List<CommitModel>>(Uri); else return GitHubRequest.Get<List<CommitModel>>(Uri, new { sha = sha }); } public override string Uri { get { return RepositoryController.Uri + "/commits"; } } } public class CommitController : Controller { public RepositoryController RepositoryController { get; private set; } public string Sha { get; private set; } public CommitCommentsController Comments { get { return new CommitCommentsController(Client, this); } } public CommitController(Client client, RepositoryController repositoryController, string sha) : base(client) { RepositoryController = repositoryController; Sha = sha; } public GitHubRequest<CommitModel> Get() { return GitHubRequest.Get<CommitModel>(Uri); } public override string Uri { get { return RepositoryController.Uri + "/commits/" + Sha; } } } } ``` Support commit listing for single file within repository
```c# using System; using GitHubSharp.Models; using System.Collections.Generic; namespace GitHubSharp.Controllers { public class CommitsController : Controller { public string FilePath { get; set; } public RepositoryController RepositoryController { get; private set; } public CommitController this[string key] { get { return new CommitController(Client, RepositoryController, key); } } public CommitsController(Client client, RepositoryController repo) : base(client) { RepositoryController = repo; } public GitHubRequest<List<CommitModel>> GetAll(string sha = null) { if (sha == null) return GitHubRequest.Get<List<CommitModel>>(Uri); else return GitHubRequest.Get<List<CommitModel>>(Uri, new { sha = sha }); } public override string Uri { get { return RepositoryController.Uri + "/commits" + (string.IsNullOrEmpty(this.FilePath) ? string.Empty : "?path=" + this.FilePath); } } } public class CommitController : Controller { public RepositoryController RepositoryController { get; private set; } public string Sha { get; private set; } public CommitCommentsController Comments { get { return new CommitCommentsController(Client, this); } } public CommitController(Client client, RepositoryController repositoryController, string sha) : base(client) { RepositoryController = repositoryController; Sha = sha; } public GitHubRequest<CommitModel> Get() { return GitHubRequest.Get<CommitModel>(Uri); } public override string Uri { get { return RepositoryController.Uri + "/commits/" + Sha; } } } } ```
917c8ff0-c01b-4668-aa4d-73bebc79fc6f
{ "language": "C#" }
```c# namespace ATP.AnimationPathTools { public class TargetAnimationPath : AnimationPath { } } ``` Set default target path gizmo curve color
```c# using UnityEngine; namespace ATP.AnimationPathTools { public class TargetAnimationPath : AnimationPath { /// <summary> /// Color of the gizmo curve. /// </summary> private Color gizmoCurveColor = Color.magenta; } } ```
c1dfd013-e36b-4d6d-96bd-7dca248e5883
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TourOfCSharp6 { public class Point { public double X { get; set; } public double Y { get; set; } public double Distance { get { return Math.Sqrt(X * X + Y * Y); } } } } ``` Convert Distance to Expression Bodied Member
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TourOfCSharp6 { public class Point { public double X { get; set; } public double Y { get; set; } public double Distance => Math.Sqrt(X * X + Y * Y); } } ```
6677c7e3-2279-4b65-b6ca-8907ae9f05d9
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.76.0" ) ]``` Revert "bump version again to 1.3.76.0"
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.75.0" ) ]```
7d201328-cfca-4bc5-8849-7aa49989521d
{ "language": "C#" }
```c# namespace CertiPay.Common.Testing { using ApprovalTests; using Newtonsoft.Json; using Ploeh.AutoFixture; public static class TestExtensions { private static readonly Fixture _fixture = new Fixture { }; /// <summary> /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object /// </summary> public static void VerifyMe(this object obj) { var json = JsonConvert.SerializeObject(obj); Approvals.VerifyJson(json); } /// <summary> /// Returns an auto-initialized instance of the type T, filled via mock /// data via AutoFixture. /// /// This will not work for interfaces, only concrete types. /// </summary> public static T AutoGenerate<T>() { return _fixture.Create<T>(); } } }``` Use StringEnumConvert for Approvals.VerifyJson / VerifyMe
```c# namespace CertiPay.Common.Testing { using ApprovalTests; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Ploeh.AutoFixture; public static class TestExtensions { private static readonly Fixture _fixture = new Fixture { }; private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; static TestExtensions() { _settings.Converters.Add(new StringEnumConverter { }); } /// <summary> /// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object /// </summary> public static void VerifyMe(this object obj) { var json = JsonConvert.SerializeObject(obj, _settings); Approvals.VerifyJson(json); } /// <summary> /// Returns an auto-initialized instance of the type T, filled via mock /// data via AutoFixture. /// /// This will not work for interfaces, only concrete types. /// </summary> public static T AutoGenerate<T>() { return _fixture.Create<T>(); } } }```
4b1b0c04-d96c-46e3-af8a-674c71f5b4f8
{ "language": "C#" }
```c# using System; namespace GrovePi.Sensors { public abstract class Sensor<TSensorType> where TSensorType : class { protected readonly IGrovePi Device; protected readonly Pin Pin; internal Sensor(IGrovePi device, Pin pin, PinMode pinMode) { if (device == null) throw new ArgumentNullException(nameof(device)); device.PinMode(Pin, pinMode); Device = device; Pin = pin; } internal Sensor(IGrovePi device, Pin pin) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; } public SensorStatus CurrentState => (SensorStatus) Device.DigitalRead(Pin); public TSensorType ChangeState(SensorStatus newState) { Device.DigitalWrite(Pin, (byte) newState); return this as TSensorType; } public void AnalogWrite(byte value) { Device.AnalogWrite(Pin,value); } } }``` Fix bug in pinmode usage The device.PinMode was being set from internal members which had not been stored yet. Would result in Relay module not working as expected.
```c# using System; namespace GrovePi.Sensors { public abstract class Sensor<TSensorType> where TSensorType : class { protected readonly IGrovePi Device; protected readonly Pin Pin; internal Sensor(IGrovePi device, Pin pin, PinMode pinMode) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; device.PinMode(Pin, pinMode); } internal Sensor(IGrovePi device, Pin pin) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; Pin = pin; } public SensorStatus CurrentState => (SensorStatus) Device.DigitalRead(Pin); public TSensorType ChangeState(SensorStatus newState) { Device.DigitalWrite(Pin, (byte) newState); return this as TSensorType; } public void AnalogWrite(byte value) { Device.AnalogWrite(Pin,value); } } }```
5e2d1bd3-4d0d-4afb-9cbc-46d9c5d3c4bb
{ "language": "C#" }
```c# using System.Collections; class IENumDemo { /// <summary> /// Create a cosinus table enumerator with 0..360 deg values /// </summary> private IEnumerator costable = new Func<List<float>>(() => { List<float> nn = new List<float>(); for (int v = 0; v < 360; v++) { nn.Add((float)Math.Cos(v * Math.PI / 180)); } return nn; } )().GetEnumerator(); /// <summary> /// Demonstrates eternal fetch of next value from an IEnumerator /// At end of list the enumerator is reset to start of list /// </summary> /// <returns></returns> private float GetaNum() { //Advance to next item if (!costable.MoveNext()) { //End of list - reset and advance to first costable.Reset(); costable.MoveNext(); } //Return Enum current value yield return costable.Current; } } ``` Revert "Now with "yield" in GetaNum()"
```c# using System.Collections; class IENumDemo { /// <summary> /// Create a cosinus table enumerator with 0..360 deg values /// </summary> private IEnumerator costable = new Func<List<float>>(() => { List<float> nn = new List<float>(); for (int v = 0; v < 360; v++) { nn.Add((float)Math.Cos(v * Math.PI / 180)); } return nn; } )().GetEnumerator(); /// <summary> /// Demonstrates eternal fetch of next value from an IEnumerator /// At end of list the enumerator is reset to start of list /// </summary> /// <returns></returns> private float GetaNum() { //Advance to next item if (!costable.MoveNext()) { //End of list - reset and advance to first costable.Reset(); costable.MoveNext(); } //Return Enum current value return costable.Current; } } ```
0d8f34c2-3f7d-4a5b-9afc-bcd94f562dc8
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Utils; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModMirror : ModMirror, IApplicableToHitObject { public override string Description => "Reflect the playfield."; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; [SettingSource("Mirrored axes", "Choose which of the playfield's axes are mirrored.")] public Bindable<MirrorType> Reflection { get; } = new Bindable<MirrorType>(); public void ApplyToHitObject(HitObject hitObject) { var osuObject = (OsuHitObject)hitObject; switch (Reflection.Value) { case MirrorType.Horizontal: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); break; case MirrorType.Vertical: OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; case MirrorType.Both: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; } } public enum MirrorType { Horizontal, Vertical, Both } } } ``` Update description to match mania mirror implementation
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Game.Configuration; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Utils; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModMirror : ModMirror, IApplicableToHitObject { public override string Description => "Flip objects on the chosen axes."; public override Type[] IncompatibleMods => new[] { typeof(ModHardRock) }; [SettingSource("Mirrored axes", "Choose which axes objects are mirrored over.")] public Bindable<MirrorType> Reflection { get; } = new Bindable<MirrorType>(); public void ApplyToHitObject(HitObject hitObject) { var osuObject = (OsuHitObject)hitObject; switch (Reflection.Value) { case MirrorType.Horizontal: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); break; case MirrorType.Vertical: OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; case MirrorType.Both: OsuHitObjectGenerationUtils.ReflectHorizontally(osuObject); OsuHitObjectGenerationUtils.ReflectVertically(osuObject); break; } } public enum MirrorType { Horizontal, Vertical, Both } } } ```
e874bbef-6820-49a6-a5ef-977fe57b18d6
{ "language": "C#" }
```c# using System; using Rant.Localization; namespace Rant.Vocabulary { /// <summary> /// Thrown when Rant encounters an error while loading a dictionary table. /// </summary> public sealed class RantTableLoadException : Exception { internal RantTableLoadException(string origin, int line, int col, string messageType, params object[] messageArgs) : base(Txtres.GetString("src-line-col", Txtres.GetString(messageType, messageArgs), line, col)) { Line = line; Column = col; Origin = origin; } /// <summary> /// Gets the line number on which the error occurred. /// </summary> public int Line { get; } /// <summary> /// Gets the column on which the error occurred. /// </summary> public int Column { get; } /// <summary> /// Gets a string describing where the table was loaded from. For tables loaded from disk, this will be the file path. /// </summary> public string Origin { get; } } }``` Fix formatting of table load errors
```c# using System; using Rant.Localization; namespace Rant.Vocabulary { /// <summary> /// Thrown when Rant encounters an error while loading a dictionary table. /// </summary> public sealed class RantTableLoadException : Exception { internal RantTableLoadException(string origin, int line, int col, string messageType, params object[] messageArgs) : base($"{Txtres.GetString("src-line-col", origin, line, col)} {Txtres.GetString(messageType, messageArgs)}") { Line = line; Column = col; Origin = origin; } /// <summary> /// Gets the line number on which the error occurred. /// </summary> public int Line { get; } /// <summary> /// Gets the column on which the error occurred. /// </summary> public int Column { get; } /// <summary> /// Gets a string describing where the table was loaded from. For tables loaded from disk, this will be the file path. /// </summary> public string Origin { get; } } }```
25ee4f9b-0c84-4ac6-b71a-2ebfe0b64164
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace BetterLoadSaveGame { class SaveWatcher : IDisposable { private FileSystemWatcher _watcher; public event FileSystemEventHandler OnSave; public SaveWatcher() { _watcher = new FileSystemWatcher(Util.SaveDir); _watcher.Created += FileCreated; _watcher.EnableRaisingEvents = true; } private void FileCreated(object sender, FileSystemEventArgs e) { if (OnSave != null) { OnSave(sender, e); } } public void Dispose() { _watcher.Dispose(); } } } ``` Fix updating screenshots for quicksave
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace BetterLoadSaveGame { class SaveWatcher : IDisposable { private FileSystemWatcher _watcher; public event FileSystemEventHandler OnSave; public SaveWatcher() { _watcher = new FileSystemWatcher(Util.SaveDir); _watcher.Created += FileCreated; _watcher.Changed += FileCreated; _watcher.EnableRaisingEvents = true; } private void FileCreated(object sender, FileSystemEventArgs e) { if (OnSave != null) { OnSave(sender, e); } } public void Dispose() { _watcher.Dispose(); } } } ```
8fbf7405-2a54-4d0b-813b-4970ad262bee
{ "language": "C#" }
```c# using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "http://go.microsoft.com/fwlink/?LinkID=207106"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } } ``` Update default publishing url to point to v2 feed.
```c# using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "https://www.nuget.org"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } } ```
92780c44-40c0-4d2e-855a-fa91e66af6b7
{ "language": "C#" }
```c# using System; namespace JustSaying.Models { public abstract class Message { protected Message() { TimeStamp = DateTime.UtcNow; Id = Guid.NewGuid(); } public Guid Id { get; set; } public DateTime TimeStamp { get; private set; } public string RaisingComponent { get; set; } public string Version{ get; private set; } public string SourceIp { get; private set; } public string Tenant { get; set; } public string Conversation { get; set; } //footprint in order to avoid the same message being processed multiple times. public virtual string UniqueKey() { return Id.ToString(); } } }``` Allow message TimeStamp to be set when deserializing
```c# using System; namespace JustSaying.Models { public abstract class Message { protected Message() { TimeStamp = DateTime.UtcNow; Id = Guid.NewGuid(); } public Guid Id { get; set; } public DateTime TimeStamp { get; set; } public string RaisingComponent { get; set; } public string Version{ get; private set; } public string SourceIp { get; private set; } public string Tenant { get; set; } public string Conversation { get; set; } //footprint in order to avoid the same message being processed multiple times. public virtual string UniqueKey() { return Id.ToString(); } } } ```
4cca71a7-3cc9-437c-bb3c-3e9142d831f3
{ "language": "C#" }
```c# using System.Reflection; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }``` Revert "registration of api controllers fixed"
```c# using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { static Bootstrapper() { Init(); } public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .Where(c=>c.Name.EndsWith("Controller")) .AsSelf(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }```
2fef0830-1ac3-499c-9b5a-f0053e42edf8
{ "language": "C#" }
```c# using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } public override void Close() { base.Close(); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } } ``` Fix possible cause of null bytes in config file
```c# using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } protected override void Dispose(bool disposing) { base.Dispose(disposing); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } } ```
dd6e3463-f458-4782-a271-d5fc09046167
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(args.Name); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } } ``` Apply policy when loading reflection only assemblys
```c# using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } } ```
531316ce-9db4-46ad-9f3f-2f8de787475c
{ "language": "C#" }
```c#  using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "<-", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } } ``` Use single arrow character for backspace.
```c#  using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "←", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } } ```
2c4b052e-296e-42f3-b065-28e9e9e88b27
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Tests GC.TotalMemory using System; public class Test { public static int Main() { GC.Collect(); GC.Collect(); int[] array1 = new int[20000]; int memold = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memold); array1=null; GC.Collect(); int[] array2 = new int[40000]; int memnew = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memnew); if(memnew >= memold) { Console.WriteLine("Test for GC.TotalMemory passed!"); return 100; } else { Console.WriteLine("Test for GC.TotalMemory failed!"); return 1; } } } ``` Fix the GC total memory test.
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Tests GC.TotalMemory using System; public class Test { public static int Main() { GC.Collect(); GC.Collect(); int[] array1 = new int[20000]; int memold = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memold); array1=null; GC.Collect(); int[] array2 = new int[40000]; int memnew = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memnew); GC.KeepAlive(array2); if(memnew >= memold) { Console.WriteLine("Test for GC.TotalMemory passed!"); return 100; } else { Console.WriteLine("Test for GC.TotalMemory failed!"); return 1; } } } ```
bc3d6f15-81fb-4109-aa87-414a5d5bef19
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ``` Update server side API for single multiple answer question
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ```
d75da500-730e-43ec-a65d-2e740fd0e56f
{ "language": "C#" }
```c# using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string generator, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } }``` Update param name to match IWebHookHandler
```c# using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } } ```
bb32d5fb-dc05-41e9-8f0b-6726e368efc4
{ "language": "C#" }
```c# using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] ``` Revert "remove a suppression no longer needed"
```c# using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] [assembly: SuppressMessage("Style", "IDE0071WithoutSuggestion")] ```
9a52deb8-a584-46eb-affe-58245238aa35
{ "language": "C#" }
```c# using System; namespace NPSharp.NP { internal class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }``` Make NP file exception class public
```c# using System; namespace NPSharp.NP { public class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }```
68f433de-4674-46c5-b213-2af79ab56723
{ "language": "C#" }
```c# using CareerHub.Client.API.Meta; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CareerHub.Client.API { public class APIInfo { public APIInfo() { this.SupportedComponents = new List<string>(); } public string BaseUrl { get; set; } public string Version { get; set; } public IEnumerable<string> SupportedComponents { get; set; } public static async Task<APIInfo> GetFromRemote(string baseUrl, ApiArea area) { var metaApi = new MetaApi(baseUrl); var result = await metaApi.GetAPIInfo(); if (!result.Success) { throw new ApplicationException(result.Error); } var remoteInfo = result.Content; string areaname = area.ToString(); var remoteArea = remoteInfo.Areas.Single(a => a.Name == areaname); if (remoteArea == null) { return null; } return new APIInfo { BaseUrl = baseUrl, Version = remoteArea.LatestVersion, SupportedComponents = remoteInfo.Components }; } } } ``` Make area name case insensitive, better error handling
```c# using CareerHub.Client.API.Meta; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CareerHub.Client.API { public class APIInfo { public APIInfo() { this.SupportedComponents = new List<string>(); } public string BaseUrl { get; set; } public string Version { get; set; } public IEnumerable<string> SupportedComponents { get; set; } public static async Task<APIInfo> GetFromRemote(string baseUrl, ApiArea area) { var metaApi = new MetaApi(baseUrl); var result = await metaApi.GetAPIInfo(); if (!result.Success) { throw new ApplicationException(result.Error); } var remoteInfo = result.Content; string areaname = area.ToString(); var remoteArea = remoteInfo.Areas.SingleOrDefault(a => a.Name.Equals(areaname, StringComparison.OrdinalIgnoreCase)); if (remoteArea == null) { return null; } return new APIInfo { BaseUrl = baseUrl, Version = remoteArea.LatestVersion, SupportedComponents = remoteInfo.Components }; } } } ```
98e065e3-7681-4308-9154-2dbaa6fbb390
{ "language": "C#" }
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public ICollection<Song> Songs { get; set; } } }``` Add virtual property to album model
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public ICollection<Song> Songs { get; set; } } }```
656a78b5-1399-4ba9-ae98-3b617249832e
{ "language": "C#" }
```c# using System; using MessageBird.Objects; using MessageBird.Resources; using MessageBird.Net; namespace MessageBird { public class Client { private IRestClient restClient; private Client(IRestClient restClient) { this.restClient = restClient; } public static Client Create(IRestClient restClient) { return new Client(restClient); } public static Client CreateDefault(string accessKey) { return new Client(new RestClient(accessKey)); } public Message SendMessage(Message message) { Messages messageToSend = new Messages(message); Messages result = (Messages)restClient.Create(messageToSend); return result.Message; } public Message SendMessage(string originator, string body, long[] msisdns, MessageOptionalArguments optionalArguments = null) { Recipients recipients = new Recipients(msisdns); Message message = new Message(originator, body, recipients, optionalArguments); Messages messages = new Messages(message); Messages result = (Messages)restClient.Create(messages); return result.Message; } public Message ViewMessage(string id) { Messages messageToView = new Messages(id); Messages result = (Messages)restClient.Retrieve(messageToView); return result.Message; } } }``` Remove obsolete send message method
```c# using System; using MessageBird.Objects; using MessageBird.Resources; using MessageBird.Net; namespace MessageBird { public class Client { private IRestClient restClient; private Client(IRestClient restClient) { this.restClient = restClient; } public static Client Create(IRestClient restClient) { return new Client(restClient); } public static Client CreateDefault(string accessKey) { return new Client(new RestClient(accessKey)); } public Message SendMessage(string originator, string body, long[] msisdns, MessageOptionalArguments optionalArguments = null) { Recipients recipients = new Recipients(msisdns); Message message = new Message(originator, body, recipients, optionalArguments); Messages messages = new Messages(message); Messages result = (Messages)restClient.Create(messages); return result.Message; } public Message ViewMessage(string id) { Messages messageToView = new Messages(id); Messages result = (Messages)restClient.Retrieve(messageToView); return result.Message; } } }```
029673eb-aa3f-49e6-b822-552fb38363c2
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; using Derby.Infrastructure; namespace Derby.Models { public class Competition { public int Id { get; set; } public int PackId { get; set; } public string Title { get; set; } public string Location { get; set; } [Required] [Display(Name = "Race Type")] public RaceType RaceType { get; set; } [Display(Name = "Created Date")] public DateTime CreatedDate { get; set; } [Required] [Display(Name = "Event Date")] [DataType(DataType.Date)] public DateTime EventDate { get; set; } [Required] [Display(Name = "Number of Lanes")] public int LaneCount { get; set; } public string CreatedById { get; set; } public Pack Pack { get; set; } public bool Completed { get; set; } } }``` Refactor from RaceType to DerbyType
```c# using System; using System.ComponentModel.DataAnnotations; using Derby.Infrastructure; namespace Derby.Models { public class Competition { public int Id { get; set; } public int PackId { get; set; } public string Title { get; set; } public string Location { get; set; } [Required] [Display(Name = "Race Type")] public DerbyType RaceType { get; set; } [Display(Name = "Created Date")] public DateTime CreatedDate { get; set; } [Required] [Display(Name = "Event Date")] [DataType(DataType.Date)] public DateTime EventDate { get; set; } [Required] [Display(Name = "Number of Lanes")] public int LaneCount { get; set; } public string CreatedById { get; set; } public Pack Pack { get; set; } public bool Completed { get; set; } } }```
ce225ef6-1f35-4ea9-95e9-981d89187e23
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BabelMark; using Newtonsoft.Json; namespace EncryptApp { class Program { static int Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: passphrase"); return 1; } Environment.SetEnvironmentVariable(MarkdownRegistry.PassphraseEnv, args[0]); var entries = MarkdownRegistry.Instance.GetEntriesAsync().Result; foreach (var entry in entries) { if (!entry.Url.StartsWith("http")) { entry.Url = StringCipher.Decrypt(entry.Url, args[0]); } else { var originalUrl = entry.Url; entry.Url = StringCipher.Encrypt(entry.Url, args[0]); var testDecrypt = StringCipher.Decrypt(entry.Url, args[0]); if (originalUrl != testDecrypt) { Console.WriteLine("Unexpected error while encrypt/decrypt. Not matching"); return 1; } } } Console.WriteLine(JsonConvert.SerializeObject(entries, Formatting.Indented)); return 0; } } } ``` Allow to encode/decode the registry
```c# using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BabelMark; using Newtonsoft.Json; namespace EncryptApp { class Program { static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: passphrase decode|encode"); return 1; } if (!(args[1] == "decode" || args[1] == "encode")) { Console.WriteLine("Usage: passphrase decode|encode"); Console.WriteLine($"Invalid argument ${args[1]}"); return 1; } var encode = args[1] == "encode"; Environment.SetEnvironmentVariable(MarkdownRegistry.PassphraseEnv, args[0]); var entries = MarkdownRegistry.Instance.GetEntriesAsync().Result; foreach (var entry in entries) { if (encode) { var originalUrl = entry.Url; entry.Url = StringCipher.Encrypt(entry.Url, args[0]); var testDecrypt = StringCipher.Decrypt(entry.Url, args[0]); if (originalUrl != testDecrypt) { Console.WriteLine("Unexpected error while encrypt/decrypt. Not matching"); return 1; } } } Console.WriteLine(JsonConvert.SerializeObject(entries, Formatting.Indented)); return 0; } } } ```
c62d3173-070d-4d8c-8f23-1ea69f1eeae2
{ "language": "C#" }
```c# using System; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; namespace ExpressiveAnnotations.MvcWebSample.UITests { public class DriverFixture : IDisposable { public DriverFixture() // called before every test class { var service = PhantomJSDriverService.CreateDefaultService(); service.IgnoreSslErrors = true; service.WebSecurity = false; var options = new PhantomJSOptions(); Driver = new PhantomJSDriver(service, options, TimeSpan.FromSeconds(15)); // headless browser testing } public RemoteWebDriver Driver { get; private set; } protected virtual void Dispose(bool disposing) { if (disposing) { if (Driver != null) { Driver.Quit(); Driver = null; } } } public void Dispose() // called after every test class { Dispose(true); GC.SuppressFinalize(this); } } } ``` Switch to FirefoxDriver due to instability of PhantomJS headless testing.
```c# using System; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; namespace ExpressiveAnnotations.MvcWebSample.UITests { public class DriverFixture : IDisposable { public DriverFixture() // called before every test class { //var service = PhantomJSDriverService.CreateDefaultService(); //service.IgnoreSslErrors = true; //service.WebSecurity = false; //var options = new PhantomJSOptions(); //Driver = new PhantomJSDriver(service, options, TimeSpan.FromSeconds(15)); // headless browser testing Driver = new FirefoxDriver(); } public RemoteWebDriver Driver { get; private set; } protected virtual void Dispose(bool disposing) { if (disposing) { if (Driver != null) { Driver.Quit(); Driver = null; } } } public void Dispose() // called after every test class { Dispose(true); GC.SuppressFinalize(this); } } } ```
0a5e514e-b2e8-4d7a-9a85-8005bf001304
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OneWireConsoleScanner { class Program { static void Main(string[] args) { Console.WriteLine("OneWire scanner"); var ports = OneWire.OneWire.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("No one availible port"); return; } var oneWire = new OneWire.OneWire(); foreach (var port in ports) { oneWire.PortName = port; try { oneWire.Open(); if (oneWire.ResetLine()) { List<OneWire.OneWire.Address> devices; oneWire.FindDevices(out devices); Console.WriteLine("Found {0} devices on port {1}", devices.Count, port); devices.ForEach(Console.WriteLine); } else { Console.WriteLine("No devices on port {0}", port); } } catch { Console.WriteLine("Can't scan port {0}", port); } finally { oneWire.Close(); } } } } } ``` Read value of OneWire device with address in first command-line argument
```c# using System; using System.Collections.Generic; namespace OneWireConsoleScanner { internal class Program { private static void Main(string[] args) { Console.WriteLine("OneWire scanner"); var ports = OneWire.OneWire.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("No one availible port"); return; } var oneWire = new OneWire.OneWire(); foreach (var port in ports) { oneWire.PortName = port; try { oneWire.Open(); if (oneWire.ResetLine()) { if (args.Length > 0) { // when read concrete devices var sensor = new OneWire.SensorDS18B20(oneWire) { Address = OneWire.OneWire.Address.Parse(args[0]) }; if (sensor.UpdateValue()) { Console.WriteLine("Sensor's {0} value is {1} C", sensor.Address, sensor.Value); } } else { List<OneWire.OneWire.Address> devices; oneWire.FindDevices(out devices); Console.WriteLine("Found {0} devices on port {1}", devices.Count, port); devices.ForEach(Console.WriteLine); } } else { Console.WriteLine("No devices on port {0}", port); } } catch { Console.WriteLine("Can't scan port {0}", port); } finally { oneWire.Close(); } } } } } ```
8c40b25e-067b-4fc6-8103-3a1b3846a20c
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Collections.ObjectModel; using Azimuth.DataAccess.Infrastructure; namespace Azimuth.DataAccess.Entities { public class User : BaseEntity { public virtual Name Name { get; set; } public virtual string ScreenName { get; set; } public virtual string Gender { get; set; } public virtual string Birthday { get; set; } public virtual string Photo { get; set; } public virtual int Timezone { get; set; } public virtual Location Location { get; set; } public virtual string Email { get; set; } public virtual ICollection<UserSocialNetwork> SocialNetworks { get; set; } public virtual ICollection<User> Followers { get; set; } public virtual ICollection<User> Following { get; set; } public virtual ICollection<PlaylistLike> PlaylistFollowing { get; set; } public User() { SocialNetworks = new List<UserSocialNetwork>(); Followers = new List<User>(); Following = new List<User>(); PlaylistFollowing = new List<PlaylistLike>(); } public override string ToString() { return Name.FirstName + Name.LastName + ScreenName + Gender + Email + Birthday + Timezone + Location.City + ", " + Location.Country + Photo; } } } ``` Insert check user fields for null
```c# using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Azimuth.DataAccess.Infrastructure; namespace Azimuth.DataAccess.Entities { public class User : BaseEntity { public virtual Name Name { get; set; } public virtual string ScreenName { get; set; } public virtual string Gender { get; set; } public virtual string Birthday { get; set; } public virtual string Photo { get; set; } public virtual int Timezone { get; set; } public virtual Location Location { get; set; } public virtual string Email { get; set; } public virtual ICollection<UserSocialNetwork> SocialNetworks { get; set; } public virtual ICollection<User> Followers { get; set; } public virtual ICollection<User> Following { get; set; } public virtual ICollection<PlaylistLike> PlaylistFollowing { get; set; } public User() { SocialNetworks = new List<UserSocialNetwork>(); Followers = new List<User>(); Following = new List<User>(); PlaylistFollowing = new List<PlaylistLike>(); } public override string ToString() { return Name.FirstName ?? String.Empty + Name.LastName ?? String.Empty + ScreenName ?? String.Empty + Gender ?? String.Empty + Email ?? String.Empty + Birthday ?? String.Empty + Timezone ?? String.Empty + ((Location != null) ? Location.City ?? String.Empty : String.Empty) + ", " + ((Location != null) ? Location.Country ?? String.Empty : String.Empty) + Photo ?? String.Empty; } } } ```
36dcf91c-12bc-4fd6-b36c-ae4a6456dcb1
{ "language": "C#" }
```c# namespace Bakery.Security { using System; using System.Text; using Text; public class BasicAuthenticationParser : IBasicAuthenticationParser { private readonly IBase64Parser base64Parser; private readonly Encoding encoding; public BasicAuthenticationParser(IBase64Parser base64Parser, Encoding encoding) { this.base64Parser = base64Parser; this.encoding = encoding; } public IBasicAuthentication TryParse(String @string) { if (!@string.StartsWith("BASIC ", StringComparison.OrdinalIgnoreCase)) return null; var basicAuthenticationBase64 = @string.Substring(6); var basicAuthenticationBytes = base64Parser.TryParse(basicAuthenticationBase64); if (basicAuthenticationBytes == null) return null; var basicAuthenticationText = TryGetString(basicAuthenticationBytes); if (basicAuthenticationText == null) return null; var parts = basicAuthenticationText.Split(new Char[] { ':' }, 2); if (parts.Length != 2) return null; return new BasicAuthentication() { Password = parts[0], Username = parts[1] }; } private String TryGetString(Byte[] bytes) { try { return encoding.GetString(bytes); } catch { return null; } } } } ``` Fix mis-matched split string indices (username is 0, password is 1).
```c# namespace Bakery.Security { using System; using System.Text; using Text; public class BasicAuthenticationParser : IBasicAuthenticationParser { private readonly IBase64Parser base64Parser; private readonly Encoding encoding; public BasicAuthenticationParser(IBase64Parser base64Parser, Encoding encoding) { this.base64Parser = base64Parser; this.encoding = encoding; } public IBasicAuthentication TryParse(String @string) { if (!@string.StartsWith("BASIC ", StringComparison.OrdinalIgnoreCase)) return null; var basicAuthenticationBase64 = @string.Substring(6); var basicAuthenticationBytes = base64Parser.TryParse(basicAuthenticationBase64); if (basicAuthenticationBytes == null) return null; var basicAuthenticationText = TryGetString(basicAuthenticationBytes); if (basicAuthenticationText == null) return null; var parts = basicAuthenticationText.Split(new Char[] { ':' }, 2); if (parts.Length != 2) return null; return new BasicAuthentication() { Password = parts[1], Username = parts[0] }; } private String TryGetString(Byte[] bytes) { try { return encoding.GetString(bytes); } catch { return null; } } } } ```
c8a3fd08-6489-465e-870d-7b15d726b5a4
{ "language": "C#" }
```c# using System.Collections.Generic; using WalletWasabi.Helpers; using WalletWasabi.Crypto.Groups; namespace System.Linq { public static class Extensions { public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) => groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc); public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, Func<TFirst, TSecond, TThird, TResult> resultSelector) { Guard.NotNull(nameof(first), first); Guard.NotNull(nameof(second), second); Guard.NotNull(nameof(third), third); Guard.NotNull(nameof(resultSelector), resultSelector); using var e1 = first.GetEnumerator(); using var e2 = second.GetEnumerator(); using var e3 = third.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext()) { yield return resultSelector(e1.Current, e2.Current, e3.Current); } } } } ``` Add extension method to check eq mat dimensions
```c# using System.Collections.Generic; using WalletWasabi.Helpers; using WalletWasabi.Crypto.Groups; using WalletWasabi.Crypto.ZeroKnowledge.LinearRelation; using WalletWasabi.Crypto; namespace System.Linq { public static class Extensions { public static GroupElement Sum(this IEnumerable<GroupElement> groupElements) => groupElements.Aggregate(GroupElement.Infinity, (ge, acc) => ge + acc); public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third, Func<TFirst, TSecond, TThird, TResult> resultSelector) { Guard.NotNull(nameof(first), first); Guard.NotNull(nameof(second), second); Guard.NotNull(nameof(third), third); Guard.NotNull(nameof(resultSelector), resultSelector); using var e1 = first.GetEnumerator(); using var e2 = second.GetEnumerator(); using var e3 = third.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext()) { yield return resultSelector(e1.Current, e2.Current, e3.Current); } } public static void CheckDimesions(this IEnumerable<Equation> equations, IEnumerable<ScalarVector> allResponses) { if (equations.Count() != allResponses.Count() || Enumerable.Zip(equations, allResponses).Any(x => x.First.Generators.Count() != x.Second.Count())) { throw new ArgumentException("The number of responses and the number of generators in the equations do not match."); } } } } ```
730d6327-1a2c-4c1c-a473-e4dc4a161601
{ "language": "C#" }
```c# using UnityEngine; namespace HoloToolkit.Unity { public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera main { get { return cachedCamera ?? CacheMain(Camera.main); } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> /// <returns></returns> private static Camera CacheMain(Camera newMain) { return cachedCamera = newMain; } } } ``` Rename cache refresh and make public
```c# using UnityEngine; namespace HoloToolkit.Unity { public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera main { get { return cachedCamera ?? Refresh(Camera.main); } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> /// <returns></returns> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } } ```
8831efa8-97b9-423c-9ec0-df2c10972be0
{ "language": "C#" }
```c# using System; namespace CertiPay.Common.Notifications { public class AndroidNotification : Notification { public static string QueueName { get; } = "AndroidNotifications"; // Message => Content /// <summary> /// The subject line of the email /// </summary> public String Title { get; set; } // TODO Android specific properties? Image, Sound, Action Button, Picture, Priority } }``` Add comments and the TTL and highPriority flags for android notifications
```c# using System; namespace CertiPay.Common.Notifications { /// <summary> /// Describes a notification sent to an Android device via Google Cloud Messaging /// </summary> public class AndroidNotification : Notification { public static string QueueName { get; } = "AndroidNotifications"; /// <summary> /// The subject line of the notification /// </summary> public String Title { get; set; } /// <summary> /// Maximum lifespan of the message, from 0 to 4 weeks, after which delivery attempts will expire. /// Setting this to 0 seconds will prevent GCM from throttling the "now or never" message. /// /// GCM defaults this to 4 weeks. /// </summary> public TimeSpan? TimeToLive { get; set; } /// <summary> /// Set high priority only if the message is time-critical and requires the user’s /// immediate interaction, and beware that setting your messages to high priority contributes /// more to battery drain compared to normal priority messages. /// </summary> public Boolean HighPriority { get; set; } = false; } }```
b5a6c866-0830-4c17-988e-b792c583a27a
{ "language": "C#" }
```c# using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } } ``` Revert "Revert "Revert "Update Examples/.vs/Aspose.Email.Examples.CSharp/v15/Server/sqlite3/storage.ide-wal"""
```c# using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } } ```
074c3869-9c73-4138-bc43-e20048ccc8d3
{ "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("ExtractCopyright.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // 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("085a7785-c407-4623-80c0-bffd2b0d2475")] #if STRONG_NAME [assembly: AssemblyKeyFileAttribute("../palaso.snk")] #endif``` Add nl to end of 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("ExtractCopyright.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // 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("085a7785-c407-4623-80c0-bffd2b0d2475")] #if STRONG_NAME [assembly: AssemblyKeyFileAttribute("../palaso.snk")] #endif ```
0226d603-0029-4c38-9e63-2e981f382d9f
{ "language": "C#" }
```c# using NUnit.Framework; namespace ZeroLog.Tests { [TestFixture] public class UninitializedLogManagerTests { [TearDown] public void Teardown() { LogManager.Shutdown(); } [Test] public void should_log_without_initialize() { LogManager.GetLogger("Test").Info($"Test"); } } } ``` Add unit test that checks that a logger retrieved before the log manager is initialised can log correctly
```c# using System; using NFluent; using NUnit.Framework; using ZeroLog.Configuration; namespace ZeroLog.Tests { [TestFixture, NonParallelizable] public class UninitializedLogManagerTests { private TestAppender _testAppender; [SetUp] public void SetUpFixture() { _testAppender = new TestAppender(true); } [TearDown] public void Teardown() { LogManager.Shutdown(); } [Test] public void should_log_without_initialize() { LogManager.GetLogger("Test").Info($"Test"); } [Test] public void should_log_correctly_when_logger_is_retrieved_before_log_manager_is_initialized() { var log = LogManager.GetLogger<LogManagerTests>(); LogManager.Initialize(new ZeroLogConfiguration { LogMessagePoolSize = 10, RootLogger = { Appenders = { _testAppender } } }); var signal = _testAppender.SetMessageCountTarget(1); log.Info("Lol"); Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue(); } } } ```
201c4d93-acd3-499e-990e-0ca57d314a1b
{ "language": "C#" }
```c# using System; namespace Renci.SshClient { public class ConnectionInfo { public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public PrivateKeyFile KeyFile { get; set; } public TimeSpan Timeout { get; set; } public int RetryAttempts { get; set; } public int MaxSessions { get; set; } public ConnectionInfo() { // Set default connection values this.Port = 22; this.Timeout = TimeSpan.FromMinutes(30); this.RetryAttempts = 10; this.MaxSessions = 10; } } } ``` Change default timeout to 30 seconds
```c# using System; namespace Renci.SshClient { public class ConnectionInfo { public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public PrivateKeyFile KeyFile { get; set; } public TimeSpan Timeout { get; set; } public int RetryAttempts { get; set; } public int MaxSessions { get; set; } public ConnectionInfo() { // Set default connection values this.Port = 22; this.Timeout = TimeSpan.FromSeconds(30); this.RetryAttempts = 10; this.MaxSessions = 10; } } } ```
fdd4301a-016e-450e-8a68-12ccf8ccea3e
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Timing; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher { // Using a frozen clock because trails should not be animated when the skin has an animated catcher. // TODO: The animation should be frozen at the animation frame at the time of the trail generation. Clock = new FramedClock(new ManualClock()), }; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } } ``` Fix catcher hyper-dash afterimage is not always displayed
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Timing; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher { // Using a frozen clock because trails should not be animated when the skin has an animated catcher. // TODO: The animation should be frozen at the animation frame at the time of the trail generation. Clock = new FramedClock(new ManualClock()), }; } protected override void FreeAfterUse() { ClearTransforms(); Alpha = 1; base.FreeAfterUse(); } } } ```
54306772-2f86-4b49-95d6-8f0e55eb1c42
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } } ``` Handle subdirectories during beatmap stable import
```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 System.Linq; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); protected override IEnumerable<string> GetStableImportPaths(Storage storage) { foreach (string beatmapDirectory in storage.GetDirectories(string.Empty)) { var beatmapStorage = storage.GetStorageForDirectory(beatmapDirectory); if (!beatmapStorage.GetFiles(string.Empty).ExcludeSystemFileNames().Any()) { // if a directory doesn't contain files, attempt looking for beatmaps inside of that directory. // this is a special behaviour in stable for beatmaps only, see https://github.com/ppy/osu/issues/18615. foreach (string beatmapInDirectory in GetStableImportPaths(beatmapStorage)) yield return beatmapStorage.GetFullPath(beatmapInDirectory); } else yield return storage.GetFullPath(beatmapDirectory); } } public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } } ```
d7e4588c-53b7-4e96-bbad-8747dc02fa8f
{ "language": "C#" }
```c# using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class WebApiTemplateTest : TemplateTestBase { public WebApiTemplateTest(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(null)] [InlineData("net461")] public void WebApiTemplate_Works(string targetFrameworkOverride) { RunDotNetNew("api", targetFrameworkOverride); foreach (var publish in new[] { false, true }) { using (var aspNetProcess = StartAspNetProcess(targetFrameworkOverride, publish)) { aspNetProcess.AssertOk("/api/values"); aspNetProcess.AssertNotFound("/"); } } } } } ``` Update tests to use newer name for 'webapi' template
```c# using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class WebApiTemplateTest : TemplateTestBase { public WebApiTemplateTest(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(null)] [InlineData("net461")] public void WebApiTemplate_Works(string targetFrameworkOverride) { RunDotNetNew("webapi", targetFrameworkOverride); foreach (var publish in new[] { false, true }) { using (var aspNetProcess = StartAspNetProcess(targetFrameworkOverride, publish)) { aspNetProcess.AssertOk("/api/values"); aspNetProcess.AssertNotFound("/"); } } } } } ```
2afee1a5-6a09-4298-b581-9191169f25d6
{ "language": "C#" }
```c# using Nancy; namespace Plating { public class Bootstrapper : DefaultNancyBootstrapper { public Bootstrapper() { Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true; } } }``` Enable error traces for Razor.
```c# using Nancy; namespace Plating { public class Bootstrapper : DefaultNancyBootstrapper { public Bootstrapper() { StaticConfiguration.DisableErrorTraces = false; Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true; } } }```
fae56a8c-1818-481d-b60b-9d98bdec3a21
{ "language": "C#" }
```c# namespace CompetitionPlatform.Helpers { public static class StreamsRoles { public const string Admin = "ADMIN"; } public static class ResultVoteTypes { public const string Admin = "ADMIN"; public const string Author = "AUTHOR"; } public static class OrderingConstants { public const string All = "All"; public const string Ascending = "Ascending"; public const string Descending = "Descending"; } public static class LykkeEmailDomains { public const string LykkeCom = "lykke.com"; public const string LykkexCom = "lykkex.com"; } } ``` Change class name to OrderingTypes.
```c# namespace CompetitionPlatform.Helpers { public static class StreamsRoles { public const string Admin = "ADMIN"; } public static class ResultVoteTypes { public const string Admin = "ADMIN"; public const string Author = "AUTHOR"; } public static class OrderingTypes { public const string All = "All"; public const string Ascending = "Ascending"; public const string Descending = "Descending"; } public static class LykkeEmailDomains { public const string LykkeCom = "lykke.com"; public const string LykkexCom = "lykkex.com"; } } ```
a03d6a1d-f248-42a2-b71a-dbdd831472f0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Ajax { /// <summary> /// A metadata attribute to indicate parameter methods /// Does not affect execution. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class AjaxMethodParameterAttribute : Attribute { public string ParameterName { get; set; } public AjaxMethodParameterType ParameterType { get; set; } } public enum AjaxMethodParameterType { StringParameter, ObjectParameter, ArrayParameter } } ``` Add BoolParameter and IntParameter to enum
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Ajax { /// <summary> /// A metadata attribute to indicate parameter methods /// Does not affect execution. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class AjaxMethodParameterAttribute : Attribute { public string ParameterName { get; set; } public AjaxMethodParameterType ParameterType { get; set; } } public enum AjaxMethodParameterType { StringParameter, ObjectParameter, ArrayParameter, BoolParameter, IntParameter } } ```
df54e1de-cab6-4b40-832d-3f8426007bb7
{ "language": "C#" }
```c# /* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; namespace OpenSim.Framework { public interface ISearchModule { } } ``` Add Refresh() Method to ISerachModule to allow forcing a sim to resend it's search data
```c# /* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; namespace OpenSim.Framework { public interface ISearchModule { void Refresh(); } } ```
177448dd-70c8-4b81-81a7-eb50e842b51a
{ "language": "C#" }
```c# namespace dotless.Core.Parser.Functions { using System.Linq; using Infrastructure; using Infrastructure.Nodes; using Tree; using Utils; public class RgbaFunction : Function { protected override Node Evaluate(Env env) { if (Arguments.Count == 2) { Guard.ExpectNode<Color>(Arguments[0], this, Location); Guard.ExpectNode<Number>(Arguments[1], this, Location); return new Color(((Color) Arguments[0]).RGB, ((Number) Arguments[1]).Value); } Guard.ExpectNumArguments(4, Arguments.Count, this, Location); Guard.ExpectAllNodes<Number>(Arguments, this, Location); var args = Arguments.Cast<Number>(); var rgb = args.Take(3); return new Color(rgb, args.ElementAt(3)); } } }``` Use new return value of Guard.ExpectNode to refine casting...
```c# namespace dotless.Core.Parser.Functions { using System.Linq; using Infrastructure; using Infrastructure.Nodes; using Tree; using Utils; public class RgbaFunction : Function { protected override Node Evaluate(Env env) { if (Arguments.Count == 2) { var color = Guard.ExpectNode<Color>(Arguments[0], this, Location); var alpha = Guard.ExpectNode<Number>(Arguments[1], this, Location); return new Color(color.RGB, alpha.Value); } Guard.ExpectNumArguments(4, Arguments.Count, this, Location); Guard.ExpectAllNodes<Number>(Arguments, this, Location); var args = Arguments.Cast<Number>(); var rgb = args.Take(3); return new Color(rgb, args.ElementAt(3)); } } }```
d9dcaef0-ae81-4379-a46c-612bfd14dd6b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace unBand { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { unBand.Properties.Settings.Default.Save(); } private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Telemetry.Client.TrackException(e.Exception); } } } ``` Add visual MessageBox when an unhandled crash is encountered
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace unBand { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { unBand.Properties.Settings.Default.Save(); } private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Telemetry.Client.TrackException(e.Exception); MessageBox.Show("An unhandled exception occurred - sorry about that, we're going to have to crash now :(\n\nYou can open a bug with a copy of this crash: hit Ctrl + C right now and then paste into a new bug at https://github.com/nachmore/unBand/issues.\n\n" + e.Exception.ToString(), "Imminent Crash", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } } ```
d0db3c1f-afac-468d-9eac-0315282cf3d5
{ "language": "C#" }
```c# using System.IO; using System.Net.Http; using MyCouch.Extensions; using MyCouch.Serialization; namespace MyCouch.Responses.Factories { public class DocumentResponseFactory : ResponseFactoryBase { public DocumentResponseFactory(SerializationConfiguration serializationConfiguration) : base(serializationConfiguration) { } public virtual DocumentResponse Create(HttpResponseMessage httpResponse) { return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse); } protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse) { using (var content = httpResponse.Content.ReadAsStream()) { if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage)) PopulateDocumentHeaderFromResponseStream(response, content); else { PopulateMissingIdFromRequestUri(response, httpResponse); PopulateMissingRevFromRequestHeaders(response, httpResponse); } content.Position = 0; using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding)) { response.Content = reader.ReadToEnd(); } } } } }``` Fix issue with trailing whitespace.
```c# using System.IO; using System.Net.Http; using System.Text; using MyCouch.Extensions; using MyCouch.Serialization; namespace MyCouch.Responses.Factories { public class DocumentResponseFactory : ResponseFactoryBase { public DocumentResponseFactory(SerializationConfiguration serializationConfiguration) : base(serializationConfiguration) { } public virtual DocumentResponse Create(HttpResponseMessage httpResponse) { return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse); } protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse) { using (var content = httpResponse.Content.ReadAsStream()) { if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage)) PopulateDocumentHeaderFromResponseStream(response, content); else { PopulateMissingIdFromRequestUri(response, httpResponse); PopulateMissingRevFromRequestHeaders(response, httpResponse); } content.Position = 0; var sb = new StringBuilder(); using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding)) { while (!reader.EndOfStream) { sb.Append(reader.ReadLine()); } } response.Content = sb.ToString(); sb.Clear(); } } } }```
167ff654-2267-4690-8d4a-97a18fd003b9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using RepoZ.Api.Common; using RepoZ.Api.Common.Git; using RepoZ.Api.Git; namespace RepoZ.Api.Win.Git { public class WindowsRepositoryCache : FileRepositoryCache { public WindowsRepositoryCache(IErrorHandler errorHandler) : base(errorHandler) { } public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "RepoZ\\Repositories.cache"); } } ``` Use the user-specific appdata path for the repository cache
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using RepoZ.Api.Common; using RepoZ.Api.Common.Git; using RepoZ.Api.Git; namespace RepoZ.Api.Win.Git { public class WindowsRepositoryCache : FileRepositoryCache { public WindowsRepositoryCache(IErrorHandler errorHandler) : base(errorHandler) { } public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RepoZ\\Repositories.cache"); } } ```
2066d02a-f5a3-44b9-ab36-382c73f23dfb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class DdsBenchmark { [Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Dds.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings { Format = MagickFormat.Dds }; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Dds)) { return image.Width; } } } } ``` Remove unused directives from benchmarking
```c# using System.IO; using BenchmarkDotNet.Attributes; using FreeImageAPI; using ImageMagick; using DS = DevILSharp; namespace Pfim.Benchmarks { public class DdsBenchmark { [Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")] public string Payload { get; set; } private byte[] data; [GlobalSetup] public void SetupData() { data = File.ReadAllBytes(Payload); DS.Bootstrap.Init(); } [Benchmark] public IImage Pfim() => Dds.Create(new MemoryStream(data)); [Benchmark] public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data)); [Benchmark] public int ImageMagick() { var settings = new MagickReadSettings { Format = MagickFormat.Dds }; using (var image = new MagickImage(new MemoryStream(data), settings)) { return image.Width; } } [Benchmark] public int DevILSharp() { using (var image = DS.Image.Load(data, DS.ImageType.Dds)) { return image.Width; } } } } ```
a38a28fd-9823-4af2-8c03-2a6e21f5ac8e
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Yaclops { /// <summary> /// Settings that alter the default behavior of the parser, but do not depend on the command type. /// </summary> public class GlobalParserSettings { /// <summary> /// Constructor /// </summary> public GlobalParserSettings() { HelpVerb = "help"; HelpFlags = new[] { "-h", "--help", "-?" }; } /// <summary> /// The verb that indicates help is desired. Defaults to "help". /// </summary> public string HelpVerb { get; set; } /// <summary> /// List of strings that indicate help is desired. Defaults to -h, -? and --help. /// </summary> public IEnumerable<string> HelpFlags { get; set; } /// <summary> /// Enable (hidden) internal Yaclops command used for debugging. /// </summary> public bool EnableYaclopsCommands { get; set; } } } ``` Enable yaclops internal commands by default
```c# using System.Collections.Generic; namespace Yaclops { /// <summary> /// Settings that alter the default behavior of the parser, but do not depend on the command type. /// </summary> public class GlobalParserSettings { /// <summary> /// Constructor /// </summary> public GlobalParserSettings() { HelpVerb = "help"; HelpFlags = new[] { "-h", "--help", "-?" }; EnableYaclopsCommands = true; } /// <summary> /// The verb that indicates help is desired. Defaults to "help". /// </summary> public string HelpVerb { get; set; } /// <summary> /// List of strings that indicate help is desired. Defaults to -h, -? and --help. /// </summary> public IEnumerable<string> HelpFlags { get; set; } /// <summary> /// Enable (hidden) internal Yaclops command used for debugging. /// </summary> public bool EnableYaclopsCommands { get; set; } } } ```
735c2e0e-5617-4f34-b49c-5669aa94fec9
{ "language": "C#" }
```c# using Glimpse.Host.Web.Owin; using Owin; namespace Glimpse.Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { app.Use<GlimpseMiddleware>(); app.UseWelcomePage(); app.UseErrorPage(); } } }``` Update startup of sample to pass in the serviceProvider
```c# using Glimpse.Host.Web.Owin; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; using Owin; using System.Collections.Generic; namespace Glimpse.Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { var serviceDescriptors = new List<IServiceDescriptor>(); var serviceProvider = serviceDescriptors.BuildServiceProvider(); app.Use<GlimpseMiddleware>(serviceProvider); app.UseWelcomePage(); app.UseErrorPage(); } } }```
f9e8eb9f-3b05-42d3-81ac-e453ce1169a2
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ``` Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
```c# //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] ```
b1cb7de3-48b1-46e0-938a-9ccfdd1db2d8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public IList<MailConfiguration> Mail { get; set; } public IList<RabbitMQConfiguration> RabbitMQ { get; set; } public IList<ElasticsearchConfiguration> Elasticsearch { get; set; } } } ``` Use List because IList isn't supported by FX.Configuration
```c# using System; using System.Collections.Generic; namespace IntegrationEngine.Core.Configuration { public class IntegrationPointConfigurations { public List<MailConfiguration> Mail { get; set; } public List<RabbitMQConfiguration> RabbitMQ { get; set; } public List<ElasticsearchConfiguration> Elasticsearch { get; set; } } } ```
2e30a178-9000-457b-b341-f9e7964e777f
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded && Beatmap.Value.Track != null) // null check... wasn't required until now? { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } } ``` Remove unnecessary null check and associated comment
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class RateAdjustedBeatmapTestScene : ScreenTestScene { protected override void Update() { base.Update(); if (Beatmap.Value.TrackLoaded) { // note that this will override any mod rate application Beatmap.Value.Track.Tempo.Value = Clock.Rate; } } } } ```
fb51525d-5f14-439e-af2f-238456a07893
{ "language": "C#" }
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge KHTML = 1 << 5, // Konqueror Presto = 1 << 6, // Goanna = 1 << 7, // Pale Moon NetSurf = 1 << 8, // NetSurf NetFront = 1 << 9, // Access NetFront Prince = 1 << 10, // Robin = 1 << 11, // The Bat! Servo = 1 << 12, // Mozilla & Samsung Tkhtml = 1 << 13, // hv3 Links2 = 1 << 14, // launched with -g Others = 1 << 15 // Others } } ``` Remove not common engine from base
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System; namespace Wangkanai.Detection.Models { [Flags] public enum Engine { Unknown = 0, // Unknown engine WebKit = 1, // iOs (Safari, WebViews, Chrome <28) Blink = 1 << 1, // Google Chrome, Opera v15+ Gecko = 1 << 2, // Firefox, Netscape Trident = 1 << 3, // IE, Outlook EdgeHTML = 1 << 4, // Microsoft Edge Servo = 1 << 12, // Mozilla & Samsung Others = 1 << 15 // Others } } ```
89d2b2b1-081c-4427-a2eb-ce1671a8b7fa
{ "language": "C#" }
```c# @model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>``` Fix APFT list sort by score
```c# @model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td data-sort="@model.TotalScore"> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>```
b84d9121-a61f-44d7-af2c-b7169ca1b885
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while on hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for hyper-dash fruits. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } } ``` Fix grammer issue and more rewording
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Catch.Skinning { public enum CatchSkinColour { /// <summary> /// The colour to be used for the catcher while in hyper-dashing state. /// </summary> HyperDash, /// <summary> /// The colour to be used for fruits that grant the catcher the ability to hyper-dash. /// </summary> HyperDashFruit, /// <summary> /// The colour to be used for the "exploding" catcher sprite on beginning of hyper-dashing. /// </summary> HyperDashAfterImage, } } ```
e21ce9f8-418f-4f81-9e77-920324eb8512
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; Bar.Height = 0; } } } } } ``` Update header breadcrumb tab control
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; Height = 47; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { AccentColour = colourProvider.Light2; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { RelativeSizeAxes = Axes.Y; Text.Font = Text.Font.With(size: 14); Text.Anchor = Anchor.CentreLeft; Text.Origin = Anchor.CentreLeft; Chevron.Y = 1; Bar.Height = 0; } // base OsuTabItem makes font bold on activation, we don't want that here protected override void OnActivated() => FadeHovered(); protected override void OnDeactivated() => FadeUnhovered(); } } } } ```
f1960641-4b57-4daa-b2b6-9fbba39042a2
{ "language": "C#" }
```c# using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } } ``` Revise dropdowns for building unitypackages.
```c# using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Testing/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } } ```
affb486c-e50f-4f6e-bdc3-12fbbdf183c7
{ "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.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")] ``` Increase project version number to 0.11.0
```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.11.0.0")] [assembly: AssemblyFileVersion("0.11.0.0")] ```
1ef000dd-6860-4612-8feb-7c3611800919
{ "language": "C#" }
```c# #define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } } ``` Check debugger is attached before writing something to it
```c# #define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null && Debugger.IsAttached) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } } ```
382e1218-f8f9-4a8f-b33e-553f7691aed8
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Count > 0) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } } ``` Use Any instead of Count > 0
```c# using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Any()) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } } ```
f4743512-5908-424e-8b7a-48392ca40b11
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else if (qnotes.IsActive) qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } } ``` Revert "Fixed a bug where closing the quicknotes window then clicking show/hide quicknotes on the settings window would crash the program."
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } } ```
6e4da705-2210-4e40-ac49-14c8889d1151
{ "language": "C#" }
```c# namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); } } } ``` Set env vars when updating VSTS variables
```c# namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); SetEnvVariableForBuildVariable("Build.BuildNumber", buildNumber); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); SetEnvVariableForBuildVariable(name, value); } private static void SetEnvVariableForBuildVariable(string name, string value) { string envVarName = name.ToUpperInvariant().Replace('.', '_'); Environment.SetEnvironmentVariable(envVarName, value); } } } ```
2828717e-7061-42c7-bdfd-eb91c56cc61d
{ "language": "C#" }
```c# using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<DeploymentPlannerViewModel>(); } } } ``` Set default size for window
```c# using System.Collections.Generic; using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { var settings = new Dictionary<string, object> { { "SizeToContent", SizeToContent.Manual }, { "Height" , 768 }, { "Width" , 768 }, }; DisplayRootViewFor<DeploymentPlannerViewModel>(settings); } } } ```
752e6997-d843-4454-bd3f-0cc124952e5a
{ "language": "C#" }
```c# using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } } } ``` Add helper method to return KeyModifier
```c# using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } public KeyModifier KeyModifier { get { KeyModifier mod = KeyModifier.None; if (AltModifier) { mod |= KeyModifier.Alt; } if (WinModifier) { mod |= KeyModifier.Win; } if (ShiftModifier) { mod |= KeyModifier.Shift; } if (CtrlModifier) { mod |= KeyModifier.Ctrl; } return mod; } } } } ```
b737c1ec-9153-41f5-8bd3-4edd0dcd3859
{ "language": "C#" }
```c# using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (object obj, string argumentName) { NotNull (obj, argumentName); if (!(obj is String)) return; var val = (String)obj; if (string.IsNullOrWhiteSpace(val)) throw new ArgumentException(argumentName); } } } ``` Change type signature of NotNullOrEmpty to string since it's only used for strings.
```c# using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (string obj, string argumentName) { NotNull (obj, argumentName); if (string.IsNullOrWhiteSpace(obj)) throw new ArgumentException(argumentName); } } } ```
c2a789e2-633a-4d4f-bbba-43f6220839c4
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { public DefaultSmoke() { Radius = 2; } } } ``` Update default cursor smoke implementation to use a texture
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Textures; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { [BackgroundDependencyLoader] private void load(TextureStore textures) { // ISkinSource doesn't currently fallback to global textures. // We might want to change this in the future if the intention is to allow the user to skin this as per legacy skins. Texture = textures.Get("Gameplay/osu/cursor-smoke"); } } } ```
c8df4dfd-9d4b-4c1e-8a46-173b9983fd5f
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { if (instruction.operand == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }``` Make Visual Studio 2017 Enterprise happy
```c# using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }```
b9189a2b-d7b3-4ed7-88ec-2dbf1675f904
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; // Use this for initialization void Start () { curTime = maxTime; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); Debug.Log(prettyTime); } } ``` Update text on countdown timer GUI
```c# using UnityEngine; using System.Collections; using UnityEngine.UI; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; private Text text; // Use this for initialization void Start () { curTime = maxTime; text = gameObject.GetComponent( typeof(Text) ) as Text; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); //Debug.Log(prettyTime); text.text = prettyTime; } } ```
1efb2273-fa0f-4e1d-bc80-75e4495f0ca8
{ "language": "C#" }
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } } }``` Fix file paths default value null
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } = ""; } }```
01f40f46-83b7-4c3a-aa4d-20d42dfa8c45
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; // Use this for initialization void Start() { // Here only for test Rain(); } // Update is called once per frame void Update() { } void Rain() { int whichRain = Random.Range(1, 4); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(-4f, 4f); float y_rand = Random.Range(-1f, 1f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y + y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } } ``` Make it Rain now rains blocks constantly
```c# using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; int count = 0; // Use this for initialization void Start() { } // Update is called once per frame // Just for test void Update() { if (count % 100 == 0) { Rain(); count++; } count++; } // Called only when dance is finished void Rain() { int whichRain = Random.Range(1, 5); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(minX, maxX - rain.GetComponent<BoxCollider2D>().size.x); float y_rand = Random.Range(1f, 3f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y - y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }```
28b91805-7974-4b4c-9b03-b666a911a286
{ "language": "C#" }
```c# using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct MaybeAssume<T> { ///<summary>Create a new Maybe{T}.</summary> private MaybeAssume(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = !_hasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } } ``` Align failing CodeContracts case better to object Invariant.
```c# using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct Maybe<T> { ///<summary>Create a new Maybe{T}.</summary> private Maybe(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = ! HasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } } ```
7750646d-7df0-4d4b-bae8-c72402d28857
{ "language": "C#" }
```c# using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) .EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }``` Disable partitioning in the bootstrapper.
```c# using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) //.EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }```
68e2bf82-e0a5-4b0b-8f3c-00773ebe2ef3
{ "language": "C#" }
```c# // ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }``` Fix in API, added IsLocked field to nested schema.
```c# // ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is locked. /// </summary> public bool IsLocked { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }```
e73d4bf8-d404-45c3-8286-51826b70cd9d
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { //DontDestroyOnLoad(money); Application.LoadLevel(1); } } ``` Adjust screen resolution to samsung galaxy s4
```c# using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { Screen.SetResolution(1080, 1920, true); //DontDestroyOnLoad(money); Application.LoadLevel(1); } } ```
22a966b5-dbad-4537-aabf-541984ac9bf7
{ "language": "C#" }
```c# using System; namespace TDDUnit { class Assert { public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { string message = string.Format("Expected: Not '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void That(bool condition) { Equal(true, condition); } } } ``` Refactor the error caused by a failing assertion
```c# using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual); } } public static void That(bool condition) { Equal(true, condition); } } } ```
00299689-4535-4c75-85d5-327fda8cbacf
{ "language": "C#" }
```c# using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } } ``` Clean up: removed empty line
```c# using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } } ```
cdac5396-d167-4646-bcd1-1092020f23f5
{ "language": "C#" }
```c# using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); } //--------------------------------------------------------------------------- }``` Fix for 'new' setting button triggering if you hit enter when editing a setting.
```c# using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; settingsView.Focus(); } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); settingsView.Focus(); } //--------------------------------------------------------------------------- }```
f0363849-a95d-4fe5-b403-b6e115d0f53d
{ "language": "C#" }
```c# /******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, } }``` Update List of ConnectorTypes to be compatible with ISOBUS.net List
```c# /******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, ChassisMountedSelfPropelled } }```
cffe28f4-4d31-4005-b4c1-d9e7b9435086
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } public IEnumerable<string> GetDirectories(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } } ``` Test fix- catching permission denied exceptions
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetFiles: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetDirectories(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetDirectories: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }```
c99368d1-f0d9-40f5-b602-00d56dfa49a7
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0")] [assembly: AssemblyFileVersion("28.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] ``` Make version 4 digits to fix replacement regex
```c# using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0.0")] [assembly: AssemblyFileVersion("28.0.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] ```
91dddb83-9f24-4858-854f-7a2fdb2779fa
{ "language": "C#" }
```c# using LibGit2Sharp.Handlers; namespace LibGit2Sharp { /// <summary> /// Collection of parameters controlling Fetch behavior. /// </summary> public sealed class FetchOptions { /// <summary> /// Specifies the tag-following behavior of the fetch operation. /// <para> /// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/> /// based on the remote's <see cref="Remote.TagFetchMode"/> configuration. /// </para> /// <para>If neither this property nor the remote `tagopt` configuration is set, /// this will default to <see cref="TagFetchMode.Auto"/> (i.e. tags that point to objects /// retrieved during this fetch will be retrieved as well).</para> /// </summary> public TagFetchMode? TagFetchMode { get; set; } /// <summary> /// Delegate that progress updates of the network transfer portion of fetch /// will be reported through. /// </summary> public ProgressHandler OnProgress { get; set; } /// <summary> /// Delegate that updates of remote tracking branches will be reported through. /// </summary> public UpdateTipsHandler OnUpdateTips { get; set; } /// <summary> /// Callback method that transfer progress will be reported through. /// <para> /// Reports the client's state regarding the received and processed (bytes, objects) from the server. /// </para> /// </summary> public TransferProgressHandler OnTransferProgress { get; set; } /// <summary> /// Credentials to use for username/password authentication. /// </summary> public Credentials Credentials { get; set; } } } ``` Fix Xml documentation compilation warning
```c# using LibGit2Sharp.Handlers; namespace LibGit2Sharp { /// <summary> /// Collection of parameters controlling Fetch behavior. /// </summary> public sealed class FetchOptions { /// <summary> /// Specifies the tag-following behavior of the fetch operation. /// <para> /// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/> /// based on the remote's <see cref="Remote.TagFetchMode"/> configuration. /// </para> /// <para>If neither this property nor the remote `tagopt` configuration is set, /// this will default to <see cref="F:TagFetchMode.Auto"/> (i.e. tags that point to objects /// retrieved during this fetch will be retrieved as well).</para> /// </summary> public TagFetchMode? TagFetchMode { get; set; } /// <summary> /// Delegate that progress updates of the network transfer portion of fetch /// will be reported through. /// </summary> public ProgressHandler OnProgress { get; set; } /// <summary> /// Delegate that updates of remote tracking branches will be reported through. /// </summary> public UpdateTipsHandler OnUpdateTips { get; set; } /// <summary> /// Callback method that transfer progress will be reported through. /// <para> /// Reports the client's state regarding the received and processed (bytes, objects) from the server. /// </para> /// </summary> public TransferProgressHandler OnTransferProgress { get; set; } /// <summary> /// Credentials to use for username/password authentication. /// </summary> public Credentials Credentials { get; set; } } } ```
224f16bd-86ba-4764-a892-c2fa96ed0f03
{ "language": "C#" }
```c# using System.Resources; using System.Reflection; // 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.0-alpha1")] ``` Update to beta1 for next release
```c# using System.Resources; using System.Reflection; // 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.1.1")] [assembly: AssemblyFileVersion("1.0.1.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.1-beta1")] ```