Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Mef")] [assembly: AssemblyDescription("Autofac MEF Integration")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mef, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Mef")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mef, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)]
Store settings as plain strings, without SettingsHelper
using Template10.Mvvm; using Template10.Services.SettingsService; namespace Zermelo.App.UWP.Services { public class SettingsService : BindableBase, ISettingsService { ISettingsHelper _helper; public SettingsService(ISettingsHelper settingsHelper) { _helper = settingsHelper; } private T Read<T>(string key, T otherwise = default(T)) => _helper.Read<T>(key, otherwise, SettingsStrategies.Roam); private void Write<T>(string key, T value) => _helper.Write(key, value, SettingsStrategies.Roam); //Account public string School { get => Read<string>("Host"); set { Write("Host", value); RaisePropertyChanged(); } } public string Token { get => Read<string>("Token"); set { Write("Token", value); RaisePropertyChanged(); } } } }
using Template10.Mvvm; using Template10.Services.SettingsService; using Windows.Storage; namespace Zermelo.App.UWP.Services { public class SettingsService : BindableBase, ISettingsService { ApplicationDataContainer _settings; public SettingsService() { _settings = ApplicationData.Current.RoamingSettings; } private T Read<T>(string key) => (T)_settings.Values[key]; private void Write<T>(string key, T value) => _settings.Values[key] = value; //Account public string School { get => Read<string>("Host"); set { Write("Host", value); RaisePropertyChanged(); } } public string Token { get => Read<string>("Token"); set { Write("Token", value); RaisePropertyChanged(); } } } }
Handle null/missing category and tags
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. namespace ServiceStack.IntroSpec.Services { using System.Linq; using DTO; public class ApiSpecMetadataService : IService { private readonly IApiDocumentationProvider documentationProvider; public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider) { documentationProvider.ThrowIfNull(nameof(documentationProvider)); this.documentationProvider = documentationProvider; } public object Get(SpecMetadataRequest request) { var documentation = documentationProvider.GetApiDocumentation(); return SpecMetadataResponse.Create( documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(), documentation.Resources.Select(r => r.Category).Distinct().ToArray(), documentation.Resources.SelectMany(r => r.Tags).Distinct().ToArray() ); } } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. namespace ServiceStack.IntroSpec.Services { using System.Linq; using DTO; public class ApiSpecMetadataService : IService { private readonly IApiDocumentationProvider documentationProvider; public ApiSpecMetadataService(IApiDocumentationProvider documentationProvider) { documentationProvider.ThrowIfNull(nameof(documentationProvider)); this.documentationProvider = documentationProvider; } public object Get(SpecMetadataRequest request) { var documentation = documentationProvider.GetApiDocumentation(); return SpecMetadataResponse.Create( documentation.Resources.Select(r => r.TypeName).Distinct().ToArray(), documentation.Resources.Select(r => r.Category).Where(c => !string.IsNullOrEmpty(c)).Distinct().ToArray(), documentation.Resources.SelectMany(r => r.Tags ?? new string[0]).Distinct().ToArray() ); } } }
Fix evaluation of max values for random int and long
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StrangerData.Utils { internal static class RandomValues { public static object ForColumn(TableColumnInfo columnInfo) { switch (columnInfo.ColumnType) { case ColumnType.String: // generates a random string return Any.String(columnInfo.MaxLength); case ColumnType.Int: // generates a random integer long maxValue = 10 ^ columnInfo.Precision - 1; if (maxValue > int.MaxValue) { return Any.Long(1, columnInfo.Precision - 1); } return Any.Int(1, 10 ^ columnInfo.Precision - 1); case ColumnType.Decimal: // generates a random decimal return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Double: // generates a random double return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Long: // generates a random long return Any.Long(1, 10 ^ columnInfo.Precision - 1); case ColumnType.Boolean: // generates a random boolean return Any.Boolean(); case ColumnType.Guid: // generates a random guid return Guid.NewGuid(); case ColumnType.Date: // generates a random date return Any.DateTime().Date; case ColumnType.Datetime: // generates a random DateTime return Any.DateTime(); default: return null; } } } }
using System; namespace StrangerData.Utils { internal static class RandomValues { public static object ForColumn(TableColumnInfo columnInfo) { switch (columnInfo.ColumnType) { case ColumnType.String: // generates a random string return Any.String(columnInfo.MaxLength); case ColumnType.Int: // generates a random integer long maxValue = (int)Math.Pow(10, columnInfo.Precision - 1); if (maxValue > int.MaxValue) { return Any.Long(1, maxValue); } return Any.Int(1, (int)maxValue); case ColumnType.Decimal: // generates a random decimal return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Double: // generates a random double return Any.Double(columnInfo.Precision, columnInfo.Scale); case ColumnType.Long: // generates a random long return Any.Long(1, (int)Math.Pow(10, columnInfo.Precision - 1)); case ColumnType.Boolean: // generates a random boolean return Any.Boolean(); case ColumnType.Guid: // generates a random guid return Guid.NewGuid(); case ColumnType.Date: // generates a random date return Any.DateTime().Date; case ColumnType.Datetime: // generates a random DateTime return Any.DateTime(); default: return null; } } } }
Fix shell-completion.yml to exclude unlisted targets for invocation
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using Nuke.Common.IO; namespace Nuke.Common.Execution { [AttributeUsage(AttributeTargets.Class)] internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo { public void OnBeforeLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { var completionItems = new SortedDictionary<string, string[]>(); var targetNames = build.ExecutableTargets.Select(x => x.Name).OrderBy(x => x).ToList(); completionItems[Constants.InvokedTargetsParameterName] = targetNames.ToArray(); completionItems[Constants.SkippedTargetsParameterName] = targetNames.ToArray(); var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false); foreach (var parameter in parameters) { var parameterName = ParameterService.GetParameterMemberName(parameter); if (completionItems.ContainsKey(parameterName)) continue; var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text); completionItems[parameterName] = subItems?.ToArray(); } SerializationTasks.YamlSerializeToFile(completionItems, Constants.GetCompletionFile(NukeBuild.RootDirectory)); if (EnvironmentInfo.GetParameter<bool>(Constants.CompletionParameterName)) Environment.Exit(exitCode: 0); } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using Nuke.Common.IO; using static Nuke.Common.Constants; namespace Nuke.Common.Execution { [AttributeUsage(AttributeTargets.Class)] internal class HandleShellCompletionAttribute : Attribute, IOnBeforeLogo { public void OnBeforeLogo( NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { var completionItems = new SortedDictionary<string, string[]>(); var targets = build.ExecutableTargets.OrderBy(x => x.Name).ToList(); completionItems[InvokedTargetsParameterName] = targets.Where(x => x.Listed).Select(x => x.Name).ToArray(); completionItems[SkippedTargetsParameterName] = targets.Select(x => x.Name).ToArray(); var parameters = InjectionUtility.GetParameterMembers(build.GetType(), includeUnlisted: false); foreach (var parameter in parameters) { var parameterName = ParameterService.GetParameterMemberName(parameter); if (completionItems.ContainsKey(parameterName)) continue; var subItems = ParameterService.GetParameterValueSet(parameter, build)?.Select(x => x.Text); completionItems[parameterName] = subItems?.ToArray(); } SerializationTasks.YamlSerializeToFile(completionItems, GetCompletionFile(NukeBuild.RootDirectory)); if (EnvironmentInfo.GetParameter<bool>(CompletionParameterName)) Environment.Exit(exitCode: 0); } } }
Update Tester class implementation due to the recent changes in Tester implementation
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tracer; namespace Tester { class SingleThreadTest : ITest { private ITracer tracer = new Tracer.Tracer(); public void Run() { tracer.StartTrace(); RunCycle(204800000); tracer.StopTrace(); TraceResult result = tracer.GetTraceResult(); result.PrintToConsole(); } private void RunCycle(int repeatAmount) { ITracer tracer = new Tracer.Tracer(); tracer.StartTrace(); for (int i = 0; i < repeatAmount; i++) { int a = 1; a += i; } tracer.StopTrace(); TraceResult result = tracer.GetTraceResult(); result.PrintToConsole(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tracer; using System.Threading; namespace Tester { class SingleThreadTest : ITest { private ITracer tracer = new Tracer.Tracer(); public void Run() { tracer.StartTrace(); Thread.Sleep(500); RunCycle(500); tracer.StopTrace(); PrintTestResults(); } private void RunCycle(int sleepTime) { tracer.StartTrace(); Thread.Sleep(sleepTime); tracer.StopTrace(); } private void PrintTestResults() { var traceResult = tracer.GetTraceResult(); foreach (TraceResultItem analyzedItem in traceResult) { analyzedItem.PrintToConsole(); } } } }
Update fixture path for specs
using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Taxjar.Tests { public class TaxjarFixture { public static string GetJSON(string fixturePath) { using (StreamReader file = File.OpenText(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "../../../", "Fixtures", fixturePath))) using (JsonTextReader reader = new JsonTextReader(file)) { JObject response = (JObject)JToken.ReadFrom(reader); var resString = response.ToString(Formatting.None).Replace(@"\", ""); return response.ToString(Formatting.None).Replace(@"\", ""); } } } }
using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Taxjar.Tests { public class TaxjarFixture { public static string GetJSON(string fixturePath) { using (StreamReader file = File.OpenText(Path.Combine("../../../", "Fixtures", fixturePath))) using (JsonTextReader reader = new JsonTextReader(file)) { JObject response = (JObject)JToken.ReadFrom(reader); var resString = response.ToString(Formatting.None).Replace(@"\", ""); return response.ToString(Formatting.None).Replace(@"\", ""); } } } }
Clean up unused lat/long coordinates in language tests.
using System.Threading.Tasks; namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; private const double MumbaiLatitude = 18.975; private const double MumbaiLongitude = 72.825833; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } }
using System.Threading.Tasks; namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async Task UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } }
Fix stackoverflow error caused by navigation property in Session model
using Microsoft.Extensions.DependencyInjection; using ISTS.Application.Rooms; using ISTS.Application.Studios; using ISTS.Domain.Rooms; using ISTS.Domain.Studios; using ISTS.Infrastructure.Repository; namespace ISTS.Api { public static class DependencyInjectionConfiguration { public static void Configure(IServiceCollection services) { services.AddSingleton<IStudioRepository, StudioRepository>(); services.AddSingleton<IRoomRepository, RoomRepository>(); services.AddSingleton<IStudioService, StudioService>(); services.AddSingleton<IRoomService, RoomService>(); } } }
using Microsoft.Extensions.DependencyInjection; using ISTS.Application.Rooms; using ISTS.Application.Schedules; using ISTS.Application.Studios; using ISTS.Domain.Rooms; using ISTS.Domain.Schedules; using ISTS.Domain.Studios; using ISTS.Infrastructure.Repository; namespace ISTS.Api { public static class DependencyInjectionConfiguration { public static void Configure(IServiceCollection services) { services.AddSingleton<ISessionScheduleValidator, SessionScheduleValidator>(); services.AddSingleton<IStudioRepository, StudioRepository>(); services.AddSingleton<IRoomRepository, RoomRepository>(); services.AddSingleton<IStudioService, StudioService>(); services.AddSingleton<IRoomService, RoomService>(); } } }
Simplify component factory with generics
using UnityEditor; using UnityEngine; namespace Alensia.Core.UI { public static class ComponentFactory { [MenuItem("GameObject/UI/Alensia/Button", false, 10)] public static Button CreateButton(MenuCommand command) { var button = Button.CreateInstance(); GameObjectUtility.SetParentAndAlign(button.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(button, "Create " + button.name); Selection.activeObject = button; return button; } [MenuItem("GameObject/UI/Alensia/Label", false, 10)] public static Label CreateLabel(MenuCommand command) { var label = Label.CreateInstance(); GameObjectUtility.SetParentAndAlign(label.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(label, "Create " + label.name); Selection.activeObject = label; return label; } [MenuItem("GameObject/UI/Alensia/Panel", false, 10)] public static Panel CreatePanel(MenuCommand command) { var panel = Panel.CreateInstance(); GameObjectUtility.SetParentAndAlign(panel.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(panel, "Create " + panel.name); Selection.activeObject = panel; return panel; } } }
using System; using UnityEditor; using UnityEngine; namespace Alensia.Core.UI { public static class ComponentFactory { [MenuItem("GameObject/UI/Alensia/Button", false, 10)] public static Button CreateButton(MenuCommand command) => CreateComponent(command, Button.CreateInstance); [MenuItem("GameObject/UI/Alensia/Label", false, 10)] public static Label CreateLabel(MenuCommand command) => CreateComponent(command, Label.CreateInstance); [MenuItem("GameObject/UI/Alensia/Panel", false, 10)] public static Panel CreatePanel(MenuCommand command) => CreateComponent(command, Panel.CreateInstance); private static T CreateComponent<T>( MenuCommand command, Func<T> factory) where T : UIComponent { var component = factory.Invoke(); GameObjectUtility.SetParentAndAlign( component.gameObject, command.context as GameObject); Undo.RegisterCreatedObjectUndo(component, "Create " + component.name); Selection.activeObject = component; return component; } } }
Modify the enode project assembly.cs file
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ENode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdf470ac-90a3-47cf-9032-a3f7a298a688")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
Remove the non-active button from the jumbotron.
<section class="container"> <div id="our-jumbotron" class="jumbotron"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around and check out our...</p> <p><a class="btn btn-primary btn-lg" role="button">... showtimes.</a></p> </div> </section>
<section class="container"> <div id="our-jumbotron" class="jumbotron"> <h1>Welcome!</h1> <p>We are Sweet Water Revolver. This is our website. Please look around.</p> </div> </section>
Revert "Newline at end of file missing, added."
 // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.PowerShell.Common; namespace Google.PowerShell.Dns { /// <summary> /// Base class for Google DNS-based cmdlets. /// </summary> public abstract class GcdCmdlet : GCloudCmdlet { // The Service for the Google DNS API public DnsService Service { get; } protected GcdCmdlet() : this(null) { } protected GcdCmdlet(DnsService service) { Service = service ?? new DnsService(GetBaseClientServiceInitializer()); } } }
 // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Dns.v1; using Google.PowerShell.Common; namespace Google.PowerShell.Dns { /// <summary> /// Base class for Google DNS-based cmdlets. /// </summary> public abstract class GcdCmdlet : GCloudCmdlet { // The Service for the Google DNS API public DnsService Service { get; } protected GcdCmdlet() : this(null) { } protected GcdCmdlet(DnsService service) { Service = service ?? new DnsService(GetBaseClientServiceInitializer()); } } }
Fix build error in VS2015
// Copyright 2015-2017 Directive Games Limited - All Rights Reserved using UnrealBuildTool; public class RapidJson : ModuleRules { public RapidJson(TargetInfo Target) { bFasterWithoutUnity = true; PCHUsage = PCHUsageMode.NoSharedPCHs; PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { // ... add other public dependencies that you statically link with here ... "Core", "HTTP", } ); PrivateDependencyModuleNames.AddRange( new string[] { // ... add private dependencies that you statically link with here ... } ); } }
// Copyright 2015-2017 Directive Games Limited - All Rights Reserved using UnrealBuildTool; public class RapidJson : ModuleRules { public RapidJson(TargetInfo Target) { bFasterWithoutUnity = true; PCHUsage = PCHUsageMode.NoSharedPCHs; PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { // ... add other public dependencies that you statically link with here ... "Core", "HTTP", } ); PrivateDependencyModuleNames.AddRange( new string[] { // ... add private dependencies that you statically link with here ... } ); if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.PS4)) { Definitions.Add("RAPIDJSON_HAS_CXX11_RVALUE_REFS=1"); } } }
Add extension method for working out if an entry is deleted or not.
using KeePassLib; using System; using System.Linq; namespace HaveIBeenPwned { public static class PwEntryExtension { public static DateTime GetPasswordLastModified(this PwEntry entry) { if(entry.History != null && entry.History.Any()) { var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime); foreach(var historyEntry in sortedEntries) { if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString()) { return historyEntry.LastModificationTime; } } return sortedEntries.Last().LastModificationTime; } return entry.LastModificationTime; } } }
using KeePass.Plugins; using KeePassLib; using System; using System.Linq; namespace HaveIBeenPwned { public static class PwEntryExtension { public static DateTime GetPasswordLastModified(this PwEntry entry) { if(entry.History != null && entry.History.Any()) { var sortedEntries = entry.History.OrderByDescending(h => h.LastModificationTime); foreach(var historyEntry in sortedEntries) { if(entry.Strings.GetSafe(PwDefs.PasswordField).ReadString() != historyEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString()) { return historyEntry.LastModificationTime; } } return sortedEntries.Last().LastModificationTime; } return entry.LastModificationTime; } public static bool IsDeleted(this PwEntry entry, IPluginHost pluginHost) { return entry.ParentGroup.Uuid.CompareTo(pluginHost.Database.RecycleBinUuid) == 0; } } }
Fix script location via AppDomain base dir for web applications
using System; using System.IO; using System.Reflection; using NServiceBus; using NServiceBus.Settings; static class ScriptLocation { public static string FindScriptDirectory(ReadOnlySettings settings) { var currentDirectory = GetCurrentDirectory(settings); return Path.Combine(currentDirectory, "NServiceBus.Persistence.Sql", settings.GetSqlDialect().Name); } static string GetCurrentDirectory(ReadOnlySettings settings) { if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory)) { return scriptDirectory; } var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { return AppDomain.CurrentDomain.BaseDirectory; } var codeBase = entryAssembly.CodeBase; return Directory.GetParent(new Uri(codeBase).LocalPath).FullName; } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }
using System; using System.IO; using System.Reflection; using NServiceBus; using NServiceBus.Settings; static class ScriptLocation { const string ScriptFolder = "NServiceBus.Persistence.Sql"; public static string FindScriptDirectory(ReadOnlySettings settings) { var currentDirectory = GetCurrentDirectory(settings); return Path.Combine(currentDirectory, ScriptFolder, settings.GetSqlDialect().Name); } static string GetCurrentDirectory(ReadOnlySettings settings) { if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory)) { return scriptDirectory; } var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { var baseDir = AppDomain.CurrentDomain.BaseDirectory; var scriptDir = Path.Combine(baseDir, ScriptFolder); //if the app domain base dir contains the scripts folder, return it. Otherwise add "bin" to the base dir so that web apps work correctly if (Directory.Exists(scriptDir)) { return baseDir; } return Path.Combine(baseDir, "bin"); } var codeBase = entryAssembly.CodeBase; return Directory.GetParent(new Uri(codeBase).LocalPath).FullName; } public static void ValidateScriptExists(string createScript) { if (!File.Exists(createScript)) { throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint or NServiceBus.Persistence.Sql.MsBuild nuget was not included in the project."); } } }
Implement extracting the property name
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rhaeo.Mvvm { public class ObservableObject { } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ObservableObject.cs" company="Rhaeo"> // Licenced under the MIT licence. // </copyright> // <summary> // Defines the ObservableObject type. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Linq.Expressions; namespace Rhaeo.Mvvm { /// <summary> /// Serves as a back class for object instances obserable through the <see cref="INotifyPropertyChanged"/> interface. /// </summary> public class ObservableObject : INotifyPropertyChanged { #region Events /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Methods /// <summary> /// Raises the <see cref="PropertyChanged"/> event with a property name extracted from the property expression. /// </summary> /// <typeparam name="TViewModel"> /// The view model type. /// </typeparam> /// <typeparam name="TValue"> /// The property value type. /// </typeparam> /// <param name="propertyExpression"> /// The property expression. /// </param> protected void RaisePropertyChanged<TViewModel, TValue>(Expression<Func<TViewModel, TValue>> propertyExpression) where TViewModel : ObservableObject { var propertyName = (propertyExpression.Body as MemberExpression).Member.Name; var propertyChangedHandler = this.PropertyChanged; if (propertyChangedHandler != null) { propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }
Build and print the trie
// https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/ // // Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words // using System; using System.Collections.Generic; using System.IO; using System.Linq; class Trie { private class Node { internal Dictionary<char, Node> Next = new Dictionary<char, Node>(); bool IsWord = false; } } class Program { static void Main() { Trie trie = new Trie(); using (StreamReader reader = new StreamReader("/usr/share/dict/words")) { String line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
// https://www.reddit.com/r/dailyprogrammer/comments/3n55f3/20150930_challenge_234_intermediate_red_squiggles/ // // Your challenge today is to implement a real time spell checker and indicate where you would throw the red squiggle. For your dictionary use /usr/share/dict/words // using System; using System.Collections.Generic; using System.IO; using System.Linq; class Trie { private class Node { internal Dictionary<char, Node> Next = new Dictionary<char, Node>(); internal bool IsWord = false; public override String ToString() { return String.Format("[Node.IsWord:{0} {1}]", IsWord, String.Join(", ", Next.Select(x => String.Format("{0} => {1}", x.Key, x.Value.ToString())))); } } private readonly Node Root = new Node(); public void Add(String s) { Node current = Root; for (int i = 0; i < s.Length; i++) { Node next; if (!current.Next.TryGetValue(s[i], out next)) { next = new Node(); current.Next[s[i]] = next; } next.IsWord = i == s.Length - 1; current = next; } } public override String ToString() { return Root.ToString(); } } class Program { static void Main() { Trie trie = new Trie(); using (StreamReader reader = new StreamReader("/usr/share/dict/words")) { String line; while ((line = reader.ReadLine()) != null) { trie.Add(line); } } Console.WriteLine(trie); } }
Allow rotating the screen without crashing by overriding the Configuration changes.
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; namespace SampleGame.Android { [Activity(Label = "SampleGame", MainLauncher = true, ScreenOrientation = ScreenOrientation.Landscape, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new SampleGameView(this)); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Content.PM; using Android.Views; using System; using Android.Runtime; using Android.Content.Res; namespace SampleGame.Android { [Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")] public class MainActivity : Activity { private SampleGameView sampleGameView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(sampleGameView = new SampleGameView(this)); } } }
Increment version before creating release (0.2.5).
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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.4")] [assembly: AssemblyFileVersion("0.2.4")]
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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.5")] [assembly: AssemblyFileVersion("0.2.5")]
Write the autolink's URL so we can see the autolink.
// Copyright (c) 2016-2017 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using System; using System.Windows.Documents; using Markdig.Annotations; using Markdig.Syntax.Inlines; using Markdig.Wpf; namespace Markdig.Renderers.Wpf.Inlines { /// <summary> /// A WPF renderer for a <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline> { /// <inheritdoc/> protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link) { var url = link.Url; if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { url = "#"; } var hyperlink = new Hyperlink { Command = Commands.Hyperlink, CommandParameter = url, NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute), ToolTip = url, }; renderer.WriteInline(hyperlink); } } }
// Copyright (c) 2016-2017 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using System; using System.Windows.Documents; using Markdig.Annotations; using Markdig.Syntax.Inlines; using Markdig.Wpf; namespace Markdig.Renderers.Wpf.Inlines { /// <summary> /// A WPF renderer for a <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Wpf.WpfObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : WpfObjectRenderer<AutolinkInline> { /// <inheritdoc/> protected override void Write([NotNull] WpfRenderer renderer, [NotNull] AutolinkInline link) { var url = link.Url; if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { url = "#"; } var hyperlink = new Hyperlink { Command = Commands.Hyperlink, CommandParameter = url, NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute), ToolTip = url, }; renderer.Push(hyperlink); renderer.WriteText(link.Url); renderer.Pop(); } } }
Use MvcJsonOptions json serializer formatting when generating swagger.json
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Swashbuckle.Swagger.Application { public class SwaggerSerializerFactory { internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions) { // TODO: Should this handle case where mvcJsonOptions.Value == null? return new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings) }; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Swashbuckle.Swagger.Application { public class SwaggerSerializerFactory { internal static JsonSerializer Create(IOptions<MvcJsonOptions> mvcJsonOptions) { // TODO: Should this handle case where mvcJsonOptions.Value == null? return new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, Formatting = mvcJsonOptions.Value.SerializerSettings.Formatting, ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings) }; } } }
Update View convention to recognize MainWindow
using Conventional.Conventions; namespace Pirac.Conventions { internal class ViewConvention : Convention { public ViewConvention() { Must.HaveNameEndWith("View").BeAClass(); Should.BeAConcreteClass(); BaseName = t => t.Name.Substring(0, t.Name.Length - 4); Variants.HaveBaseNameAndEndWith("View"); } } }
using System; using Conventional.Conventions; namespace Pirac.Conventions { internal class ViewConvention : Convention { public ViewConvention() { Must.Pass(t => t.IsClass && (t.Name.EndsWith("View") || t.Name == "MainWindow"), "Name ends with View or is named MainWindow"); Should.BeAConcreteClass(); BaseName = t => t.Name == "MainWindow" ? t.Name : t.Name.Substring(0, t.Name.Length - 4); Variants.Add(new DelegateBaseFilter((t, b) => { if (t.Name == "MainWindow" && b == "MainWindow") return true; return t.Name == b + "View"; })); } class DelegateBaseFilter : IBaseFilter { private readonly Func<Type, string, bool> predicate; public DelegateBaseFilter(Func<Type, string, bool> predicate) { this.predicate = predicate; } public bool Matches(Type t, string baseName) { return predicate(t, baseName); } } } }
Install NuGet as a tool
using System; using System.Collections.Generic; using System.IO; using Cake.Core; using Cake.Core.Configuration; using Cake.Frosting; using Cake.NuGet; public class Program : IFrostingStartup { public static int Main(string[] args) { // Create the host. var host = new CakeHostBuilder() .WithArguments(args) .UseStartup<Program>() .Build(); // Run the host. return host.Run(); } public void Configure(ICakeServices services) { services.UseContext<Context>(); services.UseLifetime<Lifetime>(); services.UseWorkingDirectory(".."); // from https://github.com/cake-build/cake/discussions/2931 var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>())); module.Register(services); services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1")); services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0")); services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0")); } }
using System; using System.Collections.Generic; using System.IO; using Cake.Core; using Cake.Core.Configuration; using Cake.Frosting; using Cake.NuGet; public class Program : IFrostingStartup { public static int Main(string[] args) { // Create the host. var host = new CakeHostBuilder() .WithArguments(args) .UseStartup<Program>() .Build(); // Run the host. return host.Run(); } public void Configure(ICakeServices services) { services.UseContext<Context>(); services.UseLifetime<Lifetime>(); services.UseWorkingDirectory(".."); // from https://github.com/cake-build/cake/discussions/2931 var module = new NuGetModule(new CakeConfiguration(new Dictionary<string, string>())); module.Register(services); services.UseTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1")); services.UseTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0")); services.UseTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0")); services.UseTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0")); } }
Move DataFolder config get to static member initializer
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return Config.Get("data-folder", @"../../../Data/"); } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/"); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
Use a path for storage that doesn't include version and company name
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Kyru.Core { class Config { internal readonly string storeDirectory; internal Config() { storeDirectory = Path.Combine(System.Windows.Forms.Application.UserAppDataPath); } } }
using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kyru", "objects"); } } }
Update the static content module to fit the new API.
using System; using System.IO; using Mango; // // This the default StaticContentModule that comes with all Mango apps // if you do not wish to serve any static content with Mango you can // remove its route handler from <YourApp>.cs's constructor and delete // this file. // // All Content placed on the Content/ folder should be handled by this // module. // namespace $APPNAME { public class StaticContentModule : MangoModule { public StaticContentModule () { Get ("*", Content); } public static void Content (MangoContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; } } }
using System; using System.IO; using Mango; // // This the default StaticContentModule that comes with all Mango apps // if you do not wish to serve any static content with Mango you can // remove its route handler from <YourApp>.cs's constructor and delete // this file. // // All Content placed on the Content/ folder should be handled by this // module. // namespace AppNameFoo { public class StaticContentModule : MangoModule { public StaticContentModule () { Get ("*", Content); } public static void Content (IMangoContext ctx) { string path = ctx.Request.LocalPath; if (path.StartsWith ("/")) path = path.Substring (1); if (File.Exists (path)) { ctx.Response.SendFile (path); } else ctx.Response.StatusCode = 404; } } }
Add url to get unicorns
using Nancy; using Owin; namespace Bbl.KnockoutJs { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); } } public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => View["index"]; } } }
using System.IO; using System.Linq; using System.Web.Hosting; using Nancy; using Owin; namespace Bbl.KnockoutJs { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); } } public class IndexModule : NancyModule { private const string UnicornsPath = "/Content/Unicorn/"; public IndexModule() { Get["/"] = parameters => View["index"]; Get["/api/unicorns"] = parameters => { var imagesDirectory = HostingEnvironment.MapPath("~" + UnicornsPath); return new DirectoryInfo(imagesDirectory) .EnumerateFiles() .Select(ConvertToDto); }; } private dynamic ConvertToDto(FileInfo file) { var name = Path.GetFileNameWithoutExtension(file.Name); return new { Key = name, ImagePath = UnicornsPath + file.Name, Name = name.Replace('_', ' '), Keywords = name.Split('_'), CreationDate = file.CreationTime }; } } }
Fix case when project directory already exists
using System; using System.Diagnostics; using System.IO; namespace dotnet_new2 { public class ProjectCreator { public bool CreateProject(string name, string path, Template template) { Directory.CreateDirectory(path); foreach (var file in template.Files) { var dest = Path.Combine(path, file.DestPath); File.Copy(file.SourcePath, dest); ProcessFile(dest, name); } Console.WriteLine(); Console.WriteLine($"Created \"{name}\" in {path}"); return true; } private void ProcessFile(string destPath, string name) { // TODO: Make this good var contents = File.ReadAllText(destPath); File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name)); } } }
using System; using System.Diagnostics; using System.IO; namespace dotnet_new2 { public class ProjectCreator { public bool CreateProject(string name, string path, Template template) { Directory.CreateDirectory(path); if (Directory.GetFileSystemEntries(path).Length > 0) { // Files already exist in the directory Console.WriteLine($"Directory {path} already contains files. Please specify a different project name."); return false; } foreach (var file in template.Files) { var dest = Path.Combine(path, file.DestPath); File.Copy(file.SourcePath, dest); ProcessFile(dest, name); } Console.WriteLine(); Console.WriteLine($"Created \"{name}\" in {path}"); Console.WriteLine(); return true; } private void ProcessFile(string destPath, string name) { // TODO: Make this good var contents = File.ReadAllText(destPath); File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name)); } } }
Throw all dispatcher exceptions on the non-service build.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace SteamIrcBot { class ServiceDispatcher { static ServiceDispatcher _instance = new ServiceDispatcher(); public static ServiceDispatcher Instance { get { return _instance; } } Task dispatcher; CancellationTokenSource cancelToken; ServiceDispatcher() { cancelToken = new CancellationTokenSource(); dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning ); } void ServiceTick() { while ( true ) { if ( cancelToken.IsCancellationRequested ) break; Steam.Instance.Tick(); IRC.Instance.Tick(); RSS.Instance.Tick(); } } public void Start() { dispatcher.Start(); } public void Stop() { cancelToken.Cancel(); } public void Wait() { try { dispatcher.Wait(); } catch ( AggregateException ) { // we'll ignore any cancelled/failed tasks } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace SteamIrcBot { class ServiceDispatcher { static ServiceDispatcher _instance = new ServiceDispatcher(); public static ServiceDispatcher Instance { get { return _instance; } } Task dispatcher; CancellationTokenSource cancelToken; ServiceDispatcher() { cancelToken = new CancellationTokenSource(); dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning ); } void ServiceTick() { while ( true ) { if ( cancelToken.IsCancellationRequested ) break; Steam.Instance.Tick(); IRC.Instance.Tick(); RSS.Instance.Tick(); } } public void Start() { dispatcher.Start(); } public void Stop() { cancelToken.Cancel(); } public void Wait() { dispatcher.Wait(); } } }
Fix the XML docs generic class references
using System; using System.Collections.Generic; using System.Linq; namespace Monacs.Core.Unit { ///<summary> /// Extensions for <see cref="Result<Unit>" /> type. ///</summary> public static class Result { ///<summary> /// Creates successful <see cref="Result<Unit>" />. ///</summary> public static Result<Unit> Ok() => Core.Result.Ok(Unit.Default); ///<summary> /// Creates failed <see cref="Result<Unit>" /> with provided error details. ///</summary> public static Result<Unit> Error(ErrorDetails error) => Core.Result.Error<Unit>(error); ///<summary> /// Rejects the value of the <see cref="Result<T>" /> and returns <see cref="Result<Unit>" /> instead. /// If the input <see cref="Result<T>" /> is Error then the error details are preserved. ///</summary> public static Result<Unit> Ignore<T>(this Result<T> result) => result.Map(_ => Unit.Default); } }
using System; using System.Collections.Generic; using System.Linq; namespace Monacs.Core.Unit { ///<summary> /// Extensions for <see cref="Result{Unit}" /> type. ///</summary> public static class Result { ///<summary> /// Creates successful <see cref="Result{Unit}" />. ///</summary> public static Result<Unit> Ok() => Core.Result.Ok(Unit.Default); ///<summary> /// Creates failed <see cref="Result{Unit}" /> with provided error details. ///</summary> public static Result<Unit> Error(ErrorDetails error) => Core.Result.Error<Unit>(error); ///<summary> /// Rejects the value of the <see cref="Result{T}" /> and returns <see cref="Result{Unit}" /> instead. /// If the input <see cref="Result{T}" /> is Error then the error details are preserved. ///</summary> public static Result<Unit> Ignore<T>(this Result<T> result) => result.Map(_ => Unit.Default); } }
Set assembly culture to neutral
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ProviderModel")] [assembly: AssemblyDescription("An improvment over the bundled .NET provider model")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Enrique Alejandro Allegretta")] [assembly: AssemblyProduct("ProviderModel")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("en-US")] [assembly: ComVisible(false)] [assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ProviderModel")] [assembly: AssemblyDescription("An improvment over the bundled .NET provider model")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Enrique Alejandro Allegretta")] [assembly: AssemblyProduct("ProviderModel")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")] [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.1")] [assembly: AssemblyInformationalVersion("1.0.1")]
Change port for new RabbitMQ-MQTT server
using SOVND.Lib; using System.IO; namespace SOVND.Server { public class ServerMqttSettings : IMQTTSettings { public string Broker { get { return "104.131.87.42"; } } public int Port { get { return 8883; } } public string Username { get { return File.ReadAllText("username.key"); } } public string Password { get { return File.ReadAllText("password.key"); } } } }
using SOVND.Lib; using System.IO; namespace SOVND.Server { public class ServerMqttSettings : IMQTTSettings { public string Broker { get { return "104.131.87.42"; } } public int Port { get { return 2883; } } public string Username { get { return File.ReadAllText("username.key"); } } public string Password { get { return File.ReadAllText("password.key"); } } } }
Truncate stream when writing sidecar XMP files.
using System; using System.IO; using GLib; using Hyena; using TagLib.Image; using TagLib.Xmp; namespace FSpot.Utils { public static class SidecarXmpExtensions { /// <summary> /// Parses the XMP file identified by resource and replaces the XMP /// tag of file by the parsed data. /// </summary> public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { string xmp; using (var stream = resource.ReadStream) { using (var reader = new StreamReader (stream)) { xmp = reader.ReadToEnd (); } } var tag = new XmpTag (xmp); var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag; xmp_tag.ReplaceFrom (tag); } public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag; if (xmp_tag == null) return; var xmp = xmp_tag.Render (); using (var stream = resource.WriteStream) { using (var writer = new StreamWriter (stream)) { writer.Write (xmp); } resource.CloseStream (stream); } } } }
using System; using System.IO; using GLib; using Hyena; using TagLib.Image; using TagLib.Xmp; namespace FSpot.Utils { public static class SidecarXmpExtensions { /// <summary> /// Parses the XMP file identified by resource and replaces the XMP /// tag of file by the parsed data. /// </summary> public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { string xmp; using (var stream = resource.ReadStream) { using (var reader = new StreamReader (stream)) { xmp = reader.ReadToEnd (); } } var tag = new XmpTag (xmp); var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag; xmp_tag.ReplaceFrom (tag); } public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource) { var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag; if (xmp_tag == null) return; var xmp = xmp_tag.Render (); using (var stream = resource.WriteStream) { stream.SetLength (0); using (var writer = new StreamWriter (stream)) { writer.Write (xmp); } resource.CloseStream (stream); } } } }
Remove exit step (needs login to show properly)
// 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 System.Collections.Generic; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Multiplayer), typeof(LoungeSubScreen), typeof(FilterControl) }; public TestCaseMultiScreen() { Multiplayer multi = new Multiplayer(); AddStep(@"show", () => LoadScreen(multi)); AddUntilStep(() => multi.IsCurrentScreen(), "wait until current"); AddStep(@"exit", multi.Exit); } } }
// 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 System.Collections.Generic; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Multiplayer), typeof(LoungeSubScreen), typeof(FilterControl) }; public TestCaseMultiScreen() { Multiplayer multi = new Multiplayer(); AddStep(@"show", () => LoadScreen(multi)); } } }
Replace StackTrace with CallerMemberName attribute
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace DocumentFormat.OpenXml.Tests { public class TestContext { public TestContext(string currentTest) { this.TestName = currentTest; this.FullyQualifiedTestClassName = currentTest; } public string TestName { get; set; } public string FullyQualifiedTestClassName { get; set; } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetCurrentMethod() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace DocumentFormat.OpenXml.Tests { public class TestContext { public TestContext(string currentTest) { this.TestName = currentTest; this.FullyQualifiedTestClassName = currentTest; } public string TestName { get; set; } public string FullyQualifiedTestClassName { get; set; } public static string GetCurrentMethod([CallerMemberName]string name = null) => name; } }
Stop double call of Directory.GetCurrentDirectory on startup, as 20% slower on linux
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseWebRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }
Refactor Add Integers Operation to use GetValues and CloneWithValues
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { Tensor<int> result = new Tensor<int>(); result.SetValue(tensor1.GetValue() + tensor2.GetValue()); return result; return result; } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { int[] values1 = tensor1.GetValues(); int l = values1.Length; int[] values2 = tensor2.GetValues(); int[] newvalues = new int[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] + values2[k]; return tensor1.CloneWithNewValues(newvalues); } } }
Fix normalizing a vector results in a zero vector
namespace SharpMath.Geometry { public static class VectorExtensions { public static T Negate<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = -vector[i]; return resultVector; } /// <summary> /// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>. /// </summary> /// <returns>The normalized <see cref="Vector"/>.</returns> public static T Normalize<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] /= vector.Magnitude; return resultVector; } } }
using SharpMath.Geometry.Exceptions; namespace SharpMath.Geometry { public static class VectorExtensions { public static T Negate<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); if (vector.Dimension != resultVector.Dimension) throw new DimensionException("The dimensions of the vectors do not equal each other."); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = -vector[i]; return resultVector; } /// <summary> /// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>. /// </summary> /// <returns>The normalized <see cref="Vector"/>.</returns> public static T Normalize<T>(this Vector vector) where T : Vector, new() { var resultVector = new T(); if (vector.Dimension != resultVector.Dimension) throw new DimensionException("The dimensions of the vectors do not equal each other."); for (uint i = 0; i < vector.Dimension; ++i) resultVector[i] = vector[i] / vector.Magnitude; return resultVector; } } }
Add test for Signature equality
// Copyright 2009 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NUnit.Framework; using NDesk.DBus; namespace NDesk.DBus.Tests { [TestFixture] public class SignatureTest { [Test] public void Parse () { string sigText = "as"; Signature sig = new Signature (sigText); Assert.IsTrue (sig.IsArray); Assert.IsFalse (sig.IsDict); Assert.IsFalse (sig.IsPrimitive); } } }
// Copyright 2009 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NUnit.Framework; using NDesk.DBus; namespace NDesk.DBus.Tests { [TestFixture] public class SignatureTest { [Test] public void Parse () { string sigText = "as"; Signature sig = new Signature (sigText); Assert.IsTrue (sig.IsArray); Assert.IsFalse (sig.IsDict); Assert.IsFalse (sig.IsPrimitive); } [Test] public void Equality () { string sigText = "as"; Signature a = new Signature (sigText); Signature b = new Signature (sigText); Assert.IsTrue (a == b); } } }
Add layout to guidelines page.
<h2>What is dotnet signals?</h2> .NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and knowledge as voted by the community while avoiding the clutter found in traditional sources. <h2>Posts</h2> <ul> <li>Try to keep the title of the post the same as the article except to add information on vague titles,</li> <li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li> <li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li> <li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li> </ul> <h2>Comments</h2> <ul> <li>Do not spam,</li> <li>Avoid Me toos, thanks, "awesome post" comments,</li> <li>Be professional, be polite.</li> </ul>
@{ ViewData["Title"] = "Guidelines"; Layout = "~/Views/Shared/_Layout.cshtml"; } <section> <h2>What is dotnet signals?</h2> .NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and knowledge as voted by the community while avoiding the clutter found in traditional sources. <h2>Posts</h2> <ul> <li>Try to keep the title of the post the same as the article except to add information on vague titles,</li> <li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li> <li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li> <li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li> </ul> <h2>Comments</h2> <ul> <li>Do not spam,</li> <li>Avoid Me toos, thanks, "awesome post" comments,</li> <li>Be professional, be polite.</li> </ul> </section>
Add a couple of friend assemblies
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")]
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
Add explicit usage via attribute
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using osu.Game.Online.Chat; namespace osu.Game.Online.API.Requests { public class GetUpdatesResponse { public List<Channel> Presence; public List<Message> Messages; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Online.Chat; namespace osu.Game.Online.API.Requests { public class GetUpdatesResponse { [JsonProperty] public List<Channel> Presence; [JsonProperty] public List<Message> Messages; } }
Make mainObject an instance field
using System; using ColossalFramework; using ColossalFramework.Plugins; using ICities; using ModTools.Utils; using UnityEngine; namespace ModTools { public sealed class ModToolsMod : IUserMod { public const string ModToolsName = "ModTools"; public static GameObject MainWindowObject; private static GameObject mainObject; public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly); public string Name => ModToolsName; public string Description => "Debugging toolkit for modders, version " + Version; public void OnEnabled() { try { if (MainWindowObject != null) { return; } CODebugBase<LogChannel>.verbose = true; CODebugBase<LogChannel>.EnableChannels(LogChannel.All); mainObject = new GameObject(ModToolsName); UnityEngine.Object.DontDestroyOnLoad(mainObject); MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow)); UnityEngine.Object.DontDestroyOnLoad(MainWindowObject); var modTools = MainWindowObject.AddComponent<MainWindow>(); modTools.Initialize(); } catch (Exception e) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message); } } public void OnDisabled() { if (MainWindowObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(MainWindowObject); MainWindowObject = null; } if (mainObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(mainObject); mainObject = null; } } } }
using System; using ColossalFramework; using ColossalFramework.Plugins; using ICities; using ModTools.Utils; using UnityEngine; namespace ModTools { public sealed class ModToolsMod : IUserMod { public const string ModToolsName = "ModTools"; public static GameObject MainWindowObject; private GameObject mainObject; public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly); public string Name => ModToolsName; public string Description => "Debugging toolkit for modders, version " + Version; public void OnEnabled() { try { if (MainWindowObject != null) { return; } CODebugBase<LogChannel>.verbose = true; CODebugBase<LogChannel>.EnableChannels(LogChannel.All); mainObject = new GameObject(ModToolsName); UnityEngine.Object.DontDestroyOnLoad(mainObject); MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow)); UnityEngine.Object.DontDestroyOnLoad(MainWindowObject); var modTools = MainWindowObject.AddComponent<MainWindow>(); modTools.Initialize(); } catch (Exception e) { DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message); } } public void OnDisabled() { if (MainWindowObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(MainWindowObject); MainWindowObject = null; } if (mainObject != null) { CODebugBase<LogChannel>.verbose = false; UnityEngine.Object.Destroy(mainObject); mainObject = null; } } } }
Change to use ScriptLinkCore.Objects namespace
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NTST.ScriptLinkService.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="fieldNumber"></param> /// <returns></returns> public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == fieldNumber) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ScriptLinkCore.Objects; namespace ScriptLinkCore { public partial class ScriptLink { /// <summary> /// Used set required fields /// </summary> /// <param name="optionObject"></param> /// <param name="fieldNumber"></param> /// <returns></returns> public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber) { OptionObject returnOptionObject = optionObject; Boolean updated = false; foreach (var form in returnOptionObject.Forms) { foreach (var currentField in form.CurrentRow.Fields) { if (currentField.FieldNumber == fieldNumber) { currentField.Required = "1"; updated = true; } } } if (updated == true) { foreach (var form in returnOptionObject.Forms) { form.CurrentRow.RowAction = "EDIT"; } return returnOptionObject; } else { return optionObject; } } } }
Send single sample of processor performance counter to the InfluxDB.Net.
using System; namespace InfluxDB.Net.Collector.Console { static class Program { private static InfluxDb _client; static void Main(string[] args) { if (args.Length != 3) { //url: http://128.199.43.107:8086 //username: root //Password: ????? throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database."); } var url = args[0]; var username = args[1]; var password = args[2]; _client = new InfluxDb(url, username, password); var pong = _client.PingAsync().Result; System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime); var version = _client.VersionAsync().Result; System.Console.WriteLine("Version: {0}", version); System.Console.WriteLine("Press any key to exit..."); System.Console.ReadKey(); } } }
using System; using System.Diagnostics; using InfluxDB.Net.Models; namespace InfluxDB.Net.Collector.Console { static class Program { private static InfluxDb _client; static void Main(string[] args) { if (args.Length != 3) { //url: http://128.199.43.107:8086 //username: root //Password: ????? throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database."); } var url = args[0]; var username = args[1]; var password = args[2]; _client = new InfluxDb(url, username, password); var pong = _client.PingAsync().Result; System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime); var version = _client.VersionAsync().Result; System.Console.WriteLine("Version: {0}", version); var processorCounter = GetPerformanceCounter(); System.Threading.Thread.Sleep(100); var result = RegisterCounterValue(processorCounter); System.Console.WriteLine(result.StatusCode); System.Console.WriteLine("Press enter to exit..."); System.Console.ReadKey(); } private static InfluxDbApiResponse RegisterCounterValue(PerformanceCounter processorCounter) { var data = processorCounter.NextValue(); System.Console.WriteLine("Processor value: {0}%", data); var serie = new Serie.Builder("Processor") .Columns("Total") .Values(data) .Build(); var result = _client.WriteAsync("QTest", TimeUnit.Milliseconds, serie); return result.Result; } private static PerformanceCounter GetPerformanceCounter() { var processorCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); processorCounter.NextValue(); return processorCounter; } } }
Fix quoting for Unity log file
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Tooling; namespace Nuke.Common.Tools.Unity { public partial class UnityBaseSettings { public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger; public string GetProcessToolPath() { return UnityTasks.GetToolPath(HubVersion); } public string GetLogFile() { // TODO SK return LogFile ?? NukeBuild.RootDirectory / "unity.log"; } } }
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Tooling; using Nuke.Common.Utilities; namespace Nuke.Common.Tools.Unity { public partial class UnityBaseSettings { public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger; public string GetProcessToolPath() { return UnityTasks.GetToolPath(HubVersion); } public string GetLogFile() { return (LogFile ?? NukeBuild.RootDirectory / "unity.log").DoubleQuoteIfNeeded(); } } }
Handle exiting if bot is destroyed by consuming resources.
using UnityEngine; using System.Collections; public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener { BulletGridGenerator currentLevel; public NanobotSchematic schematic; public int price; public string id; // Use this for initialization void Start() { currentLevel = FindObjectOfType<BulletGridGenerator>(); GameObject.FindObjectOfType<TimestepManager>().addListener(this); schematic = GameObject.Instantiate(schematic); } public void notifyTimestep() { currentLevel.getCellAt(gameObject.GetComponent<GridPositionComponent>().position).Cell.GetComponent<Cell>().Eat(1, false); for (int x = 0; x < schematic.getTransformation().Length; x++) { if (schematic.getTransformation()[x] != null) { for (int y = 0; y < schematic.getTransformation()[x].Length; y++) { if (schematic.getTransformation()[x][y] != null) { currentLevel.moveBotAnimated(gameObject.GetComponent<GridPositionComponent>().position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false); } } } } } }
using UnityEngine; using System.Collections; public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener { BulletGridGenerator currentLevel; public NanobotSchematic schematic; public int price; public string id; // Use this for initialization void Start() { currentLevel = FindObjectOfType<BulletGridGenerator>(); GameObject.FindObjectOfType<TimestepManager>().addListener(this); schematic = GameObject.Instantiate(schematic); } public void notifyTimestep() { GridPosition position = gameObject.GetComponent<GridPositionComponent>().position; BulletGridGenerator.GameCell cell = currentLevel.getCellAt(position); cell.Cell.GetComponent<Cell>().Eat(1, false); if (cell.Nanobot == null) { // TODO: Trigger animation for nanobot death. return; } for (int x = 0; x < schematic.getTransformation().Length; x++) { if (schematic.getTransformation()[x] != null) { for (int y = 0; y < schematic.getTransformation()[x].Length; y++) { if (schematic.getTransformation()[x][y] != null) { currentLevel.moveBotAnimated(position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false); } } } } } }
Change format on default logger formatter.
namespace SimpleLogger.Logging.Formatters { internal class DefaultLoggerFormatter : ILoggerFormatter { public string ApplyFormat(LogMessage logMessage) { return string.Format("{0:dd.MM.yyyy HH:mm}: {1} ln: {2} [{3} -> {4}()]: {5}", logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass, logMessage.CallingMethod, logMessage.Text); } } }
namespace SimpleLogger.Logging.Formatters { internal class DefaultLoggerFormatter : ILoggerFormatter { public string ApplyFormat(LogMessage logMessage) { return string.Format("{0:dd.MM.yyyy HH:mm}: {1} [line: {2} {3} -> {4}()]: {5}", logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass, logMessage.CallingMethod, logMessage.Text); } } }
Revise expected resource name after fixing default namespace
using System.IO; using System.Reflection; using NServiceBus.Persistence.Sql.ScriptBuilder; static class ResourceReader { static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly; public static string ReadResource(BuildSqlDialect sqlDialect, string prefix) { var text = $"NServiceBus.Persistence.Sql.{prefix}_{sqlDialect}.sql"; using (var stream = assembly.GetManifestResourceStream(text)) using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } }
using System.IO; using System.Reflection; using NServiceBus.Persistence.Sql.ScriptBuilder; static class ResourceReader { static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly; public static string ReadResource(BuildSqlDialect sqlDialect, string prefix) { var text = $"NServiceBus.Persistence.Sql.ScriptBuilder.{prefix}_{sqlDialect}.sql"; using (var stream = assembly.GetManifestResourceStream(text)) using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } }
Add language declaration to layout
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"]–FAV Rocks</title> <link rel="shortcut icon" href="~/favicon.ico" /> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> @RenderSection("styles", required: false) </head> <body> <header> <div id="title-container"> <a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a> <a id="about" asp-controller="About">About</a> </div> <h3 id="tagline">The most accessible and efficient favicon editor</h3> </header> <hr /> @RenderBody() <hr /> <footer> <p>&copy; @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>. </footer> @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"]–FAV Rocks</title> <link rel="shortcut icon" href="~/favicon.ico" /> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> @RenderSection("styles", required: false) </head> <body> <header> <div id="title-container"> <a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a> <a id="about" asp-controller="About">About</a> </div> <h3 id="tagline">The most accessible and efficient favicon editor</h3> </header> <hr /> @RenderBody() <hr /> <footer> <p>&copy; @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>. </footer> @RenderSection("scripts", required: false) </body> </html>
Set port 7400 and use default WebHost builder
using System.IO; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; namespace Neo4jManager.Host { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .ConfigureServices(services => services.AddAutofac()) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
using System.IO; using System.Net; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace Neo4jManager.Host { public class Program { public static void Main(string[] args) { var host = WebHost.CreateDefaultBuilder(args) .UseKestrel(options => options.Listen(IPAddress.Loopback, 7400)) .ConfigureServices(services => services.AddAutofac()) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
Use a flag to indicate if the shader stage has been successfully compiled.
using System; using OpenTK.Graphics.OpenGL; using System.Diagnostics; using ChamberLib.Content; namespace ChamberLib.OpenTK { public class ShaderStage : IShaderStage { public ShaderStage(ShaderContent content) : this(content.Source, content.Type, content.Name) { } public ShaderStage(string source, ShaderType shaderType, string name) { Source = source; ShaderType = shaderType; Name = name; } public string Name { get; protected set; } public int ShaderID { get; protected set; } public string Source { get; protected set; } public ShaderType ShaderType { get; protected set; } public void MakeReady() { if (ShaderID != 0) return; GLHelper.CheckError(); ShaderID = GL.CreateShader(ShaderType.ToOpenTK()); GLHelper.CheckError(); GL.ShaderSource(ShaderID, Source); GLHelper.CheckError(); GL.CompileShader(ShaderID); GLHelper.CheckError(); int result; GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result); Debug.WriteLine("{1} compile status: {0}", result, ShaderType); GLHelper.CheckError(); Debug.WriteLine("{0} info:", ShaderType); Debug.WriteLine(GL.GetShaderInfoLog(ShaderID)); GLHelper.CheckError(); } } }
using System; using OpenTK.Graphics.OpenGL; using System.Diagnostics; using ChamberLib.Content; using _OpenTK = global::OpenTK; namespace ChamberLib.OpenTK { public class ShaderStage : IShaderStage { public ShaderStage(ShaderContent content) : this(content.Source, content.Type, content.Name) { } public ShaderStage(string source, ShaderType shaderType, string name) { Source = source; ShaderType = shaderType; Name = name; } public string Name { get; protected set; } public int ShaderID { get; protected set; } public string Source { get; protected set; } public ShaderType ShaderType { get; protected set; } public bool IsCompiled { get; protected set; } public void MakeReady() { GLHelper.CheckError(); if (ShaderID == 0) { ShaderID = GL.CreateShader(ShaderType.ToOpenTK()); GLHelper.CheckError(); IsCompiled = false; } if (!IsCompiled) { GL.ShaderSource(ShaderID, Source); GLHelper.CheckError(); GL.CompileShader(ShaderID); GLHelper.CheckError(); int result; GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result); Debug.WriteLine("{1} compile status: {0}", result, ShaderType); GLHelper.CheckError(); Debug.WriteLine("{0} info:", ShaderType); Debug.WriteLine(GL.GetShaderInfoLog(ShaderID)); GLHelper.CheckError(); IsCompiled = (result == 1); } } } }
Add a wrong password status
namespace Espera.Network { public enum ResponseStatus { Success, PlaylistEntryNotFound, Unauthorized, MalformedRequest, NotFound, NotSupported, Rejected, Fatal } }
namespace Espera.Network { public enum ResponseStatus { Success, PlaylistEntryNotFound, Unauthorized, MalformedRequest, NotFound, NotSupported, Rejected, Fatal, WrongPassword } }
Fix Otimização desabilitada para teste
using System.Web; using System.Web.Optimization; namespace Quiz.Web { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include( "~/Scripts/jquery.pietimer.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/style").Include( "~/Scripts/style.css")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
using System.Web; using System.Web.Optimization; namespace Quiz.Web { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include( "~/Scripts/jquery.pietimer.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/style").Include( "~/Scripts/style.css")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); BundleTable.EnableOptimizations = false; } } }
Revert "Added "final door count" comment at return value."
using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; //final door count } } }
using System.Linq; namespace HundredDoors { public static class HundredDoors { /// <summary> /// Solves the 100 Doors problem /// </summary> /// <returns>An array with 101 values, each representing a door (except 0). True = open</returns> public static bool[] Solve() { // Create our array with 101 values, all of them false. We'll only use 1~100 to simplify it bool[] doors = Enumerable.Repeat(false, 101).ToArray(); // We'll pass 100 times, each pass we'll start at door #pass and increment by pass, toggling the current door for (int pass = 1; pass <= 100; pass++) for (int i = pass; i < doors.Length; i += pass) doors[i] = !doors[i]; return doors; } } }
Rename that to avoid confusion
namespace Espera.Network { public enum NetworkSongSource { Local = 0, Youtube = 1, Remote = 2 } }
namespace Espera.Network { public enum NetworkSongSource { Local = 0, Youtube = 1, Mobile = 2 } }
Remove page styling from Ajax search results.
@model IEnumerable<GiveCRM.Models.Member> @foreach (var member in Model) { <a href="javascript:AddDonation(@member.Id);">@member.FirstName @member.LastName @member.PostalCode</a><br /> }
@model IEnumerable<GiveCRM.Models.Member> @{ Layout = null; } @foreach (var member in Model) { <p style="margin:0; padding:0;"><a href="javascript:AddDonation(@member.Id);">@member.FirstName @member.LastName @member.PostalCode</a></p> }
Add missing namespace to the sample.
using Microsoft.AspNet.Abstractions; namespace KWebStartup { public class Startup { public void Configuration(IBuilder app) { app.Run(async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); }); } } }
using Microsoft.AspNet; using Microsoft.AspNet.Abstractions; namespace KWebStartup { public class Startup { public void Configuration(IBuilder app) { app.Run(async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); }); } } }
Fix issue with ms asp.net getting httproute paths with a wildcard
using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Dispatcher; using Pablo.Gallery.Logic; using Pablo.Gallery.Logic.Filters; using System.Web.Http.Controllers; using Pablo.Gallery.Logic.Selectors; namespace Pablo.Gallery { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new LoggingApiExceptionFilter()); config.Routes.MapHttpRoute( name: "api", routeTemplate: "api/{version}/{controller}/{id}/{*path}", defaults: new { version = "v0", id = RouteParameter.Optional, path = RouteParameter.Optional } ); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config, 1)); config.Formatters.JsonFormatter.AddQueryStringMapping("type", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("type", "xml", "application/xml"); //config.MessageHandlers.Add(new CorsHandler()); config.Services.Replace(typeof(IHttpActionSelector), new CorsPreflightActionSelector()); } } }
using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Dispatcher; using Pablo.Gallery.Logic; using Pablo.Gallery.Logic.Filters; using System.Web.Http.Controllers; using Pablo.Gallery.Logic.Selectors; namespace Pablo.Gallery { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new LoggingApiExceptionFilter()); config.Routes.MapHttpRoute( name: "api", routeTemplate: "api/{version}/{controller}/{id}", defaults: new { version = "v0", id = RouteParameter.Optional } ); // need this separate as Url.RouteUrl does not work with a wildcard in the route // this is used to allow files in subfolders of a pack to be retrieved. config.Routes.MapHttpRoute( name: "apipath", routeTemplate: "api/{version}/{controller}/{id}/{*path}", defaults: new { version = "v0", id = RouteParameter.Optional, path = RouteParameter.Optional } ); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config, 1)); config.Formatters.JsonFormatter.AddQueryStringMapping("type", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("type", "xml", "application/xml"); //config.MessageHandlers.Add(new CorsHandler()); config.Services.Replace(typeof(IHttpActionSelector), new CorsPreflightActionSelector()); } } }
Allow coin flip to be heads.
using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; public bool OffWhileLive { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 1) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } }
using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; public bool OffWhileLive { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 2) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } }
Allow visualtests to share config etc. with osu!.
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; using osu.Game.Modes; using osu.Game.Modes.Catch; using osu.Game.Modes.Mania; using osu.Game.Modes.Osu; using osu.Game.Modes.Taiko; namespace osu.Desktop.VisualTests { public static class Program { [STAThread] public static void Main(string[] args) { using (BasicGameHost host = Host.GetSuitableHost(@"osu-visual-tests")) { Ruleset.Register(new OsuRuleset()); Ruleset.Register(new TaikoRuleset()); Ruleset.Register(new ManiaRuleset()); Ruleset.Register(new CatchRuleset()); host.Add(new VisualTestGame()); host.Run(); } } } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; using osu.Game.Modes; using osu.Game.Modes.Catch; using osu.Game.Modes.Mania; using osu.Game.Modes.Osu; using osu.Game.Modes.Taiko; namespace osu.Desktop.VisualTests { public static class Program { [STAThread] public static void Main(string[] args) { using (BasicGameHost host = Host.GetSuitableHost(@"osu")) { Ruleset.Register(new OsuRuleset()); Ruleset.Register(new TaikoRuleset()); Ruleset.Register(new ManiaRuleset()); Ruleset.Register(new CatchRuleset()); host.Add(new VisualTestGame()); host.Run(); } } } }
Add rich text to system field types
using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents the different types available for a <see cref="Field"/>. /// </summary> public class SystemFieldTypes { /// <summary> /// Short text. /// </summary> public const string Symbol = "Symbol"; /// <summary> /// Long text. /// </summary> public const string Text = "Text"; /// <summary> /// An integer. /// </summary> public const string Integer = "Integer"; /// <summary> /// A floating point number. /// </summary> public const string Number = "Number"; /// <summary> /// A datetime. /// </summary> public const string Date = "Date"; /// <summary> /// A boolean value. /// </summary> public const string Boolean = "Boolean"; /// <summary> /// A location field. /// </summary> public const string Location = "Location"; /// <summary> /// A link to another asset or entry. /// </summary> public const string Link = "Link"; /// <summary> /// An array of objects. /// </summary> public const string Array = "Array"; /// <summary> /// An arbitrary json object. /// </summary> public const string Object = "Object"; } }
using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { /// <summary> /// Represents the different types available for a <see cref="Field"/>. /// </summary> public class SystemFieldTypes { /// <summary> /// Short text. /// </summary> public const string Symbol = "Symbol"; /// <summary> /// Long text. /// </summary> public const string Text = "Text"; /// <summary> /// An integer. /// </summary> public const string Integer = "Integer"; /// <summary> /// A floating point number. /// </summary> public const string Number = "Number"; /// <summary> /// A datetime. /// </summary> public const string Date = "Date"; /// <summary> /// A boolean value. /// </summary> public const string Boolean = "Boolean"; /// <summary> /// A location field. /// </summary> public const string Location = "Location"; /// <summary> /// A link to another asset or entry. /// </summary> public const string Link = "Link"; /// <summary> /// An array of objects. /// </summary> public const string Array = "Array"; /// <summary> /// An arbitrary json object. /// </summary> public const string Object = "Object"; /// <summary> /// An rich text document. /// </summary> public const string RichText = "RichText"; } }
Add stub for APFT list
@model IEnumerable<APFT> <h2>Units @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td></td> </tr> } </tbody> </table>
@model IEnumerable<APFT> <h2>Units @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td>@Html.DisplayFor(_ => model.Date)</td> <td>@Html.DisplayFor(_ => model.PushUps)</td> <td>@Html.DisplayFor(_ => model.SitUps)</td> <td>@Html.DisplayFor(_ => model.Run)</td> <td>@Html.DisplayFor(_ => model.TotalScore)</td> <td>@Html.DisplayFor(_ => model.IsPassing)</td> </tr> } </tbody> </table>
Fix incorrect profiler environment variable name for .NET framework support
using System; using System.Runtime.CompilerServices; namespace Mindscape.Raygun4Net { public static class APM { [ThreadStatic] private static bool _enabled = false; [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Enable() { _enabled = true; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Disable() { _enabled = false; } public static bool IsEnabled { get { return _enabled; } } public static bool ProfilerAttached { get { #if NETSTANDARD1_6 || NETSTANDARD2_0 // Look for .NET CORE compatible Environment Variables return Environment.GetEnvironmentVariable("CORECLR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("CORECLR_ENABLE_PROFILING") == "1"; #else // Look for .NET FRAMEWORK compatible Environment Variables return Environment.GetEnvironmentVariable("COR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("COR_PROFILER") == "1"; #endif } } } }
using System; using System.Runtime.CompilerServices; namespace Mindscape.Raygun4Net { public static class APM { [ThreadStatic] private static bool _enabled = false; [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Enable() { _enabled = true; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void Disable() { _enabled = false; } public static bool IsEnabled { get { return _enabled; } } public static bool ProfilerAttached { get { #if NETSTANDARD1_6 || NETSTANDARD2_0 // Look for .NET CORE compatible Environment Variables return Environment.GetEnvironmentVariable("CORECLR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("CORECLR_ENABLE_PROFILING") == "1"; #else // Look for .NET FRAMEWORK compatible Environment Variables return Environment.GetEnvironmentVariable("COR_PROFILER") == "{e2338988-38cc-48cd-a6b6-b441c31f34f1}" && Environment.GetEnvironmentVariable("COR_ENABLE_PROFILING") == "1"; #endif } } } }
Fix ConfigurationsRights.List not being a power of 2
using System; namespace Tgstation.Server.Api.Rights { /// <summary> /// Rights for <see cref="Models.ConfigurationFile"/> /// </summary> [Flags] public enum ConfigurationRights : ulong { /// <summary> /// User has no rights /// </summary> None = 0, /// <summary> /// User may read files /// </summary> Read = 1, /// <summary> /// User may write files /// </summary> Write = 2, /// <summary> /// User may list files /// </summary> List = 3 } }
using System; namespace Tgstation.Server.Api.Rights { /// <summary> /// Rights for <see cref="Models.ConfigurationFile"/> /// </summary> [Flags] public enum ConfigurationRights : ulong { /// <summary> /// User has no rights /// </summary> None = 0, /// <summary> /// User may read files /// </summary> Read = 1, /// <summary> /// User may write files /// </summary> Write = 2, /// <summary> /// User may list files /// </summary> List = 4 } }
Add a check for argument existence to the Compiler
using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static readonly string[] HelpOptions = new string[] { "--help", "-h", "-?", "/help", "/h", "/?" }; public static bool TryRun(FileInfo assembly, DirectoryInfo? projectDir) { var executor = ProjectLoader.GetExecutor(assembly.FullName); return executor.ExecuteCompile(assembly, projectDir, null); } public static int Main(string[] args) { if (args.Length != 2 || (args.Length == 1 && HelpOptions.Contains(args[0]))) { Console.Error.Write( @"Usage: DotVVM.Compiler <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory."); return 1; } var success = TryRun(new FileInfo(args[0]), new DirectoryInfo(args[1])); return success ? 0 : 1; } } }
using System; using System.IO; using System.Linq; namespace DotVVM.Compiler { public static class Program { private static readonly string[] HelpOptions = new string[] { "--help", "-h", "-?", "/help", "/h", "/?" }; public static bool TryRun(FileInfo assembly, DirectoryInfo? projectDir) { var executor = ProjectLoader.GetExecutor(assembly.FullName); return executor.ExecuteCompile(assembly, projectDir, null); } public static int Main(string[] args) { // To minimize dependencies, this tool deliberately reinvents the wheel instead of using System.CommandLine. if (args.Length != 2 || (args.Length == 1 && HelpOptions.Contains(args[0]))) { Console.Error.Write( @"Usage: DotVVM.Compiler <ASSEMBLY> <PROJECT_DIR> Arguments: <ASSEMBLY> Path to a DotVVM project assembly. <PROJECT_DIR> Path to a DotVVM project directory."); return 1; } var assemblyFile = new FileInfo(args[0]); if (!assemblyFile.Exists) { Console.Error.Write($"Assembly '{assemblyFile}' does not exist."); return 1; } var projectDir = new DirectoryInfo(args[1]); if (!projectDir.Exists) { Console.Error.Write($"Project directory '{projectDir}' does not exist."); return 1; } var success = TryRun(assemblyFile, projectDir); return success ? 0 : 1; } } }
Change icon color to be consistent with other section icon colors
namespace FALM.Housekeeping.Constants { /// <summary> /// HkConstants /// </summary> public class HkConstants { /// <summary> /// Application /// </summary> public class Application { /// <summary>Name of the Application</summary> public const string Name = "F.A.L.M."; /// <summary>Alias of the Application</summary> public const string Alias = "FALM"; /// <summary>Icon of the Application</summary> public const string Icon = "icon-speed-gauge color-yellow"; /// <summary>Title of the Application</summary> public const string Title = "F.A.L.M. Housekeeping"; } /// <summary> /// Tree /// </summary> public class Tree { /// <summary>Name of the Tree</summary> public const string Name = "Housekeeping Tools"; /// <summary>Alias of the Tree</summary> public const string Alias = "housekeeping"; /// <summary>Icon of the Tree</summary> public const string Icon = "icon-umb-deploy"; /// <summary>Title of the Tree</summary> public const string Title = "Menu"; } /// <summary> /// Controller /// </summary> public class Controller { /// <summary>Alias of the Controller</summary> public const string Alias = "FALM"; } } }
namespace FALM.Housekeeping.Constants { /// <summary> /// HkConstants /// </summary> public class HkConstants { /// <summary> /// Application /// </summary> public class Application { /// <summary>Name of the Application</summary> public const string Name = "F.A.L.M."; /// <summary>Alias of the Application</summary> public const string Alias = "FALM"; /// <summary>Icon of the Application</summary> public const string Icon = "icon-speed-gauge"; /// <summary>Title of the Application</summary> public const string Title = "F.A.L.M. Housekeeping"; } /// <summary> /// Tree /// </summary> public class Tree { /// <summary>Name of the Tree</summary> public const string Name = "Housekeeping Tools"; /// <summary>Alias of the Tree</summary> public const string Alias = "housekeeping"; /// <summary>Icon of the Tree</summary> public const string Icon = "icon-umb-deploy"; /// <summary>Title of the Tree</summary> public const string Title = "Menu"; } /// <summary> /// Controller /// </summary> public class Controller { /// <summary>Alias of the Controller</summary> public const string Alias = "FALM"; } } }
FIX CIT-785 Hide EDIT button for all users in hub
@using Cats.Models.Hubs @using Cats.Web.Hub.Helpers @using Telerik.Web.Mvc.UI @{ var usr = @Html.GetCurrentUser(); var mdl = new CurrentUserModel(usr); } <div align="right"> @{ string title = ""; if(ViewBag.Title != null) { title = ViewBag.Title; } } </div> <div class="row-fluid form-inline"> <h4 class="page-header">@Html.Translate(title) @Html.Label("Owner", mdl.Owner) - @Html.Label("WH", mdl.Name) @Html.Translate(" Hub ") @{ if(usr.UserAllowedHubs.Count > 1) { @Html.HubSelectionLink(Html.Translate("Change Warehouse"), Url.Action("HubList", "CurrentHub"), Html.Translate("Change Hub")) } } </h4> </div>
@using Cats.Models.Hubs @using Cats.Web.Hub.Helpers @using Telerik.Web.Mvc.UI @{ var usr = @Html.GetCurrentUser(); var mdl = new CurrentUserModel(usr); } <div align="right"> @{ string title = ""; if(ViewBag.Title != null) { title = ViewBag.Title; } } </div> <div class="row-fluid form-inline"> <h4 class="page-header">@Html.Translate(title) @Html.Label("Owner", mdl.Owner) - @Html.Label("WH", mdl.Name) @Html.Translate(" Hub ") @*@{ if(usr.UserAllowedHubs.Count > 1) { @Html.HubSelectionLink(Html.Translate("Change Warehouse"), Url.Action("HubList", "CurrentHub"), Html.Translate("Change Hub")) } }*@ </h4> </div>
Remove panel from index forum page for mobile devices
@{ Layout = null; } <div class="container" style="padding-top: 50px;"> <div class="container"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th></th> <th>Forum Name</th> <th>Topics</th> <th>Posts</th> <th>Last Post</th> </tr> </thead> <tbody> <tr class="board-row" data-ng-repeat="board in boards"> <td></td> <td data-ng-click="openBoard(board.id)"><a data-ng-href="/#/forums/{{board.id}}">{{ board.name }}</a></td> <td>{{ board.totalTopics }}</td> <td>{{ board.totalPosts }}</td> <td> <div data-ng-show="board.lastTopicTitle != null"> <a href="/#/forums/{{ board.id }}/{{ board.lastTopicId }}">{{ board.lastTopicTitle }}</a> <div class="last-post-author">by {{ board.lastPostAuthor }}</div> </div> <div data-ng-show="board.lastTopicTitle == null"> <em>None</em> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div>
@{ Layout = null; } <div class="container" style="padding-top: 50px;"> <div class="container"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th></th> <th>Forum Name</th> <th>Topics</th> <th>Posts</th> <th>Last Post</th> </tr> </thead> <tbody> <tr class="board-row" data-ng-repeat="board in boards"> <td></td> <td data-ng-click="openBoard(board.id)"><a data-ng-href="/#/forums/{{board.id}}">{{ board.name }}</a></td> <td>{{ board.totalTopics }}</td> <td>{{ board.totalPosts }}</td> <td> <div data-ng-show="board.lastTopicTitle != null"> <a href="/#/forums/{{ board.id }}/{{ board.lastTopicId }}">{{ board.lastTopicTitle }}</a> <div class="last-post-author">by {{ board.lastPostAuthor }}</div> </div> <div data-ng-show="board.lastTopicTitle == null"> <em>None</em> </div> </td> </tr> </tbody> </table> </div> </div>
Add case for waiting on an empty id
using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning($"{this} could not find object with id {id}"); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } }
using System.Collections; using UnityEngine; using UnityEngine.Networking; public abstract class GameMessageBase : MessageBase { public GameObject NetworkObject; public GameObject[] NetworkObjects; protected IEnumerator WaitFor(NetworkInstanceId id) { if (id.IsEmpty()) { Debug.LogError($"{this} tried to wait on an empty (0) id"); yield break; } int tries = 0; while ((NetworkObject = ClientScene.FindLocalObject(id)) == null) { if (tries++ > 10) { Debug.LogWarning($"{this} could not find object with id {id}"); yield break; } yield return YieldHelper.EndOfFrame; } } protected IEnumerator WaitFor(params NetworkInstanceId[] ids) { NetworkObjects = new GameObject[ids.Length]; while (!AllLoaded(ids)) { yield return YieldHelper.EndOfFrame; } } private bool AllLoaded(NetworkInstanceId[] ids) { for (int i = 0; i < ids.Length; i++) { GameObject obj = ClientScene.FindLocalObject(ids[i]); if (obj == null) { return false; } NetworkObjects[i] = obj; } return true; } }
Set TLS 1.2 as the default potocol
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { } } }
using Microsoft.Owin; using Owin; using System.Net; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { // .NET Framework 4.6.1 and lower does not support TLS 1.2 as the default protocol, but Delivery API requires it. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } }
Disable GDB + Bochs GUI
using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } }
using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => false; public virtual bool StartBochsDebugGUI => false; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } }
Move usings inside namespace in stringextensionstests
using Moya.Extensions; using Xunit; namespace TestMoya.Extensions { public class StringExtensionsTests { [Fact] public void StringExtensionsFormatWithWorksWithWorksWithStrings() { const string Expected = "Hello world!"; var actual = "{0} {1}".FormatWith("Hello", "world!"); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegers() { const string Expected = "1 2 3 4"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, 3, 4); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegersAndStrings() { const string Expected = "1 2 Hello World!"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, "Hello", "World!"); Assert.Equal(Expected, actual); } } }
namespace TestMoya.Extensions { using Moya.Extensions; using Xunit; public class StringExtensionsTests { [Fact] public void StringExtensionsFormatWithWorksWithWorksWithStrings() { const string Expected = "Hello world!"; var actual = "{0} {1}".FormatWith("Hello", "world!"); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegers() { const string Expected = "1 2 3 4"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, 3, 4); Assert.Equal(Expected, actual); } [Fact] public void StringExtensionsFormatWithWorksWithWorksWithIntegersAndStrings() { const string Expected = "1 2 Hello World!"; var actual = "{0} {1} {2} {3}".FormatWith(1, 2, "Hello", "World!"); Assert.Equal(Expected, actual); } } }
Fix crash caused by previous commit
using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NTumbleBit.BouncyCastle.Security { internal class SecureRandom : Random { public SecureRandom() { } public override int Next() { return RandomUtils.GetInt32(); } public override int Next(int maxValue) { throw new NotImplementedException(); } public override int Next(int minValue, int maxValue) { throw new NotImplementedException(); } public override void NextBytes(byte[] buffer) { RandomUtils.GetBytes(buffer); } } }
using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NTumbleBit.BouncyCastle.Security { internal class SecureRandom : Random { public SecureRandom() { } public override int Next() { return RandomUtils.GetInt32(); } public override int Next(int maxValue) { return (int)(RandomUtils.GetUInt32() % maxValue); } public override int Next(int minValue, int maxValue) { throw new NotImplementedException(); } public override void NextBytes(byte[] buffer) { RandomUtils.GetBytes(buffer); } } }
Remove wrong type for username and e-mail field
@model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-signin", @role="form"})) { <div class="form-group"> @Html.ValidationSummary(true) </div> <h2 class="form-signin-heading dark">Meld u alstublieft aan</h2> @Html.LabelFor(vm => vm.Login.UserName, new { @class="sr-only" }) @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @type="email", @placeholder = "Gebruikersnaam of e-mailadres" }) @Html.LabelFor(vm => vm.Login.Password, new { @class="sr-only" }) @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) <div class="checkbox dark"> <label class="pull-left"> @Html.CheckBoxFor(vm => vm.Login.RememberMe) Onthoud mij. </label> @Html.ActionLink("Wachtwoord vergeten?", "LostPassword", null, new { @class = "pull-right" }) <br/> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Inloggen</button> if(ViewData.ModelState.ContainsKey("registration")) { @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } }
@model LoginOrRegisterViewModel @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class="form-signin", @role="form"})) { <div class="form-group"> @Html.ValidationSummary(true) </div> <h2 class="form-signin-heading dark">Meld u alstublieft aan</h2> @Html.LabelFor(vm => vm.Login.UserName, new { @class="sr-only" }) @Html.TextBoxFor(vm => vm.Login.UserName, new { @class = "form-control", @placeholder = "Gebruikersnaam of e-mailadres" }) @Html.LabelFor(vm => vm.Login.Password, new { @class="sr-only" }) @Html.PasswordFor(vm => vm.Login.Password, new { @class = "form-control", @placeholder = "Wachtwoord" }) <div class="checkbox dark"> <label class="pull-left"> @Html.CheckBoxFor(vm => vm.Login.RememberMe) Onthoud mij. </label> @Html.ActionLink("Wachtwoord vergeten?", "LostPassword", null, new { @class = "pull-right" }) <br/> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Inloggen</button> if(ViewData.ModelState.ContainsKey("registration")) { @ViewData.ModelState["registration"].Errors.First().ErrorMessage; } }
Refactor benchmarks to only demonstrate what's needed
// 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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { private Bindable<int> bindable; [GlobalSetup] public void GlobalSetup() => bindable = new Bindable<int>(); /// <summary> /// Creates an instance of the bindable directly by construction. /// </summary> [Benchmark(Baseline = true)] public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>(); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>. /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>. /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true); /// <summary> /// Creates an instance of the bindable via <see cref="IBindable.CreateInstance"/>. /// This is the current and most performant version used for <see cref="IBindable.GetBoundCopy"/>, as equally performant as <see cref="CreateInstanceViaConstruction"/>. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaBindableCreateInstance() => bindable.CreateInstance(); } }
// 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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected internal override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } }
Add a couple of apparently missing events
using Newtonsoft.Json; namespace SyncTrayzor.Syncthing.ApiClient { [JsonConverter(typeof(DefaultingStringEnumConverter))] public enum EventType { Unknown, Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, // Not quite sure which it's going to be, so play it safe... MetadataChanged, ItemMetadataChanged, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, FolderErrors, FolderScanProgress, DevicePaused, DeviceResumed, LoginAttempt, ListenAddressChanged, } }
using Newtonsoft.Json; namespace SyncTrayzor.Syncthing.ApiClient { [JsonConverter(typeof(DefaultingStringEnumConverter))] public enum EventType { Unknown, Starting, StartupComplete, Ping, DeviceDiscovered, DeviceConnected, DeviceDisconnected, RemoteIndexUpdated, LocalIndexUpdated, ItemStarted, ItemFinished, // Not quite sure which it's going to be, so play it safe... MetadataChanged, ItemMetadataChanged, StateChanged, FolderRejected, DeviceRejected, ConfigSaved, DownloadProgress, FolderSummary, FolderCompletion, FolderErrors, FolderScanProgress, DevicePaused, DeviceResumed, LoginAttempt, ListenAddressChanged, RelayStateChanged, ExternalPortMappingChanged, } }
Add MI debugger working directory to PATH
// 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.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Collections.Specialized; using System.Collections; namespace MICore { public class LocalTransport : PipeTransport { public LocalTransport() { } public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer) { LocalLaunchOptions localOptions = (LocalLaunchOptions)options; Process proc = new Process(); proc.StartInfo.FileName = localOptions.MIDebuggerPath; proc.StartInfo.Arguments = "--interpreter=mi"; proc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath); InitProcess(proc, out reader, out writer); } protected override string GetThreadName() { return "MI.LocalTransport"; } } }
// 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.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Collections.Specialized; using System.Collections; namespace MICore { public class LocalTransport : PipeTransport { public LocalTransport() { } public override void InitStreams(LaunchOptions options, out StreamReader reader, out StreamWriter writer) { LocalLaunchOptions localOptions = (LocalLaunchOptions)options; string miDebuggerDir = System.IO.Path.GetDirectoryName(localOptions.MIDebuggerPath); Process proc = new Process(); proc.StartInfo.FileName = localOptions.MIDebuggerPath; proc.StartInfo.Arguments = "--interpreter=mi"; proc.StartInfo.WorkingDirectory = miDebuggerDir; //GDB locally requires that the directory be on the PATH, being the working directory isn't good enough if (proc.StartInfo.EnvironmentVariables.ContainsKey("PATH")) { proc.StartInfo.EnvironmentVariables["PATH"] = proc.StartInfo.EnvironmentVariables["PATH"] + ";" + miDebuggerDir; } InitProcess(proc, out reader, out writer); } protected override string GetThreadName() { return "MI.LocalTransport"; } } }
Rename SELECT * test cases to match naming convention
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NQuery.UnitTests { [TestClass] public class SelectStarTests { [TestMethod] public void Binder_DisallowsSelectStarWithoutTables() { var syntaxTree = SyntaxTree.ParseQuery("SELECT *"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(1, diagnostics.Length); Assert.AreEqual(DiagnosticId.MustSpecifyTableToSelectFrom, diagnostics[0].DiagnosticId); } [TestMethod] public void Binder_DisallowsSelectStarWithoutTables_UnlessInExists() { var syntaxTree = SyntaxTree.ParseQuery("SELECT 'Test' WHERE EXISTS (SELECT *)"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(0, diagnostics.Length); } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NQuery.UnitTests { [TestClass] public class SelectStarTests { [TestMethod] public void SelectStar_Disallowed_WhenNoTablesSpecified() { var syntaxTree = SyntaxTree.ParseQuery("SELECT *"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(1, diagnostics.Length); Assert.AreEqual(DiagnosticId.MustSpecifyTableToSelectFrom, diagnostics[0].DiagnosticId); } [TestMethod] public void SelectStar_Disallowed_WhenNoTablesSpecified_UnlessInExists() { var syntaxTree = SyntaxTree.ParseQuery("SELECT 'Test' WHERE EXISTS (SELECT *)"); var compilation = Compilation.Empty.WithSyntaxTree(syntaxTree).WithIdNameTable(); var semanticModel = compilation.GetSemanticModel(); var diagnostics = semanticModel.GetDiagnostics().ToArray(); Assert.AreEqual(0, diagnostics.Length); } } }
Implement endpoint for remove instance
using System; using System.Linq; using Nancy; namespace Okanshi.Dashboard { public class SettingsModule : NancyModule { public SettingsModule(IConfiguration configuration) { Get["/settings"] = p => { var servers = configuration.GetAll().ToArray(); return View["settings.html", servers]; }; Post["/settings"] = p => { var name = Request.Form.Name; var url = Request.Form.url; var refreshRate = Convert.ToInt64(Request.Form.refreshRate.Value); var server = new OkanshiServer(name, url, refreshRate); configuration.Add(server); return Response.AsRedirect("/settings"); }; } } }
using System; using System.Linq; using Nancy; namespace Okanshi.Dashboard { public class SettingsModule : NancyModule { public SettingsModule(IConfiguration configuration) { Get["/settings"] = p => { var servers = configuration.GetAll().ToArray(); return View["settings.html", servers]; }; Post["/settings"] = p => { var name = Request.Form.Name; var url = Request.Form.url; var refreshRate = Convert.ToInt64(Request.Form.refreshRate.Value); var server = new OkanshiServer(name, url, refreshRate); configuration.Add(server); return Response.AsRedirect("/settings"); }; Post["/settings/delete"] = p => { var name = (string)Request.Form.InstanceName; configuration.Remove(name); return Response.AsRedirect("/settings"); }; } } }
Remove hard coded USD dollar symbol and use currency string formatting instead.
@if (Model.DiscountedPrice != Model.Price) { <b class="inactive-price" style="text-decoration:line-through" title="@T("Was ${0}", Model.Price)">$@Model.Price</b> <b class="discounted-price" title="@T("Now ${0}", Model.DiscountedPrice)">$@Model.DiscountedPrice</b> <span class="discount-comment">@Model.DiscountComment</span> } else { <b>$@Model.Price</b> }
@if (Model.DiscountedPrice != Model.Price) { <b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", Model.Price.ToString("c"))">@Model.Price.ToString("c")</b> <b class="discounted-price" title="@T("Now {0}", Model.DiscountedPrice.ToString("c"))">@Model.DiscountedPrice.ToString("c")</b> <span class="discount-comment">@Model.DiscountComment</span> } else { <b>@Model.Price.ToString("c")</b> }
Put passwords in startup args
using S22.Xmpp.Client; using S22.Xmpp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using S22.Xmpp.Im; namespace XmppConsole { class Program { static void Main(string[] args) { try { using (var client = new XmppClient("something.com", "someone", "password")) { client.Connect(); client.Message += OnMessage; Console.WriteLine("Connected as " + client.Jid); string line; while ((line = Console.ReadLine()) != null) { Jid to = new Jid("something.com", "someone"); client.SendMessage(to, line, type: MessageType.Chat); } } } catch (Exception exc) { Console.WriteLine(exc.ToString()); } Console.WriteLine("Press any key to quit..."); Console.ReadLine(); } private static void OnMessage(object sender, MessageEventArgs e) { Console.WriteLine(e.Jid.Node + ": " + e.Message.Body); } } }
using S22.Xmpp.Client; using S22.Xmpp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using S22.Xmpp.Im; namespace XmppConsole { class Program { static void Main(string[] args) { try { using (var client = new XmppClient(args[0], args[1], args[2])) { client.Connect(); client.SetStatus(Availability.Online); client.Message += OnMessage; Console.WriteLine("Connected as " + client.Jid); string line; while ((line = Console.ReadLine()) != null) { Jid to = new Jid("something.com", "someone"); client.SendMessage(to, line, type: MessageType.Chat); } client.SetStatus(Availability.Offline); } } catch (Exception exc) { Console.WriteLine(exc.ToString()); } Console.WriteLine("Press any key to quit..."); Console.ReadLine(); } private static void OnMessage(object sender, MessageEventArgs e) { Console.WriteLine(e.Jid.Node + ": " + e.Message.Body); } } }
Remove the container class from the header, because it was redundant with its containing div.
 <div class="container"> <header class="container"> <h1>Sweet Water Revolver</h1> </header> </div>
 <div class="container"> <header> <h1>Sweet Water Revolver</h1> </header> </div>
Enable migrations on app start
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using PickemApp.Models; using PickemApp.Migrations; namespace PickemApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<PickemDBContext, Configuration>()); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
Enable CF migrations on restart
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Portfolio { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Runs Code First database update on each restart... // handy for deploy via GitHub. #if !DEBUG var migrator = new DbMigrator(new Configuration()); migrator.Update(); #endif } } }
Fix demo by uncommenting line accidentally left commented
using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); //distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } }
using System; using DemoDistributor.Endpoints.FileSystem; using DemoDistributor.Endpoints.Sharepoint; using Delivered; namespace DemoDistributor { internal class Program { private static void Main(string[] args) { //Configure the distributor var distributor = new Distributor<File, Vendor>(); distributor.RegisterEndpointRepository(new FileSystemEndpointRepository()); distributor.RegisterEndpointRepository(new SharepointEndpointRepository()); distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService()); distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService()); distributor.MaximumConcurrentDeliveries(3); //Distribute a file to a vendor try { var task = distributor.DistributeAsync(FakeFile, FakeVendor); task.Wait(); Console.WriteLine("\nDistribution succeeded."); } catch(AggregateException aggregateException) { Console.WriteLine("\nDistribution failed."); foreach (var exception in aggregateException.Flatten().InnerExceptions) { Console.WriteLine($"* {exception.Message}"); } } Console.WriteLine("\nPress enter to exit."); Console.ReadLine(); } private static File FakeFile => new File { Name = @"test.pdf", Contents = new byte[1024] }; private static Vendor FakeVendor => new Vendor { Name = @"Mark's Pool Supplies" }; private static Vendor FakeVendor2 => new Vendor { Name = @"Kevin's Art Supplies" }; } }
Fix null players in player list.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public abstract class BaseController : Controller { private static List<Player> playerList = new List<Player>(); public Player GetPlayer() { if (Request.Cookies["userInfo"] != null) { string idStr = Server.HtmlEncode(Request.Cookies["userInfo"]["id"]); int id = Int32.Parse(idStr); Player player = SearchPlayer(id); if (player != null) return player; lock (playerList) { player = SearchPlayer(id); if (player != null) return player; Player newPlayer = Player.GetInstance(id); if (newPlayer != null) playerList.Add(newPlayer); return newPlayer; } } return null; } private Player SearchPlayer(int id) { if (!playerList.Any()) return null; foreach (Player listPlayer in playerList) { if (listPlayer.id == id) { return listPlayer; } } return null; } } }
Maintain focus on the text editor after saving.
using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); } } }
using System; using System.Windows.Controls; namespace PlantUmlEditor.View { public partial class DiagramEditorView : UserControl { public DiagramEditorView() { InitializeComponent(); ContentEditor.IsEnabledChanged += ContentEditor_IsEnabledChanged; } void ContentEditor_IsEnabledChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { // Maintain focus on the text editor. if ((bool)e.NewValue) Dispatcher.BeginInvoke(new Action(() => ContentEditor.Focus())); } } }
Fix bug: "Copy" button don't show in TextView during saving
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = CanCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Caliburn.Micro; namespace SharpGraphEditor.ViewModels { public class TextViewerViewModel : PropertyChangedBase { private string _text; private bool _canCopy; private bool _canCancel; private bool _isReadOnly; public TextViewerViewModel(string text, bool canCopy, bool canCancel, bool isReadOnly) { Text = text; CanCopy = canCopy; CanCancel = canCancel; IsReadOnly = isReadOnly; } public void Ok(IClose closableWindow) { closableWindow.TryClose(true); } public void Cancel(IClose closableWindow) { closableWindow.TryClose(false); } public void CopyText() { Clipboard.SetText(Text); } public string Text { get { return _text; } set { _text = value; NotifyOfPropertyChange(() => Text); } } public bool CanCopy { get { return _canCopy; } set { _canCopy = value; NotifyOfPropertyChange(() => CanCopy); } } public bool CanCancel { get { return _canCancel; } set { _canCancel = value; NotifyOfPropertyChange(() => CanCancel); } } public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; NotifyOfPropertyChange(() => IsReadOnly); } } } }
Fix iOS app entry for raw keyboard input
// 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 UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, null, "AppDelegate"); } } }
// 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 UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } }
Fix ShrineRoom to always be current spawner
using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? Thing shrine = room.AllContainedThings.FirstOrDefault<Thing>(t => t is Building_Shrine); if (shrine == null) { return 0.0f; } else { return 9999.0f; } } } }
using RimWorld; using Verse; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { class RoomRoleWorker_ShrineRoom : RoomRoleWorker { public override float GetScore(Room room) { // I don't know if there should be some "If it's full of joy objects/work benches, *don't* classify it as // a Shrine - if you Shrine room wall gets broken down by a bug, this will probably push all the attached // rooms into the "Shrine Room" - is that a desired behaviour? var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner; if (room.AllContainedThings.Contains<Thing>(shrine)) { return 9999.0f; } else { return 0.0f; } } } }
Add IoC registration for login data translator
// 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 EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); } } }
// 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 EOLib.Data.Login; using EOLib.Data.Protocol; using Microsoft.Practices.Unity; namespace EOLib.Net.Translators { public class PacketTranslatorContainer : IDependencyContainer { public void RegisterDependencies(IUnityContainer container) { container.RegisterType<IPacketTranslator<IInitializationData>, InitDataTranslator>(); container.RegisterType<IPacketTranslator<IAccountLoginData>, AccountLoginPacketTranslator>(); } } }
Fix port in arguments crashing app
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost(args).Run(); Console.ResetColor(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Yio.Utilities; namespace Yio { public class Program { private static int _port { get; set; } public static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.Unicode; StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan); if (!File.Exists("appsettings.json")) { StartupUtilities.WriteFailure("configuration is missing"); Environment.Exit(1); } StartupUtilities.WriteInfo("setting port"); if(args == null || args.Length == 0) { _port = 5100; StartupUtilities.WriteSuccess("port set to " + _port + " (default)"); } else { _port = args[0] == null ? 5100 : Int32.Parse(args[0]); StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)"); } StartupUtilities.WriteInfo("starting App"); BuildWebHost().Run(); Console.ResetColor(); } public static IWebHost BuildWebHost() => WebHost.CreateDefaultBuilder() .UseUrls("http://0.0.0.0:" + _port.ToString() + "/") .UseStartup<Startup>() .Build(); } }
Fix integer overflow on large collection files
using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { var lengthToCopy = sourceData.Length; var sourceIndex = 0; var targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (int)(targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (int)(sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrude the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, sourceIndex, targetData, targetIndex, lengthToCopy); } } } }
using System; namespace MarcelloDB.Helpers { internal class DataHelper { internal static void CopyData( Int64 sourceAddress, byte[] sourceData, Int64 targetAddress, byte[] targetData) { Int64 lengthToCopy = sourceData.Length; Int64 sourceIndex = 0; Int64 targetIndex = 0; if (sourceAddress < targetAddress) { sourceIndex = (targetAddress - sourceAddress); lengthToCopy = sourceData.Length - sourceIndex; } if (sourceAddress > targetAddress) { targetIndex = (sourceAddress - targetAddress); lengthToCopy = targetData.Length - targetIndex; } //max length to copy to not overrun the target array lengthToCopy = Math.Min(lengthToCopy, targetData.Length - targetIndex); //max length to copy to not overrrun the source array lengthToCopy = Math.Min(lengthToCopy, sourceData.Length - sourceIndex); if (lengthToCopy > 0) { Array.Copy(sourceData, (int)sourceIndex, targetData, (int)targetIndex, (int)lengthToCopy); } } } }
Fix navigator.getUserMedia webkit(TypeError: Illegal invocation) + moz(typo)
using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozUserMedia || navigator.msGetUserMedia)({params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }
using System.Html.Media; using System.Runtime.CompilerServices; namespace System.Html { public partial class Navigator { [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess) {} [InlineCode("(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(navigator, {params}, {onsuccess}, {onerror})")] public static void GetUserMedia(MediaStreamOptions @params, Action<LocalMediaStream> onsuccess, Action<string> onerror) {} } }
Use glob-recurse and fix the program when you pass it file names
using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { /// <summary> /// see https://support.microsoft.com/en-us/kb/303974 /// </summary> class MetadataFinder { public System.Collections.Generic.List<String> Files = new System.Collections.Generic.List<String>(); public void SearchDirectory(string dir) { try { foreach (var d in Directory.GetDirectories(dir)) { foreach (var f in Directory.GetFiles(d, "*.devicemetadata-ms")) { Files.Add(f); } SearchDirectory(d); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } } class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); var finder = new MetadataFinder(); finder.SearchDirectory(assemblyDir); files = finder.Files; } else { files.AddRange(files); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } }
using System; using System.IO; using System.Collections; namespace DeviceMetadataInstallTool { class Program { static void Main(string[] args) { var files = new System.Collections.Generic.List<String>(); //Console.WriteLine("Args size is {0}", args.Length); if (args.Length == 0) { var assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); files = Sensics.DeviceMetadataInstaller.Util.GetMetadataFilesRecursive(assemblyDir); } else { files.AddRange(args); } var store = new Sensics.DeviceMetadataInstaller.MetadataStore(); foreach (var fn in files) { var pkg = new Sensics.DeviceMetadataInstaller.MetadataPackage(fn); Console.WriteLine("{0} - {1} - Default locale: {2}", pkg.ExperienceGUID, pkg.ModelName, pkg.DefaultLocale); store.InstallPackage(pkg); } } } }
Fix map path for single player maps
using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPathInSaveFolder); } } } }
using System.IO; using OpenSage.Network; namespace OpenSage.Data.Sav { internal static class GameStateMap { internal static void Load(SaveFileReader reader, Game game) { reader.ReadVersion(2); var mapPath1 = reader.ReadAsciiString(); var mapPath2 = reader.ReadAsciiString(); var gameType = reader.ReadEnum<GameType>(); var mapSize = reader.BeginSegment(); // TODO: Delete this temporary map when ending the game. var mapPathInSaveFolder = Path.Combine( game.ContentManager.UserMapsFileSystem.RootDirectory, mapPath1); using (var mapOutputStream = File.OpenWrite(mapPathInSaveFolder)) { reader.ReadBytesIntoStream(mapOutputStream, (int)mapSize); } reader.EndSegment(); var unknown2 = reader.ReadUInt32(); // 586 var unknown3 = reader.ReadUInt32(); // 3220 if (gameType == GameType.Skirmish) { game.SkirmishManager = new LocalSkirmishManager(game); game.SkirmishManager.Settings.Load(reader); game.SkirmishManager.Settings.MapName = mapPath1; game.SkirmishManager.StartGame(); } else { game.StartSinglePlayerGame(mapPath1); } } } }
Add extension to verify mimetype.
namespace Papyrus { public static class EBookExtensions { } }
using System; using System.Threading.Tasks; using Windows.Storage; namespace Papyrus { public static class EBookExtensions { public static async Task<bool> VerifyMimetypeAsync(this EBook ebook) { var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype"); if (mimetypeFile == null) // Make sure file exists. return false; var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile); if (fileContents != "application/epub+zip") // Make sure file contents are correct. return false; return true; } } }
Use azure hosted server for now
using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.net/api/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }
using System.Collections.Generic; using System.Net; using AppGet.Http; using NLog; namespace AppGet.PackageRepository { public class AppGetServerClient : IPackageRepository { private readonly IHttpClient _httpClient; private readonly Logger _logger; private readonly HttpRequestBuilder _requestBuilder; private const string API_ROOT = "https://appget.azurewebsites.net/v1/"; public AppGetServerClient(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; _logger = logger; _requestBuilder = new HttpRequestBuilder(API_ROOT); } public PackageInfo GetLatest(string name) { _logger.Info("Getting package " + name); var request = _requestBuilder.Build("packages/{package}/latest"); request.AddSegment("package", name); try { var package = _httpClient.Get<PackageInfo>(request); return package.Resource; } catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound) { return null; } throw; } } public List<PackageInfo> Search(string term) { _logger.Info("Searching for " + term); var request = _requestBuilder.Build("packages"); request.UriBuilder.SetQueryParam("q", term.Trim()); var package = _httpClient.Get<List<PackageInfo>>(request); return package.Resource; } } }