Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix osu! playfield (was using inheriting sizemode when it shouldn't).
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Drawables; using OpenTK; namespace osu.Game.GameModes.Play.Osu { public class OsuPlayfield : Playfield { public OsuPlayfield() { Size = new Vector2(512, 384); Anchor = Anchor.Centre; Origin = Anchor.Centre; } public override void Load() { base.Load(); Add(new Box() { Anchor = Anchor.Centre, Origin = Anchor.Centre, SizeMode = InheritMode.XY, Size = new Vector2(1.3f, 1.3f), Alpha = 0.5f }); } } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Drawables; using OpenTK; namespace osu.Game.GameModes.Play.Osu { public class OsuPlayfield : Playfield { public OsuPlayfield() { SizeMode = InheritMode.None; Size = new Vector2(512, 384); Anchor = Anchor.Centre; Origin = Anchor.Centre; } public override void Load() { base.Load(); Add(new Box() { Anchor = Anchor.Centre, Origin = Anchor.Centre, SizeMode = InheritMode.XY, Alpha = 0.5f }); } } }
Fix silent failure when using metamethods on an object without an attached state
using System.Collections.Generic; namespace Mond.VirtualMachine { class Object { public readonly Dictionary<MondValue, MondValue> Values; public bool Locked; public MondValue Prototype; public object UserData; private MondState _dispatcherState; public MondState State { set { if (_dispatcherState == null) _dispatcherState = value; } } public Object() { Values = new Dictionary<MondValue, MondValue>(); Locked = false; Prototype = null; UserData = null; } public bool TryDispatch(string name, out MondValue result, params MondValue[] args) { if (_dispatcherState == null) { result = MondValue.Undefined; return false; } MondState state = null; MondValue callable; if (!Values.TryGetValue(name, out callable)) { var current = Prototype; while (current != null && current.Type == MondValueType.Object) { if (current.ObjectValue.Values.TryGetValue(name, out callable)) { // we should use the state from the metamethod's object state = current.ObjectValue._dispatcherState; break; } current = current.Prototype; } } if (callable == null) { result = MondValue.Undefined; return false; } state = state ?? _dispatcherState; if (state == null) throw new MondRuntimeException("MondValue must have an attached state to use metamethods"); result = state.Call(callable, args); return true; } } }
using System.Collections.Generic; namespace Mond.VirtualMachine { class Object { public readonly Dictionary<MondValue, MondValue> Values; public bool Locked; public MondValue Prototype; public object UserData; private MondState _dispatcherState; public MondState State { set { if (_dispatcherState == null) _dispatcherState = value; } } public Object() { Values = new Dictionary<MondValue, MondValue>(); Locked = false; Prototype = null; UserData = null; } public bool TryDispatch(string name, out MondValue result, params MondValue[] args) { MondState state = null; MondValue callable; var current = this; while (true) { if (current.Values.TryGetValue(name, out callable)) { // we need to use the state from the metamethod's object state = current._dispatcherState; break; } var currentValue = current.Prototype; if (currentValue == null || currentValue.Type != MondValueType.Object) break; current = currentValue.ObjectValue; } if (callable == null) { result = MondValue.Undefined; return false; } if (state == null) throw new MondRuntimeException("MondValue must have an attached state to use metamethods"); result = state.Call(callable, args); return true; } } }
Create doc store or embedded doc
using Raven.Client; using Raven.Client.Embedded; using fn = qed.Functions; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; using fn = qed.Functions; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; if (string.IsNullOrEmpty(GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey))) ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; else ravenStore = new DocumentStore { Url = GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey) }; ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
Extend NetworkingProxy to support listener socket endpoints besides "any".
using System.IO; using System.Net.Sockets; namespace ItzWarty.Networking { public interface INetworkingProxy { IConnectedSocket CreateConnectedSocket(string host, int port); IConnectedSocket CreateConnectedSocket(ITcpEndPoint endpoint); IListenerSocket CreateListenerSocket(int port); IConnectedSocket Accept(IListenerSocket listenerSocket); NetworkStream CreateNetworkStream(IConnectedSocket connectedSocket, bool ownsSocket = true); ITcpEndPoint CreateLoopbackEndPoint(int port); ITcpEndPoint CreateEndPoint(string host, int port); } }
using System.IO; using System.Net.Sockets; namespace ItzWarty.Networking { public interface INetworkingProxy { IConnectedSocket CreateConnectedSocket(string host, int port); IConnectedSocket CreateConnectedSocket(ITcpEndPoint endpoint); IListenerSocket CreateListenerSocket(int port); IListenerSocket CreateListenerSocket(ITcpEndPoint endpoint); IConnectedSocket Accept(IListenerSocket listenerSocket); NetworkStream CreateNetworkStream(IConnectedSocket connectedSocket, bool ownsSocket = true); ITcpEndPoint CreateLoopbackEndPoint(int port); ITcpEndPoint CreateAnyEndPoint(int port); ITcpEndPoint CreateEndPoint(string host, int port); } }
Print ffplay output to the console in debug builds
using System; using System.Diagnostics; using System.IO; namespace WebMConverter { class FFplay : Process { public string FFplayPath = Path.Combine(Environment.CurrentDirectory, "Binaries", "Win32", "ffplay.exe"); public FFplay(string argument) { this.StartInfo.FileName = FFplayPath; this.StartInfo.Arguments = argument; this.StartInfo.RedirectStandardInput = true; this.StartInfo.RedirectStandardOutput = true; this.StartInfo.RedirectStandardError = true; this.StartInfo.UseShellExecute = false; //Required to redirect IO streams this.StartInfo.CreateNoWindow = true; //Hide console this.EnableRaisingEvents = true; } new public void Start() { base.Start(); this.BeginErrorReadLine(); this.BeginOutputReadLine(); } } }
using System; using System.Diagnostics; using System.IO; namespace WebMConverter { class FFplay : Process { public string FFplayPath = Path.Combine(Environment.CurrentDirectory, "Binaries", "Win32", "ffplay.exe"); public FFplay(string argument) { this.StartInfo.FileName = FFplayPath; this.StartInfo.Arguments = argument; this.StartInfo.RedirectStandardInput = true; this.StartInfo.RedirectStandardOutput = true; this.StartInfo.RedirectStandardError = true; this.StartInfo.UseShellExecute = false; //Required to redirect IO streams this.StartInfo.CreateNoWindow = true; //Hide console this.EnableRaisingEvents = true; #if DEBUG OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); ErrorDataReceived += (sender, args) => Console.WriteLine(args.Data); #endif } new public void Start() { base.Start(); this.BeginErrorReadLine(); this.BeginOutputReadLine(); } } }
Make log4net appender render the log event (as zero log is rendering it, the comparison wouldn't be fair otherwise)
using System.Collections.Generic; using System.Threading; using log4net.Appender; using log4net.Core; namespace ZeroLog.Benchmarks { internal class Log4NetTestAppender : AppenderSkeleton { private readonly bool _captureLoggedMessages; private int _messageCount; private ManualResetEventSlim _signal; private int _messageCountTarget; public List<string> LoggedMessages { get; } = new List<string>(); public Log4NetTestAppender(bool captureLoggedMessages) { _captureLoggedMessages = captureLoggedMessages; } public ManualResetEventSlim SetMessageCountTarget(int expectedMessageCount) { _signal = new ManualResetEventSlim(false); _messageCount = 0; _messageCountTarget = expectedMessageCount; return _signal; } protected override void Append(LoggingEvent loggingEvent) { if (_captureLoggedMessages) LoggedMessages.Add(loggingEvent.ToString()); if (++_messageCount == _messageCountTarget) _signal.Set(); } } }
using System.Collections.Generic; using System.Threading; using log4net.Appender; using log4net.Core; namespace ZeroLog.Benchmarks { internal class Log4NetTestAppender : AppenderSkeleton { private readonly bool _captureLoggedMessages; private int _messageCount; private ManualResetEventSlim _signal; private int _messageCountTarget; public List<string> LoggedMessages { get; } = new List<string>(); public Log4NetTestAppender(bool captureLoggedMessages) { _captureLoggedMessages = captureLoggedMessages; } public ManualResetEventSlim SetMessageCountTarget(int expectedMessageCount) { _signal = new ManualResetEventSlim(false); _messageCount = 0; _messageCountTarget = expectedMessageCount; return _signal; } protected override void Append(LoggingEvent loggingEvent) { var formatted = loggingEvent.RenderedMessage; if (_captureLoggedMessages) LoggedMessages.Add(loggingEvent.ToString()); if (++_messageCount == _messageCountTarget) _signal.Set(); } } }
Update Console Program with a Condition - Rename GetRoleMessageTest to GetRoleMessageForAdminTest so it is more specific
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Training.CSharpWorkshop.Tests { [TestClass] public class ProgramTests { [Ignore] [TestMethod] public void IgnoreTest() { Assert.Fail(); } [TestMethod()] public void GetRoleMessageForAdminTest() { // Arrange var userName = "Andrew"; var expected = "Role: Admin."; // Act var actual = Program.GetRoleMessage(userName); // Assert Assert.AreEqual(expected, actual); } } }
Use chrome instead of chromium on Ubuntu
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Runtime.InteropServices; namespace Interop.FunctionalTests { public static class ChromeConstants { public static string ExecutablePath { get; } = ResolveChromeExecutablePath(); private static string ResolveChromeExecutablePath() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Google", "Chrome", "Application", "chrome.exe"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return Path.Combine("/usr", "bin", "chromium-browser"); } throw new PlatformNotSupportedException(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Runtime.InteropServices; namespace Interop.FunctionalTests { public static class ChromeConstants { public static string ExecutablePath { get; } = ResolveChromeExecutablePath(); private static string ResolveChromeExecutablePath() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Google", "Chrome", "Application", "chrome.exe"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return Path.Combine("/usr", "bin", "google-chrome"); } throw new PlatformNotSupportedException(); } } }
Add WebInvoke to demonstrate how to post.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; namespace DemoWcfRest { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class DemoService { // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) // To create an operation that returns XML, // add [WebGet(ResponseFormat=WebMessageFormat.Xml)], // and include the following line in the operation body: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] [WebGet(UriTemplate = "hi/{name}")] public string Hello(string name) { return string.Format("Hello, {0}", name); } // Add more operations here and mark them with [OperationContract] } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; namespace DemoWcfRest { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class DemoService { // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) // To create an operation that returns XML, // add [WebGet(ResponseFormat=WebMessageFormat.Xml)], // and include the following line in the operation body: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] [WebGet(UriTemplate = "hi/{name}")] public string Hello(string name) { return string.Format("Hello, {0}", name); } // Add more operations here and mark them with [OperationContract] [OperationContract] [WebInvoke(Method = "POST")] public void PostSample(string postBody) { // DO NOTHING } } }
Print MOTD in the screen only
using System.Collections.Concurrent; using LmpClient.Base; using LmpClient.Base.Interface; using LmpClient.Systems.Chat; using LmpCommon.Message.Data.Motd; using LmpCommon.Message.Interface; namespace LmpClient.Systems.Motd { public class MotdMessageHandler : SubSystem<MotdSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is MotdReplyMsgData msgData)) return; if (!string.IsNullOrEmpty(msgData.MessageOfTheDay)) { ChatSystem.Singleton.PrintToChat(msgData.MessageOfTheDay); LunaScreenMsg.PostScreenMessage(msgData.MessageOfTheDay, 30f, ScreenMessageStyle.UPPER_CENTER); } } } }
using LmpClient.Base; using LmpClient.Base.Interface; using LmpCommon.Message.Data.Motd; using LmpCommon.Message.Interface; using System.Collections.Concurrent; namespace LmpClient.Systems.Motd { public class MotdMessageHandler : SubSystem<MotdSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is MotdReplyMsgData msgData)) return; if (!string.IsNullOrEmpty(msgData.MessageOfTheDay)) { LunaScreenMsg.PostScreenMessage(msgData.MessageOfTheDay, 30f, ScreenMessageStyle.UPPER_CENTER); } } } }
Make planet update dependent components.
using UnityEngine; public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public float Volume { get { return 4 / 3 * Mathf.PI * Radius * Radius * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } }
using UnityEngine; [ExecuteInEditMode] public class Planet : MonoBehaviour { [SerializeField] private float _radius; public float Radius { get { return _radius; } set { _radius = value; } } public float Permieter { get { return 2 * Mathf.PI * Radius; } } public float Volume { get { return 4 / 3 * Mathf.PI * Radius * Radius * Radius; } } public void SampleOrbit2D( float angle, float distance, out Vector3 position, out Vector3 normal ) { // Polar to cartesian coordinates float x = Mathf.Cos( angle ) * distance; float y = Mathf.Sin( angle ) * distance; Vector3 dispalcement = new Vector3( x, 0, y ); Vector3 center = transform.position; position = center + dispalcement; normal = dispalcement.normalized; } #if UNITY_EDITOR private void Update() { if( Application.isPlaying ) { return; } var sphereColider = GetComponent<SphereCollider>(); if( sphereColider ) { sphereColider.radius = Radius; } var model = transform.FindChild( "Model" ); if( model ) { model.localScale = Vector3.one * Radius * 2; } } #endif }
Remove logs link, never worked right
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IO; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IO; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } } }
Fix incorrect formatting of time stamps
using Newtonsoft.Json; using Swashbuckle.Swagger; using System; using System.Globalization; using System.Linq; using System.Reflection; using Zinc.Json; namespace Zinc.WebServices { /// <summary /> public class ZincSchemaFilter : ISchemaFilter { /// <summary /> public void Apply( Schema schema, SchemaRegistry schemaRegistry, Type type ) { #region Validations if ( schema == null ) throw new ArgumentNullException( nameof( schema ) ); if ( type == null ) throw new ArgumentNullException( nameof( type ) ); #endregion var properties = type.GetProperties() .Where( prop => prop.PropertyType == typeof( DateTime ) && prop.GetCustomAttribute<JsonConverterAttribute>() != null ); foreach ( var prop in properties ) { var conv = prop.GetCustomAttribute<JsonConverterAttribute>(); var propSchema = schema.properties[ prop.Name ]; if ( conv.ConverterType == typeof( DateConverter ) || conv.ConverterType == typeof( NullableDateConverter ) ) { propSchema.format = "date"; propSchema.example = DateTime.UtcNow.ToString( "yyyy-MM-dd", CultureInfo.InvariantCulture ); } if ( conv.ConverterType == typeof( TimeConverter ) || conv.ConverterType == typeof( NullableTimeConverter ) ) { propSchema.format = "time"; propSchema.example = DateTime.UtcNow.ToString( "hh:mm:ss", CultureInfo.InvariantCulture ); } } } } }
using Newtonsoft.Json; using Swashbuckle.Swagger; using System; using System.Globalization; using System.Linq; using System.Reflection; using Zinc.Json; namespace Zinc.WebServices { /// <summary /> public class ZincSchemaFilter : ISchemaFilter { /// <summary /> public void Apply( Schema schema, SchemaRegistry schemaRegistry, Type type ) { #region Validations if ( schema == null ) throw new ArgumentNullException( nameof( schema ) ); if ( type == null ) throw new ArgumentNullException( nameof( type ) ); #endregion var properties = type.GetProperties() .Where( prop => prop.PropertyType == typeof( DateTime ) && prop.GetCustomAttribute<JsonConverterAttribute>() != null ); foreach ( var prop in properties ) { var conv = prop.GetCustomAttribute<JsonConverterAttribute>(); var propSchema = schema.properties[ prop.Name ]; if ( conv.ConverterType == typeof( DateConverter ) || conv.ConverterType == typeof( NullableDateConverter ) ) { propSchema.format = "date"; propSchema.example = DateTime.UtcNow.ToString( "yyyy-MM-dd", CultureInfo.InvariantCulture ); } if ( conv.ConverterType == typeof( TimeConverter ) || conv.ConverterType == typeof( NullableTimeConverter ) ) { propSchema.format = "time"; propSchema.example = DateTime.UtcNow.ToString( "HH:mm:ss", CultureInfo.InvariantCulture ); } } } } }
Change Russian to Русский for the language selector
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Wox.Core.i18n { internal static class AvailableLanguages { public static Language English = new Language("en", "English"); public static Language Chinese = new Language("zh-cn", "中文"); public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)"); public static Language Russian = new Language("ru", "Russian"); public static List<Language> GetAvailableLanguages() { List<Language> languages = new List<Language> { English, Chinese, Chinese_TW, Russian, }; return languages; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Wox.Core.i18n { internal static class AvailableLanguages { public static Language English = new Language("en", "English"); public static Language Chinese = new Language("zh-cn", "中文"); public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)"); public static Language Russian = new Language("ru", "Русский"); public static List<Language> GetAvailableLanguages() { List<Language> languages = new List<Language> { English, Chinese, Chinese_TW, Russian, }; return languages; } } }
Rename params to match convention
using System.Collections.Generic; namespace CefSharp { public interface IDialogHandler { bool OnOpenFile(IWebBrowser browser, string title, string default_file_name, List<string> accept_types, out List<string> result); } }
using System.Collections.Generic; namespace CefSharp { public interface IDialogHandler { bool OnOpenFile(IWebBrowser browser, string title, string defaultFileName, List<string> acceptTypes, out List<string> result); } }
Add datetime prefix to dumped file name if texture didn't have name
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using ColossalFramework.Plugins; using ICities; namespace ModTools { public static class FileUtil { public static List<string> ListFilesInDirectory(string path, List<string> _filesMustBeNull = null) { _filesMustBeNull = _filesMustBeNull ?? new List<string>(); foreach (string file in Directory.GetFiles(path)) { _filesMustBeNull.Add(file); } return _filesMustBeNull; } public static string FindPluginPath(Type type) { var pluginManager = PluginManager.instance; var plugins = pluginManager.GetPluginsInfo(); foreach (var item in plugins) { var instances = item.GetInstances<IUserMod>(); var instance = instances.FirstOrDefault(); if (instance != null && instance.GetType() != type) { continue; } foreach (var file in Directory.GetFiles(item.modPath)) { if (Path.GetExtension(file) == ".dll") { return file; } } } throw new Exception("Failed to find assembly!"); } public static string LegalizeFileName(this string illegal) { var regexSearch = new string(Path.GetInvalidFileNameChars()/* + new string(Path.GetInvalidPathChars()*/); var r = new Regex($"[{Regex.Escape(regexSearch)}]"); return r.Replace(illegal, "_"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using ColossalFramework.Plugins; using ICities; namespace ModTools { public static class FileUtil { public static List<string> ListFilesInDirectory(string path, List<string> _filesMustBeNull = null) { _filesMustBeNull = _filesMustBeNull ?? new List<string>(); foreach (string file in Directory.GetFiles(path)) { _filesMustBeNull.Add(file); } return _filesMustBeNull; } public static string FindPluginPath(Type type) { var pluginManager = PluginManager.instance; var plugins = pluginManager.GetPluginsInfo(); foreach (var item in plugins) { var instances = item.GetInstances<IUserMod>(); var instance = instances.FirstOrDefault(); if (instance != null && instance.GetType() != type) { continue; } foreach (var file in Directory.GetFiles(item.modPath)) { if (Path.GetExtension(file) == ".dll") { return file; } } } throw new Exception("Failed to find assembly!"); } public static string LegalizeFileName(this string illegal) { if (string.IsNullOrEmpty(illegal)) { return DateTime.Now.ToString("yyyyMMddhhmmss"); } var regexSearch = new string(Path.GetInvalidFileNameChars()/* + new string(Path.GetInvalidPathChars()*/); var r = new Regex($"[{Regex.Escape(regexSearch)}]"); return r.Replace(illegal, "_"); } } }
Add a diagnostic tool for myself.
//using UnityEditor; //using UnityEngine; //using System.Collections; using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
#define DEBUG_COMMANDS //using UnityEditor; //using UnityEngine; //using System.Collections; using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { #if DEBUG_COMMANDS UnityEngine.Debug.Log("Running: " + filename + " " + arguments); #endif Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
Make the "type" attribute available from GenerateScript
using System.Collections.Generic; namespace MR.AspNet.Deps { public class OutputHelper { private List<Element> _elements = new List<Element>(); public void Add(Element element) { _elements.Add(element); } public void Add(List<Element> elements) { _elements.AddRange(elements); } public List<Element> Elements { get { return _elements; } } } public static class OutputHelperExtensions { public static void GenerateLink(this OutputHelper @this, string href) { var e = new Element("link", ClosingTagKind.None); e.Attributes.Add(new ElementAttribute("rel", "stylesheet")); e.Attributes.Add(new ElementAttribute("href", href)); @this.Add(e); } public static void GenerateScript(this OutputHelper @this, string src) { var e = new Element("script", ClosingTagKind.Normal); e.Attributes.Add(new ElementAttribute("src", src)); @this.Add(e); } } }
using System.Collections.Generic; namespace MR.AspNet.Deps { public class OutputHelper { private List<Element> _elements = new List<Element>(); public void Add(Element element) { _elements.Add(element); } public void Add(List<Element> elements) { _elements.AddRange(elements); } public List<Element> Elements { get { return _elements; } } } public static class OutputHelperExtensions { /// <summary> /// Generates a &lt;link &gt; tag. /// </summary> public static void GenerateLink(this OutputHelper @this, string href) { var e = new Element("link", ClosingTagKind.None); e.Attributes.Add(new ElementAttribute("rel", "stylesheet")); e.Attributes.Add(new ElementAttribute("href", href)); @this.Add(e); } /// <summary> /// Generates a &lt;script&gt;&lt;/script&gt; tag. /// </summary> public static void GenerateScript(this OutputHelper @this, string src, string type = null) { var e = new Element("script", ClosingTagKind.Normal); e.Attributes.Add(new ElementAttribute("src", src)); if (type != null) { e.Attributes.Add(new ElementAttribute("type", type)); } @this.Add(e); } } }
Update resource to handle message strings
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Glimpse.Server.Web { public class MessageHistoryResource : IResource { private readonly InMemoryStorage _store; private readonly JsonSerializer _jsonSerializer; public MessageHistoryResource(IStorage storage, JsonSerializer jsonSerializer) { // TODO: This hack is needed to get around signalr problem jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // TODO: Really shouldn't be here _store = (InMemoryStorage)storage; _jsonSerializer = jsonSerializer; } public async Task Invoke(HttpContext context, IDictionary<string, string> parameters) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "application/json"; var list = _store.Query(null); var output = _jsonSerializer.Serialize(list); await response.WriteAsync(output); } public string Name => "MessageHistory"; public ResourceParameters Parameters => null; } }
using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Net.Http.Headers; namespace Glimpse.Server.Web { public class MessageHistoryResource : IResource { private readonly InMemoryStorage _store; public MessageHistoryResource(IStorage storage) { // TODO: Really shouldn't be here _store = (InMemoryStorage)storage; } public async Task Invoke(HttpContext context, IDictionary<string, string> parameters) { var response = context.Response; response.Headers[HeaderNames.ContentType] = "application/json"; var list = await _store.Query(null); var sb = new StringBuilder("["); sb.Append(string.Join(",", list)); sb.Append("]"); var output = sb.ToString(); await response.WriteAsync(output); } public string Name => "MessageHistory"; public ResourceParameters Parameters => null; } }
Fix connection bug to PGSQL
using System.Data.Common; using System.Management.Automation; using Npgsql; namespace InvokeQuery { [Cmdlet("Invoke", "PostgreSqlQuery", SupportsTransactions = true, SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)] public class InvokePostgreSqlQuery : InvokeQueryBase { protected override DbProviderFactory GetProviderFactory() { return NpgsqlFactory.Instance; } } }
using Npgsql; using System.Data.Common; using System.Management.Automation; namespace InvokeQuery { [Cmdlet("Invoke", "PostgreSqlQuery", SupportsTransactions = true, SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)] public class InvokePostgreSqlQuery : InvokeQueryBase { protected override DbProviderFactory GetProviderFactory() { return NpgsqlFactory.Instance; } protected override void ConfigureConnectionString() { if (!string.IsNullOrEmpty(ConnectionString)) return; var connString = new NpgsqlConnectionStringBuilder(); connString.Host = Server; if (!string.IsNullOrEmpty(Database)) { connString.Database = Database; } if (Credential != PSCredential.Empty) { connString.Username = Credential.UserName; connString.Password = Credential.Password.ConvertToUnsecureString(); } if (ConnectionTimeout > 0) { connString.Timeout = ConnectionTimeout; } ConnectionString = connString.ToString(); } } }
Clear console before game starts
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var wordGenerator = new RandomWord(); var word = wordGenerator.Word(); var game = new Game(word); var width = Math.Min(81, Console.WindowWidth); string titleText; int spacing; if (width >= 81) { titleText = File.ReadAllText("title_long.txt"); spacing = 2; } else if (width >= 48) { titleText = File.ReadAllText("title_short.txt"); spacing = 1; } else { titleText = "Hangman"; spacing = 1; } while (game.IsPlaying()) { var table = HangmanTable.Build( word, titleText, game, width, spacing ); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; game.GuessLetter(Char.ToUpper(key)); Console.Clear(); } // After the game Console.WriteLine(game.Status); Console.WriteLine("The word was \"{0}\".", word); } } }
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var wordGenerator = new RandomWord(); var word = wordGenerator.Word(); var game = new Game(word); var width = Math.Min(81, Console.WindowWidth); string titleText; int spacing; if (width >= 81) { titleText = File.ReadAllText("title_long.txt"); spacing = 2; } else if (width >= 48) { titleText = File.ReadAllText("title_short.txt"); spacing = 1; } else { titleText = "Hangman"; spacing = 1; } while (game.IsPlaying()) { var table = HangmanTable.Build( word, titleText, game, width, spacing ); var tableOutput = table.Draw(); Console.Clear(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; game.GuessLetter(Char.ToUpper(key)); } // After the game Console.Clear(); Console.WriteLine(game.Status); Console.WriteLine("The word was \"{0}\".", word); } } }
Fix using private constructor on MessagePack object
// 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 MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> [Key(1)] public readonly float? DownloadProgress; [JsonConstructor] private BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
// 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 MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> [Key(1)] public readonly float? DownloadProgress; [JsonConstructor] public BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
Fix Basic tests (angularjs.org site has been updated)
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Chrome; namespace Protractor.Samples.Basic { [TestFixture] public class BasicTests { private IWebDriver driver; [SetUp] public void SetUp() { // Using NuGet Package 'PhantomJS' driver = new PhantomJSDriver(); // Using NuGet Package 'WebDriver.ChromeDriver.win32' //driver = new ChromeDriver(); driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5)); } [TearDown] public void TearDown() { driver.Quit(); } [Test] public void ShouldGreetUsingBinding() { IWebDriver ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); ngDriver.FindElement(NgBy.Model("yourName")).SendKeys("Julie"); Assert.AreEqual("Hello Julie!", ngDriver.FindElement(NgBy.Binding("yourName")).Text); } [Test] public void ShouldListTodos() { var ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); var elements = ngDriver.FindElements(NgBy.Repeater("todo in todos")); Assert.AreEqual("build an angular app", elements[1].Text); Assert.AreEqual(false, elements[1].Evaluate("todo.done")); } } }
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Chrome; namespace Protractor.Samples.Basic { [TestFixture] public class BasicTests { private IWebDriver driver; [SetUp] public void SetUp() { // Using NuGet Package 'PhantomJS' driver = new PhantomJSDriver(); // Using NuGet Package 'WebDriver.ChromeDriver.win32' //driver = new ChromeDriver(); driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5)); } [TearDown] public void TearDown() { driver.Quit(); } [Test] public void ShouldGreetUsingBinding() { IWebDriver ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); ngDriver.FindElement(NgBy.Model("yourName")).SendKeys("Julie"); Assert.AreEqual("Hello Julie!", ngDriver.FindElement(NgBy.Binding("yourName")).Text); } [Test] public void ShouldListTodos() { var ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); var elements = ngDriver.FindElements(NgBy.Repeater("todo in todoList.todos")); Assert.AreEqual("build an angular app", elements[1].Text); Assert.AreEqual(false, elements[1].Evaluate("todo.done")); } } }
Print the texts of each row
using System; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { return "Hello World"; } } }
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { List<string> rowTexts = new List<string>(); foreach (var row in Rows) { rowTexts.Add(row.Text); } return String.Join("\n", rowTexts); } } }
Make Razor the only ViewEngine
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 MotivateMe.Web { 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; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MotivateMe.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
Add missing EmitCloseList to backend
// // IMarkdownViewBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. using System; namespace Xwt.Backends { [Flags] enum MarkdownInlineStyle { Italic, Bold, Monospace } public interface IMarkdownViewBackend : IWidgetBackend { object CreateBuffer (); // Emit unstyled text void EmitText (object buffer, string text); // Emit a header (h1, h2, ...) void EmitHeader (object buffer, string title, int level); // What's outputed afterwards will be a in new paragrapgh void EmitNewParagraph (object buffer); // Emit a list // Chain is: // open-list, open-bullet, <above methods>, close-bullet, close-list void EmitOpenList (object buffer); void EmitOpenBullet (object buffer); void EmitCloseBullet (object buffet); // Emit a link displaying text and opening the href URL void EmitLink (object buffer, string href, string text); // Emit code in a preformated blockquote void EmitCodeBlock (object buffer, string code); // Display the passed buffer void SetBuffer (object buffer); } }
// // IMarkdownViewBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. using System; namespace Xwt.Backends { [Flags] enum MarkdownInlineStyle { Italic, Bold, Monospace } public interface IMarkdownViewBackend : IWidgetBackend { object CreateBuffer (); // Emit unstyled text void EmitText (object buffer, string text); // Emit a header (h1, h2, ...) void EmitHeader (object buffer, string title, int level); // What's outputed afterwards will be a in new paragrapgh void EmitNewParagraph (object buffer); // Emit a list // Chain is: // open-list, open-bullet, <above methods>, close-bullet, close-list void EmitOpenList (object buffer); void EmitOpenBullet (object buffer); void EmitCloseBullet (object buffet); void EmitCloseList (object buffer); // Emit a link displaying text and opening the href URL void EmitLink (object buffer, string href, string text); // Emit code in a preformated blockquote void EmitCodeBlock (object buffer, string code); // Display the passed buffer void SetBuffer (object buffer); } }
Update the Empty module template.
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName); var installModel = new InstallModel(); Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext); moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer; moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName; moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password; ModuleInfo.Save(moduleInfo); // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
Fix DisposeValueIfCreated to be extension method
using System; namespace OpenMagic.Extensions { public static class LazyExtensions { public static void DisposeValueIfCreated<T>(Lazy<T> obj) where T : IDisposable { if (obj.IsValueCreated) { obj.Value.Dispose(); } } } }
using System; namespace OpenMagic.Extensions { public static class LazyExtensions { public static void DisposeValueIfCreated<T>(this Lazy<T> obj) where T : IDisposable { if (obj.IsValueCreated) { obj.Value.Dispose(); } } } }
Test that 'true' unifies correctly
using LogicalShift.Reason.Api; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Tests { [TestFixture] public class Truthiness { [Test] public void TrueIsTrue() { Assert.IsTrue(Equals(Literal.True(), Literal.True())); } [Test] public void TrueHashesToSelf() { var dict = new Dictionary<ILiteral, bool>(); dict[Literal.True()] = true; Assert.IsTrue(dict[Literal.True()]); } } }
using LogicalShift.Reason.Api; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Tests { [TestFixture] public class Truthiness { [Test] public void TrueIsTrue() { Assert.IsTrue(Equals(Literal.True(), Literal.True())); } [Test] public void TrueHashesToSelf() { var dict = new Dictionary<ILiteral, bool>(); dict[Literal.True()] = true; Assert.IsTrue(dict[Literal.True()]); } [Test] public void TrueUnifiesWithSelf() { var truthiness = Literal.True(); Assert.AreEqual(1, truthiness.Unify(truthiness).Count()); } [Test] public void TrueDoesNotUnifyWithDifferentAtom() { var truthiness = Literal.True(); var otherAtom = Literal.NewAtom(); Assert.AreEqual(0, truthiness.Unify(otherAtom).Count()); } } }
Fix test to run with the NUnitLite in our Integration Tests on IOS
using NUnit.Framework; using RealmNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IntegrationTests.Shared { [TestFixture] public class StandAloneObjectTests { private Person _person; [SetUp] public void SetUp() { _person = new Person(); } [Test] public void PropertyGet() { string firstName = null; Assert.DoesNotThrow(() => firstName = _person.FirstName); Assert.IsNullOrEmpty(firstName); } [Test] public void PropertySet() { const string name = "John"; Assert.DoesNotThrow(() => _person.FirstName = name); Assert.AreEqual(name, _person.FirstName); } [Test] public void AddToRealm() { _person.FirstName = "Arthur"; _person.LastName = "Dent"; _person.IsInteresting = true; using (var realm = Realm.GetInstance(Path.GetTempFileName())) { using (var transaction = realm.BeginWrite()) { realm.Add(_person); transaction.Commit(); } Assert.That(_person.IsManaged); var p = realm.All<Person>().ToList().Single(); Assert.That(p.FirstName, Is.EqualTo("Arthur")); Assert.That(p.LastName, Is.EqualTo("Dent")); Assert.That(p.IsInteresting); } } } }
using NUnit.Framework; using RealmNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IntegrationTests.Shared { [TestFixture] public class StandAloneObjectTests { private Person _person; [SetUp] public void SetUp() { _person = new Person(); } [Test] public void PropertyGet() { string firstName = null; Assert.DoesNotThrow(() => firstName = _person.FirstName); Assert.That(string.IsNullOrEmpty(firstName)); } [Test] public void PropertySet() { const string name = "John"; Assert.DoesNotThrow(() => _person.FirstName = name); Assert.AreEqual(name, _person.FirstName); } [Test] public void AddToRealm() { _person.FirstName = "Arthur"; _person.LastName = "Dent"; _person.IsInteresting = true; using (var realm = Realm.GetInstance(Path.GetTempFileName())) { using (var transaction = realm.BeginWrite()) { realm.Add(_person); transaction.Commit(); } Assert.That(_person.IsManaged); var p = realm.All<Person>().ToList().Single(); Assert.That(p.FirstName, Is.EqualTo("Arthur")); Assert.That(p.LastName, Is.EqualTo("Dent")); Assert.That(p.IsInteresting); } } } }
Move OpenFileDialog initialization inside try block
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Core2D.Wpf.Windows; using Microsoft.Win32; namespace Core2D.Wpf.Importers { /// <summary> /// File image importer. /// </summary> public class FileImageImporter : IImageImporter { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="FileImageImporter"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public FileImageImporter(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<string> GetImageKeyAsync() { var dlg = new OpenFileDialog() { Filter = "All (*.*)|*.*", FilterIndex = 0, FileName = "" }; if (dlg.ShowDialog(_serviceProvider.GetService<MainWindow>()) == true) { try { var path = dlg.FileName; var bytes = System.IO.File.ReadAllBytes(path); var key = _serviceProvider.GetService<ProjectEditor>().Project.AddImageFromFile(path, bytes); return await Task.Run(() => key); } catch (Exception ex) { _serviceProvider.GetService<ILog>().LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}"); } } return null; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Core2D.Wpf.Windows; using Microsoft.Win32; namespace Core2D.Wpf.Importers { /// <summary> /// File image importer. /// </summary> public class FileImageImporter : IImageImporter { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="FileImageImporter"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public FileImageImporter(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<string> GetImageKeyAsync() { try { var dlg = new OpenFileDialog() { Filter = "All (*.*)|*.*", FilterIndex = 0, FileName = "" }; if (dlg.ShowDialog(_serviceProvider.GetService<MainWindow>()) == true) { var path = dlg.FileName; var bytes = System.IO.File.ReadAllBytes(path); var key = _serviceProvider.GetService<ProjectEditor>().Project.AddImageFromFile(path, bytes); return await Task.Run(() => key); } } catch (Exception ex) { _serviceProvider.GetService<ILog>().LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}"); } return null; } } }
Add license to new file
using System; namespace Huxley.Models { public class DelaysResponse { public DateTime GeneratedAt { get; set; } public string LocationName { get; set; } public string Crs { get; set; } public string FilterLocationName { get; set; } // Yes this is a typo but it matches StationBoard public string Filtercrs { get; set; } public bool Delays { get; set; } public int TotalTrainsDelayed { get; set; } public int TotalDelayMinutes { get; set; } public int TotalTrains { get; set; } } }
/* Huxley - a JSON proxy for the UK National Rail Live Departure Board SOAP API Copyright (C) 2015 James Singleton * http://huxley.unop.uk * https://github.com/jpsingleton/Huxley This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace Huxley.Models { public class DelaysResponse { public DateTime GeneratedAt { get; set; } public string LocationName { get; set; } public string Crs { get; set; } public string FilterLocationName { get; set; } // Yes this is a typo but it matches StationBoard public string Filtercrs { get; set; } public bool Delays { get; set; } public int TotalTrainsDelayed { get; set; } public int TotalDelayMinutes { get; set; } public int TotalTrains { get; set; } } }
Update SkillController.cs - add "Edit" action - add "GetSkillByIdQueryHandler"
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class SkillsController : Controller { private readonly IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler; private readonly ICommandHandler<AddSkillCommand> addSkillCommandHandler; public SkillsController(IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler, ICommandHandler<AddSkillCommand> addSkillCommandHandler) { this.skillsQueryHandler = skillsQueryHandler; this.addSkillCommandHandler = addSkillCommandHandler; } // GET: Skills public ActionResult Index() { var skills = this.skillsQueryHandler.Handle(new GetAllSkillsQuery()); return View(skills); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Skill skill) { skill.Id = Guid.NewGuid(); var command = new AddSkillCommand { Skill = skill, }; this.addSkillCommandHandler.Handle(command); var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } } }
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class SkillsController : Controller { private readonly IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler; private readonly ICommandHandler<AddSkillCommand> addSkillCommandHandler; private readonly IQueryHandler<GetSkillByIdQuery, Skill> getSkillByIdCommandHandler; public SkillsController(IQueryHandler<GetAllSkillsQuery, Skill[]> skillsQueryHandler, ICommandHandler<AddSkillCommand> addSkillCommandHandler, IQueryHandler<GetSkillByIdQuery, Skill> getSkillByIdCommandHandler) { this.skillsQueryHandler = skillsQueryHandler; this.addSkillCommandHandler = addSkillCommandHandler; this.getSkillByIdCommandHandler = getSkillByIdCommandHandler; } // GET: Skills public ActionResult Index() { var skills = this.skillsQueryHandler.Handle(new GetAllSkillsQuery()); return View(skills); } public ActionResult Create() { return View(); } public ActionResult Edit(Guid skillId) { var skill = this.getSkillByIdCommandHandler.Handle(new GetSkillByIdQuery { SkillId = skillId }); return View(skill); } [HttpPost] public ActionResult Create(Skill skill) { skill.Id = Guid.NewGuid(); var command = new AddSkillCommand { Skill = skill, }; this.addSkillCommandHandler.Handle(command); var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } } }
Add methods to get the overriden values, or use a default value if not overridden. Make them extension methods so that we can call them on null objects.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public class Overrides { public LightingData? Lighting; public IMaterial Material; public IShaderProgram ShaderProgram; public IShaderStage VertexShader; public IShaderStage FragmentShader; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChamberLib { public class Overrides { public LightingData? Lighting; public IMaterial Material; public IShaderProgram ShaderProgram; public IShaderStage VertexShader; public IShaderStage FragmentShader; } public static class OverridesHelper { public static LightingData? GetLighting(this Overrides overrides, LightingData? defaultValue) { if (overrides == null) return defaultValue; return overrides.Lighting ?? defaultValue; } public static IMaterial GetMaterial(this Overrides overrides, IMaterial defaultValue) { if (overrides == null) return defaultValue; return overrides.Material ?? defaultValue; } public static IShaderProgram GetShaderProgram(this Overrides overrides, IShaderProgram defaultValue) { if (overrides == null) return defaultValue; return overrides.ShaderProgram ?? defaultValue; } public static IShaderStage GetVertexShader(this Overrides overrides, IShaderStage defaultValue) { if (overrides == null) return defaultValue; return overrides.VertexShader ?? defaultValue; } public static IShaderStage GetFragmentShader(this Overrides overrides, IShaderStage defaultValue) { if (overrides == null) return defaultValue; return overrides.FragmentShader ?? defaultValue; } } }
Make cursor test scene more automated
// 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.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Osu.UI.Cursor; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneGameplayCursor : SkinnableTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CursorTrail) }; [BackgroundDependencyLoader] private void load() { SetContents(() => new OsuCursorContainer { RelativeSizeAxes = Axes.Both, Masking = true, }); } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing.Input; using osu.Game.Rulesets.Osu.UI.Cursor; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class TestSceneGameplayCursor : SkinnableTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CursorTrail) }; [BackgroundDependencyLoader] private void load() { SetContents(() => new MovingCursorInputManager { Child = new OsuCursorContainer { RelativeSizeAxes = Axes.Both, Masking = true, } }); } private class MovingCursorInputManager : ManualInputManager { public MovingCursorInputManager() { UseParentInput = false; } protected override void Update() { base.Update(); const double spin_duration = 5000; double currentTime = Time.Current; double angle = (currentTime % spin_duration) / spin_duration * 2 * Math.PI; Vector2 rPos = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); MoveMouseTo(ToScreenSpace(DrawSize / 2 + DrawSize / 3 * rPos)); } } } }
Add Version string to package for support for yaml script
using System; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace CopyAsPathCommand { [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [InstalledProductRegistration(CopyAsPathCommandPackage.ProductName, CopyAsPathCommandPackage.ProductDescription, "1.0")] [Guid(CopyAsPathCommandPackage.PackageGuidString)] [ProvideAutoLoad(UIContextGuids.SolutionExists)] [ProvideOptionPage(typeof(OptionsPage), "Environment", "Copy as Path Command", 0, 0, true)] public sealed class CopyAsPathCommandPackage : Package { public const string ProductName = "Copy as path command"; public const string ProductDescription = "Right click on a solution explorer item and get its absolute path."; public const string PackageGuidString = "d40a488d-23d0-44cc-99fb-f6dd0717ab7d"; #region Package Members protected override void Initialize() { DTE2 envDte = this.GetService(typeof(DTE)) as DTE2; UIHierarchy solutionWindow = envDte.ToolWindows.SolutionExplorer; CopyAsPathCommand.Initialize(this, solutionWindow); base.Initialize(); } #endregion } }
using System; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace CopyAsPathCommand { [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [InstalledProductRegistration(CopyAsPathCommandPackage.ProductName, CopyAsPathCommandPackage.ProductDescription, CopyAsPathCommandPackage.Version)] [Guid(CopyAsPathCommandPackage.PackageGuidString)] [ProvideAutoLoad(UIContextGuids.SolutionExists)] [ProvideOptionPage(typeof(OptionsPage), "Environment", "Copy as Path Command", 0, 0, true)] public sealed class CopyAsPathCommandPackage : Package { public const string Version = "1.0.6"; public const string ProductName = "Copy as path command"; public const string ProductDescription = "Right click on a solution explorer item and get its absolute path."; public const string PackageGuidString = "d40a488d-23d0-44cc-99fb-f6dd0717ab7d"; #region Package Members protected override void Initialize() { DTE2 envDte = this.GetService(typeof(DTE)) as DTE2; UIHierarchy solutionWindow = envDte.ToolWindows.SolutionExplorer; CopyAsPathCommand.Initialize(this, solutionWindow); base.Initialize(); } #endregion } }
Change PropertyAsObservable to return a BehaviorSubject
namespace Mappy { using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; public static class ExtensionMethods { public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged { var obs = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( x => source.PropertyChanged += x, x => source.PropertyChanged -= x) .Where(x => x.EventArgs.PropertyName == name) .Select(_ => accessor(source)) .Multicast(new BehaviorSubject<TField>(accessor(source))); // FIXME: This is leaky. // We create a connection here but don't hold on to the reference. // We can never unregister our event handler without this. obs.Connect(); return obs; } } }
namespace Mappy { using System; using System.ComponentModel; using System.Reactive.Linq; using System.Reactive.Subjects; public static class ExtensionMethods { public static BehaviorSubject<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged { var subject = new BehaviorSubject<TField>(accessor(source)); // FIXME: This is leaky. // We create a subscription here but don't hold on to the reference. // We can never unregister our event handler without this. Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( x => source.PropertyChanged += x, x => source.PropertyChanged -= x) .Where(x => x.EventArgs.PropertyName == name) .Select(_ => accessor(source)) .Subscribe(subject); return subject; } } }
Use flag instead of `StreamWriter` changes
// 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.IO; namespace osu.Framework.Platform { /// <summary> /// A <see cref="FileStream"/> which always flushes to disk on disposal. /// </summary> /// <remarks> /// This adds a considerable overhead, but is required to avoid files being potentially written to disk in a corrupt state. /// See https://stackoverflow.com/questions/49260358/what-could-cause-an-xml-file-to-be-filled-with-null-characters/52751216#52751216. /// </remarks> public class FlushingStream : FileStream { public FlushingStream(string path, FileMode mode, FileAccess access) : base(path, mode, access) { } protected override void Dispose(bool disposing) { try { Flush(true); } catch { // on some platforms, may fail due to the stream already being closed, or never being opened. // we don't really care about such failures. } base.Dispose(disposing); } } }
// 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.IO; namespace osu.Framework.Platform { /// <summary> /// A <see cref="FileStream"/> which always flushes to disk on disposal. /// </summary> /// <remarks> /// This adds a considerable overhead, but is required to avoid files being potentially written to disk in a corrupt state. /// See https://stackoverflow.com/questions/49260358/what-could-cause-an-xml-file-to-be-filled-with-null-characters/52751216#52751216. /// </remarks> public class FlushingStream : FileStream { public FlushingStream(string path, FileMode mode, FileAccess access) : base(path, mode, access) { } private bool finalFlushRun; protected override void Dispose(bool disposing) { // dispose may be called more than once. without this check Flush will throw on an already-closed stream. if (!finalFlushRun) { finalFlushRun = true; try { Flush(true); } catch { // on some platforms, may fail due to a lower level file access issue. // we don't want to throw in disposal though. } } base.Dispose(disposing); } } }
Update the assembly information to add the right owners to the package.
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("OAuth.net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OAuth.net")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("53713a6f-04fb-46ff-954b-366a7ce12eb0")] // 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("OAuth.net")] [assembly: AssemblyDescription("OAuth authenticator implementation")] [assembly: AssemblyProduct("OAuth.net")] [assembly: AssemblyCopyright("Copyright © Alex Ghiondea 2015")] // 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("53713a6f-04fb-46ff-954b-366a7ce12eb0")] // 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")]
Update tests for loose mode
using System; using Xunit; using Xunit.Extensions; namespace SemVer.Tests { public class LooseMode { [Theory] [InlineData("=1.2.3", "1.2.3")] [InlineData("v 1.2.3", "1.2.3")] [InlineData("1.2.3alpha", "1.2.3-alpha")] // SemVer spec is ambiguous about whether 01 in a prerelease identifier // means the identifier is invalid or must be treated as alphanumeric, // but consensus seems to be that it is invalid (this is the behaviour of node-semver). [InlineData("1.2.3-01", "1.2.3-1")] public void Versions(string looseVersionString, string strictVersionString) { var looseVersion = new Version(looseVersionString); // Loose version is equivalent to strict version var strictVersion = new Version(strictVersionString); Assert.Equal(strictVersion, looseVersion); // Loose version should be invalid in strict mode Assert.Throws<ArgumentException>(() => new Version(looseVersionString)); } [Theory] [InlineData(">=1.2.3", "=1.2.3")] public void Ranges(string rangeString, string versionString) { var range = new Range(rangeString); // Version doesn't satisfy range in strict mode Assert.False(range.IsSatisfied(versionString)); // Version satisfies range in loose mode Assert.True(range.IsSatisfied(versionString, true)); } } }
using System; using Xunit; using Xunit.Extensions; namespace SemVer.Tests { public class LooseMode { [Theory] [InlineData("=1.2.3", "1.2.3")] [InlineData("v 1.2.3", "1.2.3")] [InlineData("1.2.3alpha", "1.2.3-alpha")] // SemVer spec is ambiguous about whether 01 in a prerelease identifier // means the identifier is invalid or must be treated as alphanumeric, // but consensus seems to be that it is invalid (this is the behaviour of node-semver). [InlineData("1.2.3-01", "1.2.3-1")] public void Versions(string looseVersionString, string strictVersionString) { var looseVersion = new Version(looseVersionString, true); // Loose version is equivalent to strict version var strictVersion = new Version(strictVersionString); Assert.Equal(strictVersion.Clean(), looseVersion.Clean()); Assert.Equal(strictVersion, looseVersion); // Loose version should be invalid in strict mode Assert.Throws<ArgumentException>(() => new Version(looseVersionString)); } [Theory] [InlineData(">=1.2.3", "=1.2.3")] public void Ranges(string rangeString, string versionString) { var range = new Range(rangeString); // Version doesn't satisfy range in strict mode Assert.False(range.IsSatisfied(versionString, false)); // Version satisfies range in loose mode Assert.True(range.IsSatisfied(versionString, true)); } } }
Return trampoline from lazy function
using System; using System.Collections.Generic; using System.Linq; using Sharper.C.Control; namespace Sharper.C.Data { using static TrampolineModule; public static class EnumerableModule { public static B FoldLeft<A, B>(this IEnumerable<A> e, B x, Func<B, A, B> f) => e.Aggregate(x, f); public static B FoldRight<A, B>(this IEnumerable<A> e, B x, Func<A, B, B> f) => e.Reverse().Aggregate(x, (b, a) => f(a, b)); public static B LazyFoldRight<A, B> ( this IEnumerable<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => LazyFoldRight(e.GetEnumerator(), x, f).Eval(); private static Trampoline<B> LazyFoldRight<A, B> ( IEnumerator<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => e.MoveNext() ? f(e.Current, Suspend(() => LazyFoldRight(e, x, f))) : Done(x); } }
using System; using System.Collections.Generic; using System.Linq; using Sharper.C.Control; namespace Sharper.C.Data { using static TrampolineModule; public static class EnumerableModule { public static B FoldLeft<A, B>(this IEnumerable<A> e, B x, Func<B, A, B> f) => e.Aggregate(x, f); public static B FoldRight<A, B>(this IEnumerable<A> e, B x, Func<A, B, B> f) => e.Reverse().Aggregate(x, (b, a) => f(a, b)); public static Trampoline<B> LazyFoldRight<A, B> ( this IEnumerable<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => LazyFoldRight(e.GetEnumerator(), x, f); private static Trampoline<B> LazyFoldRight<A, B> ( IEnumerator<A> e , B x , Func<A, Trampoline<B>, Trampoline<B>> f ) => e.MoveNext() ? f(e.Current, Suspend(() => LazyFoldRight(e, x, f))) : Done(x); } }
Fix type name prettyfying for generics
using System; using System.CodeDom; using System.Linq; using Microsoft.CSharp; namespace Ludiq.Reflection.Editor { public static class Extensions { // Used to print pretty type names for primitives private static CSharpCodeProvider csharp = new CSharpCodeProvider(); /// <summary> /// Returns the name for the given type where primitives are in their shortcut form. /// </summary> public static string PrettyName(this Type type) { string cSharpOutput = csharp.GetTypeOutput(new CodeTypeReference(type)); if (cSharpOutput.Contains('.')) { return cSharpOutput.Substring(cSharpOutput.LastIndexOf('.') + 1); } else { return cSharpOutput; } } } }
using System; using System.CodeDom; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CSharp; namespace Ludiq.Reflection.Editor { public static class Extensions { // Used to print pretty type names for primitives private static CSharpCodeProvider csharp = new CSharpCodeProvider(); /// <summary> /// Returns the name for the given type where primitives are in their shortcut form. /// </summary> public static string PrettyName(this Type type) { string cSharpOutput = csharp.GetTypeOutput(new CodeTypeReference(type)); var matches = Regex.Matches(cSharpOutput, @"([a-zA-Z0-9_\.]+)"); var prettyName = RemoveNamespace(matches[0].Value); if (matches.Count > 1) { prettyName += "<"; prettyName += string.Join(", ", matches.Cast<Match>().Skip(1).Select(m => RemoveNamespace(m.Value)).ToArray()); prettyName += ">"; } return prettyName; } private static string RemoveNamespace(string typeFullName) { if (!typeFullName.Contains('.')) { return typeFullName; } return typeFullName.Substring(typeFullName.LastIndexOf('.') + 1); } } }
Raise authentication server prerelease version.
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Affecto Authentication Server")] [assembly: AssemblyProduct("Affecto Authentication Server")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0-prerelease02")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Affecto Authentication Server")] [assembly: AssemblyProduct("Affecto Authentication Server")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0-prerelease03")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")] [assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")]
Add FNV1a-32 description to example usage
using System.Collections.Generic; using System.Security.Cryptography; namespace BloomFilter { class ExampleUsage { static void Main(string[] args) { //standard usage using SHA1 hashing using (var bf = new BloomFilter<string>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add an item to the filter bf.Add("My Text"); //checking for existence in the filter bool b; b = bf.Contains("My Text"); //true b = bf.Contains("Never been seen before"); //false (usually ;)) } //using a different algorithm using (var bf = new BloomFilter<string, FNV1a32>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add, check for existence, etc. } } } }
using System.Collections.Generic; using System.Security.Cryptography; namespace BloomFilter { class ExampleUsage { static void Main(string[] args) { //standard usage using SHA1 hashing using (var bf = new BloomFilter<string>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add an item to the filter bf.Add("My Text"); //checking for existence in the filter bool b; b = bf.Contains("My Text"); //true b = bf.Contains("Never been seen before"); //false (usually ;)) } //using a different hash algorithm (such as the provided FNV1a-32 implementation) using (var bf = new BloomFilter<string, FNV1a32>(MaxItems: 1000, FalsePositiveProbability: .001)) { //add, check for existence, etc. } } } }
Add example links to the design-time datacontext
using System; using System.Collections.Generic; using System.Windows.Media.Imaging; using KyleHughes.AboutDialog.WPF.Properties; namespace KyleHughes.AboutDialog.WPF { /// <summary> /// A class for extracting data from an Assembly. /// </summary> internal sealed class DesignVersionable : IVersionable { public BitmapImage Image { get; set; } = null; public string Product { get; set; } = "A product"; public string Title { get; set; } = "An Assembly"; public string Version { get; set; } = "1.0.3"; public string Description { get; set; } = "A product to do that thing which this product doees"; public string Author { get; set; } = "John Doe"; public string Owner { get; set; } = "A Company, Inc."; public string License { get { return string.Format(Resources.MIT, Environment.NewLine, Copyright); } set { } } public string Copyright { get { return $"Copyright \u00a9 {Author} {string.Join(", ", Years)}"; } set { } } public int[] Years { get; set; } = {2013, 2014, 2015}; public bool ShowYearsAsRange { get; set; } = true; public IList<Tuple<string, Uri>> Links { get; set; } } }
using System; using System.Collections.Generic; using System.Windows.Media.Imaging; using KyleHughes.AboutDialog.WPF.Properties; namespace KyleHughes.AboutDialog.WPF { /// <summary> /// A class for extracting data from an Assembly. /// </summary> internal sealed class DesignVersionable : IVersionable { public BitmapImage Image { get; set; } = null; public string Product { get; set; } = "A product"; public string Title { get; set; } = "An Assembly"; public string Version { get; set; } = "1.0.3"; public string Description { get; set; } = "A product to do that thing which this product doees"; public string Author { get; set; } = "John Doe"; public string Owner { get; set; } = "A Company, Inc."; public string License { get { return string.Format(Resources.MIT, Environment.NewLine, Copyright); } set { } } public string Copyright { get { return $"Copyright \u00a9 {Author} {string.Join(", ", Years)}"; } set { } } public int[] Years { get; set; } = { 2013, 2014, 2015 }; public bool ShowYearsAsRange { get; set; } = true; public IList<Tuple<string, Uri>> Links { get { return new List<Tuple<string, Uri>> { new Tuple<string, Uri>("Link 1", new Uri("http://example.com/")), new Tuple<string, Uri>("Link 2", new Uri("http://example.com/")) }; } set { } } } }
Fix bug: properly create time span from seconds (not mod 60)
using System; using Rooijakkers.MeditationTimer.Data.Contracts; namespace Rooijakkers.MeditationTimer.Data { /// <summary> /// Stores settings data in local settings storage /// </summary> public class Settings : ISettings { private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage"; public TimeSpan TimeToGetReady { get { int? secondsToGetReady = Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?; // If settings were not yet stored set to default value. if (secondsToGetReady == null) { secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS; SetTimeToGetReady(secondsToGetReady.Value); } // Return stored time in seconds as a TimeSpan. return new TimeSpan(0, 0, secondsToGetReady.Value); } set { // Store time in seconds obtained from TimeSpan. SetTimeToGetReady(value.Seconds); } } private void SetTimeToGetReady(int value) { Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value; } } }
using System; using Rooijakkers.MeditationTimer.Data.Contracts; namespace Rooijakkers.MeditationTimer.Data { /// <summary> /// Stores settings data in local settings storage /// </summary> public class Settings : ISettings { private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage"; public TimeSpan TimeToGetReady { get { int? secondsToGetReady = Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?; // If settings were not yet stored set to default value. if (secondsToGetReady == null) { secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS; SetTimeToGetReady(secondsToGetReady.Value); } // Return stored time in seconds as a TimeSpan. return TimeSpan.FromSeconds(secondsToGetReady.Value); } set { // Store time in seconds obtained from TimeSpan. SetTimeToGetReady(value.Seconds); } } private void SetTimeToGetReady(int value) { Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value; } } }
Prepare for next development iteration
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NModbus4")] [assembly: AssemblyProduct("NModbus4")] [assembly: AssemblyCompany("Maxwe11")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: AssemblyDescription("NModbus is a C# implementation of the Modbus protocol. " + "Provides connectivity to Modbus slave compatible devices and applications. " + "Supports serial ASCII, serial RTU, TCP, and UDP protocols. "+ "NModbus4 it's a fork of NModbus(https://code.google.com/p/nmodbus)")] [assembly: CLSCompliant(false)] [assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")] #if !SIGNED [assembly: InternalsVisibleTo(@"Modbus.UnitTests")] [assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")] #endif
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NModbus4")] [assembly: AssemblyProduct("NModbus4")] [assembly: AssemblyCompany("Maxwe11")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: AssemblyDescription("NModbus is a C# implementation of the Modbus protocol. " + "Provides connectivity to Modbus slave compatible devices and applications. " + "Supports serial ASCII, serial RTU, TCP, and UDP protocols. "+ "NModbus4 it's a fork of NModbus(https://code.google.com/p/nmodbus)")] [assembly: CLSCompliant(false)] [assembly: Guid("95B2AE1E-E0DC-4306-8431-D81ED10A2D5D")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0-dev")] #if !SIGNED [assembly: InternalsVisibleTo(@"Modbus.UnitTests")] [assembly: InternalsVisibleTo(@"DynamicProxyGenAssembly2")] #endif
Use dotnet core run task
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./", title: "Xer.Cqrs", repositoryOwner: "XerProjects", repositoryName: "Xer.Cqrs", appVeyorAccountName: "mvput", shouldRunDupFinder: false, shouldRunDotNetCorePack: true); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* ", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.Run();
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./", title: "Xer.Cqrs", repositoryOwner: "XerProjects", repositoryName: "Xer.Cqrs", appVeyorAccountName: "mvput", shouldRunDupFinder: false, shouldRunDotNetCorePack: true); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* ", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
Add an IRandom.GetDigit() extension method, which returns a string between '0' and '9'.
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } public static UInt64 GetUInt64(this IRandom random) { return BitConverter.ToUInt64(random.GetBytes(8), 0); } } }
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static String GetDigit(this IRandom random) { return (random.GetUInt64() % 10).ToString(); } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } public static UInt64 GetUInt64(this IRandom random) { return BitConverter.ToUInt64(random.GetBytes(8), 0); } } }
Enable testing of internal functionality, to allow tests of AsyncBarrier
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("Channels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Channels")] [assembly: AssemblyCopyright("Copyright © 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("e3f88afb-274b-43cb-8dd9-98de51e8838e")] // 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("Channels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Channels")] [assembly: AssemblyCopyright("Copyright © 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("e3f88afb-274b-43cb-8dd9-98de51e8838e")] // 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")] // Allow test project access to internal functionality [assembly: InternalsVisibleTo("Channels.Tests")]
Create a way for users to specify the initial uris to scan.
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.Shared.Descriptors; using SmugMug.v2.Authentication; using SmugMugShared; using System.Collections.Generic; using System.Diagnostics; namespace SmugMugMetadataRetriever { class Program { static OAuthToken s_oauthToken; static void Main(string[] args) { s_oauthToken = SmugMug.Shared.SecretsAccess.GetSmugMugSecrets(); Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid)); ApiAnalyzer buf = new ApiAnalyzer(s_oauthToken); var list = new Dictionary<string, string>(); list = buf.GetBaseUris(Constants.Addresses.SmugMug, "/api/v2"); Dictionary<string, string> uris = new Dictionary<string, string>() { }; foreach (var item in list) { uris.Add(item.Key, Constants.Addresses.SmugMug + item.Value + Constants.RequestModifiers); } var types = buf.AnalyzeAPIs(uris, Constants.Addresses.SmugMugApi); } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.Shared.Descriptors; using SmugMug.v2.Authentication; using SmugMugShared; using System.Collections.Generic; using System.Diagnostics; namespace SmugMugMetadataRetriever { class Program { static OAuthToken s_oauthToken; static void Main(string[] args) { s_oauthToken = SmugMug.Shared.SecretsAccess.GetSmugMugSecrets(); Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid)); ApiAnalyzer buf = new ApiAnalyzer(s_oauthToken); var list = new Dictionary<string, string>(); list = buf.GetBaseUris(Constants.Addresses.SmugMug, "/api/v2"); for (int i = 0; i < args.Length; i++) { list.Add("arg" + i, args[i]); } Dictionary<string, string> uris = new Dictionary<string, string>(); foreach (var item in list) { uris.Add(item.Key, Constants.Addresses.SmugMug + item.Value + Constants.RequestModifiers); } var types = buf.AnalyzeAPIs(uris, Constants.Addresses.SmugMugApi); } } }
Use out var in jumbo command
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; using Serilog; namespace Modix.Modules { [Name("Fun"), Summary("A bunch of miscellaneous, fun commands")] public class FunModule : ModuleBase { [Command("jumbo"), Summary("Jumbofy an emoji")] public async Task Jumbo(string emoji) { string emojiUrl = null; if (Emote.TryParse(emoji, out Emote found)) { emojiUrl = found.Url; } else { int codepoint = Char.ConvertToUtf32(emoji, 0); string codepointHex = codepoint.ToString("X").ToLower(); emojiUrl = $"https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/{codepointHex}.png"; } try { HttpClient client = new HttpClient(); var req = await client.GetStreamAsync(emojiUrl); await Context.Channel.SendFileAsync(req, Path.GetFileName(emojiUrl), Context.User.Mention); try { await Context.Message.DeleteAsync(); } catch (HttpRequestException) { Log.Information("Couldn't delete message after jumbofying."); } } catch (HttpRequestException) { await ReplyAsync($"Sorry {Context.User.Mention}, I don't recognize that emoji."); } } } }
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; using Serilog; namespace Modix.Modules { [Name("Fun"), Summary("A bunch of miscellaneous, fun commands")] public class FunModule : ModuleBase { [Command("jumbo"), Summary("Jumbofy an emoji")] public async Task Jumbo(string emoji) { string emojiUrl = null; if (Emote.TryParse(emoji, out var found)) { emojiUrl = found.Url; } else { int codepoint = Char.ConvertToUtf32(emoji, 0); string codepointHex = codepoint.ToString("X").ToLower(); emojiUrl = $"https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/{codepointHex}.png"; } try { HttpClient client = new HttpClient(); var req = await client.GetStreamAsync(emojiUrl); await Context.Channel.SendFileAsync(req, Path.GetFileName(emojiUrl), Context.User.Mention); try { await Context.Message.DeleteAsync(); } catch (HttpRequestException) { Log.Information("Couldn't delete message after jumbofying."); } } catch (HttpRequestException) { await ReplyAsync($"Sorry {Context.User.Mention}, I don't recognize that emoji."); } } } }
Add more IHandleContext extension methods
using Aggregates.Internal; using NServiceBus; using NServiceBus.Unicast; using NServiceBus.Unicast.Messages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aggregates.Extensions { public static class BusExtensions { public static void ReplyAsync(this IHandleContext context, object message) { var incoming = context.Context.PhysicalMessage; context.Bus.Send(incoming.ReplyToAddress, String.IsNullOrEmpty( incoming.CorrelationId ) ? incoming.Id : incoming.CorrelationId, message); } public static void ReplyAsync<T>(this IHandleContext context, Action<T> message) { var incoming = context.Context.PhysicalMessage; context.Bus.Send(incoming.ReplyToAddress, String.IsNullOrEmpty(incoming.CorrelationId) ? incoming.Id : incoming.CorrelationId, message); } } }
using Aggregates.Internal; using NServiceBus; using NServiceBus.Unicast; using NServiceBus.Unicast.Messages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aggregates.Extensions { public static class BusExtensions { public static void ReplyAsync(this IHandleContext context, object message) { var incoming = context.Context.PhysicalMessage; context.Bus.Send(incoming.ReplyToAddress, String.IsNullOrEmpty( incoming.CorrelationId ) ? incoming.Id : incoming.CorrelationId, message); } public static void ReplyAsync<T>(this IHandleContext context, Action<T> message) { var incoming = context.Context.PhysicalMessage; context.Bus.Send(incoming.ReplyToAddress, String.IsNullOrEmpty(incoming.CorrelationId) ? incoming.Id : incoming.CorrelationId, message); } public static void PublishAsync<T>(this IHandleContext context, Action<T> message) { context.Bus.Publish<T>(message); } public static void PublishAsync(this IHandleContext context, object message) { context.Bus.Publish(message); } public static void SendAsync<T>(this IHandleContext context, Action<T> message) { context.Bus.Send(message); } public static void SendAsync(this IHandleContext context, object message) { context.Bus.Send(message); } public static void SendAsync<T>(this IHandleContext context, String destination, Action<T> message) { context.Bus.Send(destination, message); } public static void SendAsync(this IHandleContext context, String destination, object message) { context.Bus.Send(destination, message); } } }
Add test showing success message
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace NUnitTestDemo { public class SimpleTests { [Test] public void TestSucceeds() { Assert.That(2 + 2, Is.EqualTo(4)); } [Test, ExpectedException(typeof(ApplicationException))] public void TestSucceeds_ExpectedException() { throw new ApplicationException("Expected"); } [Test] public void TestFails() { Assert.That(2 + 2, Is.EqualTo(5)); } [Test] public void TestIsInconclusive() { Assert.Inconclusive("Testing"); } [Test, Ignore("Ignoring this test deliberately")] public void TestIsIgnored_Attribute() { } [Test] public void TestIsIgnored_Assert() { Assert.Ignore("Ignoring this test deliberately"); } [Test] public void TestThrowsException() { throw new Exception("Deliberate exception thrown"); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace NUnitTestDemo { public class SimpleTests { [Test] public void TestSucceeds() { Assert.That(2 + 2, Is.EqualTo(4)); } [Test] public void TestSucceeds_Message() { Assert.That(2 + 2, Is.EqualTo(4)); Assert.Pass("Simple arithmetic!"); } [Test, ExpectedException(typeof(ApplicationException))] public void TestSucceeds_ExpectedException() { throw new ApplicationException("Expected"); } [Test] public void TestFails() { Assert.That(2 + 2, Is.EqualTo(5)); } [Test] public void TestIsInconclusive() { Assert.Inconclusive("Testing"); } [Test, Ignore("Ignoring this test deliberately")] public void TestIsIgnored_Attribute() { } [Test] public void TestIsIgnored_Assert() { Assert.Ignore("Ignoring this test deliberately"); } [Test] public void TestThrowsException() { throw new Exception("Deliberate exception thrown"); } } }
Add error handling generating random values to inform column name and type
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; } } } }
using System; namespace StrangerData.Utils { internal static class RandomValues { public static object ForColumn(TableColumnInfo columnInfo) { try { return GenerateForColumn(columnInfo); } catch (Exception ex) { throw new Exception($"Could not generate value for column Name=[{columnInfo.Name}] Type=[{columnInfo.ColumnType}]", ex); } } private static object GenerateForColumn(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; } } } }
Add constructor with parameters for coordinate
namespace Stranne.VasttrafikNET.Models { /// <summary> /// Describes a coordinate in WGS84 decimal /// </summary> public class Coordinate { /// <summary> /// Latitude in WGS84 decimal form /// </summary> public double Latitude { get; set; } /// <summary> /// Longitude in WGS84 decimal form /// </summary> public double Longitude { get; set; } } }
namespace Stranne.VasttrafikNET.Models { /// <summary> /// Describes a coordinate in WGS84 decimal /// </summary> public class Coordinate { /// <summary> /// Latitude in WGS84 decimal form /// </summary> public double Latitude { get; set; } /// <summary> /// Longitude in WGS84 decimal form /// </summary> public double Longitude { get; set; } /// <summary> /// Create a new coordinate. /// </summary> public Coordinate() { } /// <summary> /// Create a coordinate with latitude and longitude pre defined. /// </summary> /// <param name="latitude">Latitude in WGS84 decimal form</param> /// <param name="longitude">Longitude in WGS84 decimal form</param> public Coordinate(double latitude, double longitude) { Latitude = latitude; Longitude = longitude; } } }
Remove XFrame on the checkout page
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Filters { public class XFrameOptionsAttribute : Attribute, IActionFilter { public XFrameOptionsAttribute(string value) { Value = value; } public string Value { get; set; } public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { context.HttpContext.Response.SetHeaderOnStarting("X-Frame-Options", Value); } } }
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Filters { public class XFrameOptionsAttribute : Attribute, IActionFilter { public XFrameOptionsAttribute(string value) { Value = value; } public string Value { get; set; } public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { if (context.IsEffectivePolicy<XFrameOptionsAttribute>(this)) { context.HttpContext.Response.SetHeaderOnStarting("X-Frame-Options", Value); } } } }
Use ? instead of Nullable
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ao3tracksync.Models { using System; using System.Collections.Generic; public partial class Work { public long userid { get; set; } public long id { get; set; } public long chapterid { get; set; } public long number { get; set; } public long timestamp { get; set; } public Nullable<long> location { get; set; } public virtual User User { get; set; } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ao3tracksync.Models { using System; using System.Collections.Generic; public partial class Work { public long userid { get; set; } public long id { get; set; } public long chapterid { get; set; } public long number { get; set; } public long timestamp { get; set; } public long? location { get; set; } public virtual User User { get; set; } } }
Revert "Increase the maximum time we wait for long running tests from 5 to 10."
using System; using System.Threading; using NUnit.Framework; namespace JustSaying.TestingFramework { public static class Patiently { public static void VerifyExpectation(Action expression) { VerifyExpectation(expression, 5.Seconds()); } public static void VerifyExpectation(Action expression, TimeSpan timeout) { bool hasTimedOut; var started = DateTime.Now; do { try { expression.Invoke(); return; } catch { } hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!hasTimedOut); expression.Invoke(); } public static void AssertThat(Func<bool> func) { AssertThat(func, 10.Seconds()); } public static void AssertThat(Func<bool> func, TimeSpan timeout) { bool result; bool hasTimedOut; var started = DateTime.Now; do { result = func.Invoke(); hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!result && !hasTimedOut); Assert.True(result); } } public static class Extensions { public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } } }
using System; using System.Threading; using NUnit.Framework; namespace JustSaying.TestingFramework { public static class Patiently { public static void VerifyExpectation(Action expression) { VerifyExpectation(expression, 5.Seconds()); } public static void VerifyExpectation(Action expression, TimeSpan timeout) { bool hasTimedOut; var started = DateTime.Now; do { try { expression.Invoke(); return; } catch { } hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!hasTimedOut); expression.Invoke(); } public static void AssertThat(Func<bool> func) { AssertThat(func, 5.Seconds()); } public static void AssertThat(Func<bool> func, TimeSpan timeout) { bool result; bool hasTimedOut; var started = DateTime.Now; do { result = func.Invoke(); hasTimedOut = timeout < DateTime.Now - started; Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds); } while (!result && !hasTimedOut); Assert.True(result); } } public static class Extensions { public static TimeSpan Seconds(this int seconds) { return TimeSpan.FromSeconds(seconds); } } }
Use fieldset instead of div
@model IEnumerable<alert_roster.web.Models.Message> @{ ViewBag.Title = "Messages"; } <div class="jumbotron"> <h1>@ViewBag.Title</h1> </div> @foreach (var message in Model) { <div class="row"> <div class="col-md-4"> <h2> <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script></h2> <p> @message.Content </p> </div> </div> }
@model IEnumerable<alert_roster.web.Models.Message> @{ ViewBag.Title = "Messages"; } <div class="jumbotron"> <h1>@ViewBag.Title</h1> </div> @foreach (var message in Model) { <div class="row"> <div class="col-md-4"> <fieldset> <legend> <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script> </legend> @message.Content </fieldset> </div> </div> }
Trim un-necessarry char from aggregation variable
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LodViewProvider { public enum AggregationType { Min = 0, Max = 1, Sum = 2, Count = 3, Average = 4, // group by // order by } public class Aggregation : ICondition { public string Variable { get; private set; } public AggregationType AggregationType { get; private set; } public Aggregation( string variable, AggregationType aggregationType ) { Variable = variable; AggregationType = aggregationType; } public override string ToString() { var strBuild = new StringBuilder(); switch ( AggregationType ) { case LodViewProvider.AggregationType.Average: { } break; case LodViewProvider.AggregationType.Count: { } break; case LodViewProvider.AggregationType.Max: { } break; case LodViewProvider.AggregationType.Min: { } break; default: { throw new InvalidAggregationTypeException(); } break; } return strBuild.ToString(); } } public class InvalidAggregationTypeException : Exception { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LodViewProvider { public enum AggregationType { Min = 0, Max = 1, Sum = 2, Count = 3, Average = 4, // group by // order by } public class Aggregation : ICondition { public string Variable { get; private set; } public AggregationType AggregationType { get; private set; } public Aggregation( string variable, AggregationType aggregationType ) { Variable = variable.Trim( '\"' ); AggregationType = aggregationType; } public override string ToString() { var strBuild = new StringBuilder(); switch ( AggregationType ) { case LodViewProvider.AggregationType.Average: { } break; case LodViewProvider.AggregationType.Count: { } break; case LodViewProvider.AggregationType.Max: { } break; case LodViewProvider.AggregationType.Min: { } break; default: { throw new InvalidAggregationTypeException(); } break; } return strBuild.ToString(); } } public class InvalidAggregationTypeException : Exception { } }
Fix for SSD rank filtering
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { // Ensure we're only displaying Soldiers we care about here query.OnlyEnlisted = true; return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { // Ensure we're only displaying Soldiers we care about here if (!query.Ranks.Any()) query.OnlyEnlisted = true; return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
Add check is transport work with webGL or not at transport factory
namespace LiteNetLibManager { public class WebSocketTransportFactory : BaseTransportFactory { public override bool CanUseWithWebGL { get { return false; } } public override ITransport Build() { return new WebSocketTransport(); } } }
namespace LiteNetLibManager { public class WebSocketTransportFactory : BaseTransportFactory { public override bool CanUseWithWebGL { get { return true; } } public override ITransport Build() { return new WebSocketTransport(); } } }
Fix the null reference exception coming from AutomaticPackageCurator when curatedFeed has been loaded without including Packages.
using System.IO; using System.Linq; using NuGet; namespace NuGetGallery { public class WebMatrixPackageCurator : AutomaticPackageCurator { public override void Curate( Package galleryPackage, IPackage nugetPackage) { var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix"); if (curatedFeed == null) { return; } if (!galleryPackage.IsLatestStable) { return; } var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages"); if (!shouldBeIncluded) { shouldBeIncluded = true; foreach (var file in nugetPackage.GetFiles()) { var fi = new FileInfo(file.Path); if (fi.Extension == ".ps1" || fi.Extension == ".t4") { shouldBeIncluded = false; break; } } } if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed)) { GetService<ICreateCuratedPackageCommand>().Execute( curatedFeed.Key, galleryPackage.PackageRegistration.Key, automaticallyCurated: true); } } } }
using System.IO; using System.Linq; using NuGet; namespace NuGetGallery { public class WebMatrixPackageCurator : AutomaticPackageCurator { public override void Curate( Package galleryPackage, IPackage nugetPackage) { var curatedFeed = GetService<ICuratedFeedByNameQuery>().Execute("webmatrix", includePackages: true); if (curatedFeed == null) { return; } if (!galleryPackage.IsLatestStable) { return; } var shouldBeIncluded = galleryPackage.Tags != null && galleryPackage.Tags.ToLowerInvariant().Contains("aspnetwebpages"); if (!shouldBeIncluded) { shouldBeIncluded = true; foreach (var file in nugetPackage.GetFiles()) { var fi = new FileInfo(file.Path); if (fi.Extension == ".ps1" || fi.Extension == ".t4") { shouldBeIncluded = false; break; } } } if (shouldBeIncluded && DependenciesAreCurated(galleryPackage, curatedFeed)) { GetService<ICreateCuratedPackageCommand>().Execute( curatedFeed.Key, galleryPackage.PackageRegistration.Key, automaticallyCurated: true); } } } }
Test for NH-2559 (does not fail)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace NHibernate.Test.Linq.ByMethod { [TestFixture] public class AnyTests : LinqTestCase { [Test] public void AnySublist() { var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList(); Assert.AreEqual(61, orders.Count); orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList(); Assert.AreEqual(0, orders.Count); } [Test] public void NestedAny() { var test = (from c in db.Customers where c.ContactName == "Bob" && (c.CompanyName == "NormalooCorp" || c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10))) select c).ToList(); Assert.AreEqual(0, test.Count); } } }
using System.Linq; using NUnit.Framework; namespace NHibernate.Test.Linq.ByMethod { [TestFixture] public class AnyTests : LinqTestCase { [Test] public void AnySublist() { var orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Quantity == 5)).ToList(); Assert.AreEqual(61, orders.Count); orders = db.Orders.Where(o => o.OrderLines.Any(ol => ol.Order == null)).ToList(); Assert.AreEqual(0, orders.Count); } [Test] public void NestedAny() { var test = (from c in db.Customers where c.ContactName == "Bob" && (c.CompanyName == "NormalooCorp" || c.Orders.Any(o => o.OrderLines.Any(ol => ol.Discount < 20 && ol.Discount >= 10))) select c).ToList(); Assert.AreEqual(0, test.Count); } [Test] public void ManyToManyAny() { var test = db.Orders.Where(o => o.Employee.FirstName == "test"); var result = test.Where(o => o.Employee.Territories.Any(t => t.Description == "test")).ToList(); Assert.AreEqual(0, result.Count); } } }
Add broken test to testproj
namespace testproj { using System; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { dotMemory.Check( memory => { var str1 = "1"; var str2 = "2"; var str3 = "3"; Assert.LessOrEqual(2, memory.ObjectsCount); Console.WriteLine(str1 + str2 + str3); }); } } }
namespace testproj { using System; using System.Collections.Generic; using JetBrains.dotMemoryUnit; using NUnit.Framework; [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } [Test] public void TestMethod2() { var strs = new List<string>(); var memoryCheckPoint = dotMemory.Check(); strs.Add(GenStr()); strs.Add(GenStr()); dotMemory.Check( memory => { var strCount = memory .GetDifference(memoryCheckPoint) .GetNewObjects() .GetObjects(i => i.Type == typeof(string)) .ObjectsCount; Assert.LessOrEqual(strCount, 2); }); strs.Clear(); } private static string GenStr() { return Guid.NewGuid().ToString(); } } }
Remove steps from part 1 that have been moved to part 2.
using System; using System.IO; using System.Security.Cryptography; namespace Tutorial { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("You must provide the name of a file to read and the name of a file to write."); return; } var sourceFilename = args[0]; var destinationFilename = args[1]; using (var sourceStream = File.OpenRead(sourceFilename)) using (var destinationStream = File.Create(destinationFilename)) using (var provider = new AesCryptoServiceProvider()) using (var cryptoTransform = provider.CreateEncryptor()) using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write)) { destinationStream.Write(provider.IV, 0, provider.IV.Length); sourceStream.CopyTo(cryptoStream); Console.WriteLine(System.Convert.ToBase64String(provider.Key)); } } } }
using System; using System.IO; using System.Security.Cryptography; namespace Tutorial { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("You must provide the name of a file to read and the name of a file to write."); return; } var sourceFilename = args[0]; var destinationFilename = args[1]; using (var sourceStream = File.OpenRead(sourceFilename)) using (var destinationStream = File.Create(destinationFilename)) using (var provider = new AesCryptoServiceProvider()) using (var cryptoTransform = provider.CreateEncryptor()) using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write)) { sourceStream.CopyTo(cryptoStream); } } } }
Fix code to return LanguageCode not CountryCode
using Foundation; using Internationalization.Core.Helpers; namespace Internationalization.Touch.Helpers { public class AppInfo : IAppInfo { public string CurrentLanguage => NSLocale.CurrentLocale.CountryCode.ToLower(); } }
using Foundation; using Internationalization.Core.Helpers; namespace Internationalization.Touch.Helpers { public class AppInfo : IAppInfo { public string CurrentLanguage { get { return NSLocale.CurrentLocale.LanguageCode.ToLower(); } } } }
Fix dragging tournament ladder too far causing it to disappear
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Input.Events; using osuTK; namespace osu.Game.Tournament.Screens.Ladder { public class LadderDragContainer : Container { protected override bool OnDragStart(DragStartEvent e) => true; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; private Vector2 target; private float scale = 1; protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false; protected override void OnDrag(DragEvent e) { this.MoveTo(target += e.Delta, 1000, Easing.OutQuint); } private const float min_scale = 0.6f; private const float max_scale = 1.4f; protected override bool OnScroll(ScrollEvent e) { var newScale = Math.Clamp(scale + e.ScrollDelta.Y / 15 * scale, min_scale, max_scale); this.MoveTo(target -= e.MousePosition * (newScale - scale), 2000, Easing.OutQuint); this.ScaleTo(scale = newScale, 2000, Easing.OutQuint); return true; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Input.Events; using osuTK; namespace osu.Game.Tournament.Screens.Ladder { public class LadderDragContainer : Container { protected override bool OnDragStart(DragStartEvent e) => true; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; private Vector2 target; private float scale = 1; protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false; public override bool UpdateSubTreeMasking(Drawable source, RectangleF maskingBounds) => false; protected override void OnDrag(DragEvent e) { this.MoveTo(target += e.Delta, 1000, Easing.OutQuint); } private const float min_scale = 0.6f; private const float max_scale = 1.4f; protected override bool OnScroll(ScrollEvent e) { var newScale = Math.Clamp(scale + e.ScrollDelta.Y / 15 * scale, min_scale, max_scale); this.MoveTo(target -= e.MousePosition * (newScale - scale), 2000, Easing.OutQuint); this.ScaleTo(scale = newScale, 2000, Easing.OutQuint); return true; } } }
Set only just one torch
using UnityEngine; using System.Collections; using System; public class LightDiminuer : MonoBehaviour { public float intensity = 15; public float intensityRate = 0.001F; public float ambientIntensity = 3; public float torchNoiseRange = 1; private GameObject player; private Light playerLight; private Light ambientPlayerLight; // Use this for initialization void Awake () { player = GameObject.FindGameObjectWithTag ("Player"); playerLight = GameObject.FindGameObjectWithTag ("PlayerLight").GetComponent<Light>(); playerLight.intensity = 0; playerLight.range = 15; ambientPlayerLight = GameObject.FindGameObjectWithTag ("AmbientPlayerLight").GetComponent<Light>(); ambientPlayerLight.intensity = 0; } // Update is called once per frame void Update () { if (playerLight.intensity == 0) { ambientPlayerLight.intensity = ambientIntensity; } else { playerLight.intensity -= intensityRate; } if (playerLight.intensity < 2F && ambientPlayerLight.intensity < ambientIntensity) { ambientPlayerLight.intensity += intensityRate; } if (Input.GetKey (KeyCode.L)) { playerLight.intensity = intensity; } } }
using UnityEngine; using System.Collections; using System; public class LightDiminuer : MonoBehaviour { public float intensity = 15; public float intensityRate = 0.001F; public float ambientIntensity = 3; public float torchNoiseRange = 1; public bool lightOn = false; private GameObject player; private Light playerLight; private Light ambientPlayerLight; // Use this for initialization void Awake () { player = GameObject.FindGameObjectWithTag ("Player"); playerLight = GameObject.FindGameObjectWithTag ("PlayerLight").GetComponent<Light>(); playerLight.intensity = 0; playerLight.range = 15; ambientPlayerLight = GameObject.FindGameObjectWithTag ("AmbientPlayerLight").GetComponent<Light>(); ambientPlayerLight.intensity = 0; } // Update is called once per frame void Update () { if (playerLight.intensity == 0) { ambientPlayerLight.intensity = ambientIntensity; } else { playerLight.intensity -= intensityRate; } if (playerLight.intensity < 2F && ambientPlayerLight.intensity < ambientIntensity) { ambientPlayerLight.intensity += intensityRate; } if (Input.GetKey (KeyCode.L) && !lightOn) { lightOn = true; playerLight.intensity = intensity; } } }
Switch to list instead of Dictionnary
using System; using System.Collections.Generic; public class MultipleDelegate { private readonly Dictionary<int, Func<int, int>> _delegates = new Dictionary<int, Func<int, int>>(); private Type _typeOf; private int _pos = 0; public int Suscribe(Func<int, int> item) { _delegates.Add(_pos, item); return _pos++; } public void Unsuscribe(int key) { _delegates.Remove(key); } public void Empty() { _delegates.Clear(); } public void Execute(int value) { foreach (var item in _delegates) { var func = item.Value; func(value); } } }
using System; using System.Collections.Generic; using UnityEngine; public class MultipleDelegate { private readonly List<Func<int, int>> _delegates = new List<Func<int, int>>(); private Type _typeOf; private int _pos = 0; public int Suscribe(Func<int, int> item) { _delegates.Add(item); return 0; } public void Empty() { _delegates.Clear(); } public void Execute(int value) { foreach (var func in _delegates) { func(value); } } }
Fix array out of index issue @neico
using Oxide.Core.Libraries; using Oxide.Core.Logging; namespace Oxide.Ext.Lua.Libraries { /// <summary> /// A global library containing game-agnostic Lua utilities /// </summary> public class LuaGlobal : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal => true; /// <summary> /// Gets the logger that this library writes to /// </summary> public Logger Logger { get; private set; } /// <summary> /// Initializes a new instance of the LuaGlobal library /// </summary> /// <param name="logger"></param> public LuaGlobal(Logger logger) { Logger = logger; } /// <summary> /// Prints a message /// </summary> /// <param name="args"></param> [LibraryFunction("print")] public void Print(params object[] args) { if (args.Length == 1) { Logger.Write(LogType.Info, args[0]?.ToString() ?? "null"); } else { var message = string.Empty; for (var i = 0; i <= args.Length; ++i) { if (i > 0) message += "\t"; message += args[i]?.ToString() ?? "null"; } Logger.Write(LogType.Info, message); } } } }
using Oxide.Core.Libraries; using Oxide.Core.Logging; namespace Oxide.Ext.Lua.Libraries { /// <summary> /// A global library containing game-agnostic Lua utilities /// </summary> public class LuaGlobal : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal => true; /// <summary> /// Gets the logger that this library writes to /// </summary> public Logger Logger { get; private set; } /// <summary> /// Initializes a new instance of the LuaGlobal library /// </summary> /// <param name="logger"></param> public LuaGlobal(Logger logger) { Logger = logger; } /// <summary> /// Prints a message /// </summary> /// <param name="args"></param> [LibraryFunction("print")] public void Print(params object[] args) { if (args.Length == 1) { Logger.Write(LogType.Info, args[0]?.ToString() ?? "null"); } else { var message = string.Empty; for (var i = 0; i < args.Length; ++i) { if (i > 0) message += "\t"; message += args[i]?.ToString() ?? "null"; } Logger.Write(LogType.Info, message); } } } }
Call widget "Special Event" on "Search" search
using System.Diagnostics; using System.Windows.Input; using DesktopWidgets.Helpers; using DesktopWidgets.WidgetBase; using DesktopWidgets.WidgetBase.ViewModel; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}"); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }
using System.Diagnostics; using System.Windows.Input; using DesktopWidgets.Helpers; using DesktopWidgets.WidgetBase; using DesktopWidgets.WidgetBase.ViewModel; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}"); OnSpecialEvent(); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }
Change the Db name for the object context.
using System.Data.Entity; namespace RWXViewer.Models { public class ObjectPathContext : DbContext { public ObjectPathContext() : base("ObjectPathContext") { } public DbSet<World> Worlds { get; set; } public DbSet<ObjectPathItem> ObjectPathItem { get; set; } } }
using System.Data.Entity; namespace RWXViewer.Models { public class ObjectPathContext : DbContext { public ObjectPathContext() : base("ObjectPathDb") { } public DbSet<World> Worlds { get; set; } public DbSet<ObjectPathItem> ObjectPathItem { get; set; } } }
Rename Error category to Danger
namespace HtmlLogger.Model { public enum LogCategory { Info, Warning, Error } }
namespace HtmlLogger.Model { public enum LogCategory { Info, Warning, Danger } }
Update default rendering partial view
@inherits UmbracoViewPage<BlockListModel> @using ContentModels = Umbraco.Web.PublishedModels; @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; @Html.Partial("BlockList/" + data.ContentType.Alias, layout) } </div>
@inherits UmbracoViewPage<BlockListModel> @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; @Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout) } </div>
Add OS and Version information to telemetry
using Microsoft.ApplicationInsights; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace unBand { public static class Telemetry { public static TelemetryClient Client {get; private set;} static Telemetry() { Client = new TelemetryClient(); Init(); } private static void Init() { var props = Properties.Settings.Default; if (props.Device == Guid.Empty) { props.Device = Guid.NewGuid(); props.Save(); Client.Context.Session.IsFirst = true; } Client.Context.Device.Id = props.Device.ToString(); Client.Context.Session.Id = Guid.NewGuid().ToString(); } /// <summary> /// Poor mans enum -> expanded string. /// /// Once I've been using this for a while I may change this to a pure enum if /// spaces in names prove to be annoying for querying / sorting the data /// </summary> public static class Events { public const string AppLaunch = "Launch"; public const string DeclinedFirstRunWarning = "Declined First Run Warning"; public const string DeclinedTelemetry = "Declined Telemetry"; public const string ChangeBackground = "Change Background"; public const string ChangeThemeColor = "Change Theme Color"; } } }
using Microsoft.ApplicationInsights; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace unBand { public static class Telemetry { public static TelemetryClient Client {get; private set;} static Telemetry() { Client = new TelemetryClient(); Init(); } private static void Init() { var props = Properties.Settings.Default; if (props.Device == Guid.Empty) { props.Device = Guid.NewGuid(); props.Save(); Client.Context.Session.IsFirst = true; } Client.Context.Device.Id = props.Device.ToString(); Client.Context.Session.Id = Guid.NewGuid().ToString(); Client.Context.Device.OperatingSystem = GetOS(); Client.Context.Device.Language = System.Globalization.CultureInfo.InstalledUICulture.TwoLetterISOLanguageName; Client.Context.Component.Version = About.Current.Version; } private static string GetOS() { return Environment.OSVersion.VersionString + "(" + (Environment.Is64BitOperatingSystem ? "x64" : "x86") + ")"; } /// <summary> /// Poor mans enum -> expanded string. /// /// Once I've been using this for a while I may change this to a pure enum if /// spaces in names prove to be annoying for querying / sorting the data /// </summary> public static class Events { public const string AppLaunch = "Launch"; public const string DeclinedFirstRunWarning = "Declined First Run Warning"; public const string DeclinedTelemetry = "Declined Telemetry"; public const string ChangeBackground = "Change Background"; public const string ChangeThemeColor = "Change Theme Color"; } } }
Use TypeNameHelper instead of private method
using System; using System.Linq; using System.Reflection; namespace Scrutor { public class MissingTypeRegistrationException : InvalidOperationException { public MissingTypeRegistrationException(Type serviceType) : base($"Could not find any registered services for type '{GetFriendlyName(serviceType)}'.") { ServiceType = serviceType; } public Type ServiceType { get; } private static string GetFriendlyName(Type type) { if (type == typeof(int)) return "int"; if (type == typeof(short)) return "short"; if (type == typeof(byte)) return "byte"; if (type == typeof(bool)) return "bool"; if (type == typeof(char)) return "char"; if (type == typeof(long)) return "long"; if (type == typeof(float)) return "float"; if (type == typeof(double)) return "double"; if (type == typeof(decimal)) return "decimal"; if (type == typeof(string)) return "string"; if (type == typeof(object)) return "object"; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType) return GetGenericFriendlyName(typeInfo); return type.Name; } private static string GetGenericFriendlyName(TypeInfo typeInfo) { var argumentNames = typeInfo.GenericTypeArguments.Select(GetFriendlyName).ToArray(); var baseName = typeInfo.Name.Split('`').First(); return $"{baseName}<{string.Join(", ", argumentNames)}>"; } } }
using System; using Microsoft.Extensions.Internal; namespace Scrutor { public class MissingTypeRegistrationException : InvalidOperationException { public MissingTypeRegistrationException(Type serviceType) : base($"Could not find any registered services for type '{TypeNameHelper.GetTypeDisplayName(serviceType)}'.") { ServiceType = serviceType; } public Type ServiceType { get; } } }
Fix routing tests, we DO need a database for these
using NUnit.Framework; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.template; namespace Umbraco.Tests.Routing { [TestFixture] public class LookupByAliasTests : BaseRoutingTest { public override void Initialize() { base.Initialize(); Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema = false; } /// <summary> /// We don't need a db for this test, will run faster without one /// </summary> protected override bool RequiresDbSetup { get { return false; } } [TestCase("/this/is/my/alias", 1046)] [TestCase("/anotheralias", 1046)] [TestCase("/page2/alias", 1173)] [TestCase("/2ndpagealias", 1173)] [TestCase("/only/one/alias", 1174)] [TestCase("/ONLY/one/Alias", 1174)] public void Lookup_By_Url_Alias(string urlAsString, int nodeMatch) { var routingContext = GetRoutingContext(urlAsString); var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url var docRequest = new PublishedContentRequest(url, routingContext); var lookup = new LookupByAlias(); var result = lookup.TrySetDocument(docRequest); Assert.IsTrue(result); Assert.AreEqual(docRequest.DocumentId, nodeMatch); } } }
using NUnit.Framework; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.template; namespace Umbraco.Tests.Routing { [TestFixture] public class LookupByAliasTests : BaseRoutingTest { public override void Initialize() { base.Initialize(); Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema = false; } [TestCase("/this/is/my/alias", 1046)] [TestCase("/anotheralias", 1046)] [TestCase("/page2/alias", 1173)] [TestCase("/2ndpagealias", 1173)] [TestCase("/only/one/alias", 1174)] [TestCase("/ONLY/one/Alias", 1174)] public void Lookup_By_Url_Alias(string urlAsString, int nodeMatch) { var routingContext = GetRoutingContext(urlAsString); var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url var docRequest = new PublishedContentRequest(url, routingContext); var lookup = new LookupByAlias(); var result = lookup.TrySetDocument(docRequest); Assert.IsTrue(result); Assert.AreEqual(docRequest.DocumentId, nodeMatch); } } }
Fix an error with console client test
namespace SupermarketChain.Client.Console { using System; using System.Linq; using SupermarketChain.Data.SqlServer; using SupermarketChain.Model; using SupermarketChain.Data.SqlServer.Repositories; class Program { static void Main(string[] args) { // Testing SupermarketChainDbContext var dbContext = new SupermarketChainDbContext(); Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name); Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Amstel").Name); Console.WriteLine(dbContext.Vendors.Find(2).Name); // Testing repository var dbVendors = new Repository<Vendor>(); dbVendors.Add(new Vendor { Name = "Zagorka" }); dbVendors.SaveChanges(); } } }
namespace SupermarketChain.Client.Console { using System; using System.Linq; using SupermarketChain.Data.SqlServer; using SupermarketChain.Model; using SupermarketChain.Data.SqlServer.Repositories; class Program { static void Main(string[] args) { // Testing SupermarketChainDbContext var dbContext = new SupermarketChainDbContext(); Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name); Console.WriteLine(dbContext.Vendors.FirstOrDefault(v => v.Name == "Kamenitza").Name); Console.WriteLine(dbContext.Vendors.Find(2).Name); // Testing repository var dbVendors = new Repository<Vendor>(); dbVendors.Add(new Vendor { Name = "Zagorka" }); dbVendors.SaveChanges(); } } }
Add cancellation field to progress object.
using System; using System.Threading; namespace Depends { public delegate void ProgressBarIncrementer(); public class Progress { private long _total = 0; private ProgressBarIncrementer _progBarIncr; private long _workMultiplier = 1; public static Progress NOPProgress() { ProgressBarIncrementer pbi = () => { return; }; return new Progress(pbi, 1L); } public Progress(ProgressBarIncrementer progBarIncrement, long workMultiplier) { _progBarIncr = progBarIncrement; _workMultiplier = workMultiplier; } public long TotalWorkUnits { get { return _total; } set { _total = value; } } public long UpdateEvery { get { return Math.Max(1L, _total / 100L / _workMultiplier); } } public void IncrementCounter() { _progBarIncr(); } } }
using System; using System.Threading; namespace Depends { public delegate void ProgressBarIncrementer(); public class Progress { private bool _cancelled = false; private long _total = 0; private ProgressBarIncrementer _progBarIncr; private long _workMultiplier = 1; public static Progress NOPProgress() { ProgressBarIncrementer pbi = () => { return; }; return new Progress(pbi, 1L); } public Progress(ProgressBarIncrementer progBarIncrement, long workMultiplier) { _progBarIncr = progBarIncrement; _workMultiplier = workMultiplier; } public long TotalWorkUnits { get { return _total; } set { _total = value; } } public long UpdateEvery { get { return Math.Max(1L, _total / 100L / _workMultiplier); } } public void IncrementCounter() { _progBarIncr(); } public void Cancel() { _cancelled = true; } public bool IsCancelled() { return _cancelled; } } }
Fix formatting of dates when the year comes first (JP)
using System; using System.Globalization; namespace MultiMiner.Win.Extensions { static class DateTimeExtensions { public static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateValue = dateTime.ToShortDateString(); int lastIndex = shortDateValue.LastIndexOf(CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator); return shortDateValue.Remove(lastIndex); } } }
using System; using System.Globalization; namespace MultiMiner.Win.Extensions { public static class DateTimeExtensions { public static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateString = dateTime.ToShortDateString(); //year could be at beginning (JP) or end (EN) string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator; string value1 = dateTime.Year + dateSeparator; string value2 = dateSeparator + dateTime.Year; return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty); } } }
Fix issue on possible null reference.
using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace Talagozis.Website.Controllers { public abstract class BaseController : Controller { public override void OnActionExecuting(ActionExecutingContext context) { this.ViewBag.startTime = DateTime.Now; this.ViewBag.AssemblyVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version.ToString() ?? string.Empty; base.OnActionExecuting(context); } } }
using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace Talagozis.Website.Controllers { public abstract class BaseController : Controller { public override void OnActionExecuting(ActionExecutingContext context) { this.ViewBag.startTime = DateTime.Now; this.ViewBag.AssemblyVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? string.Empty; base.OnActionExecuting(context); } } }
Simplify AbstractGrammarSpec by replacing deprecated helper methods with a sample Lexer implementation
namespace Parsley { public sealed class CharLexer : Lexer { public CharLexer(string source) : this(new Text(source)) { } public CharLexer(Text text) : base(text, new TokenMatcher(typeof(char), @".")) { } } }
namespace Parsley { public sealed class CharLexer : Lexer { public CharLexer(string source) : base(new Text(source), new TokenMatcher(typeof(char), @".")) { } } }
Revert "Reacting to CLI breaking change"
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Watcher.Core.Internal { internal class Project : IProject { public Project(ProjectModel.Project runtimeProject) { ProjectFile = runtimeProject.ProjectFilePath; ProjectDirectory = runtimeProject.ProjectDirectory; Files = runtimeProject.Files.SourceFiles.Concat( runtimeProject.Files.ResourceFiles.Values.Concat( runtimeProject.Files.PreprocessSourceFiles.Concat( runtimeProject.Files.SharedFiles))).Concat( new string[] { runtimeProject.ProjectFilePath }) .ToList(); var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json"); if (File.Exists(projectLockJsonPath)) { var lockFile = LockFileReader.Read(projectLockJsonPath, designTime: false); ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList(); } else { ProjectDependencies = new string[0]; } } public IEnumerable<string> ProjectDependencies { get; private set; } public IEnumerable<string> Files { get; private set; } public string ProjectFile { get; private set; } public string ProjectDirectory { get; private set; } private string GetProjectRelativeFullPath(string path) { return Path.GetFullPath(Path.Combine(ProjectDirectory, path)); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Watcher.Core.Internal { internal class Project : IProject { public Project(ProjectModel.Project runtimeProject) { ProjectFile = runtimeProject.ProjectFilePath; ProjectDirectory = runtimeProject.ProjectDirectory; Files = runtimeProject.Files.SourceFiles.Concat( runtimeProject.Files.ResourceFiles.Values.Concat( runtimeProject.Files.PreprocessSourceFiles.Concat( runtimeProject.Files.SharedFiles))).Concat( new string[] { runtimeProject.ProjectFilePath }) .ToList(); var projectLockJsonPath = Path.Combine(runtimeProject.ProjectDirectory, "project.lock.json"); if (File.Exists(projectLockJsonPath)) { var lockFile = LockFileReader.Read(projectLockJsonPath); ProjectDependencies = lockFile.ProjectLibraries.Select(dep => GetProjectRelativeFullPath(dep.Path)).ToList(); } else { ProjectDependencies = new string[0]; } } public IEnumerable<string> ProjectDependencies { get; private set; } public IEnumerable<string> Files { get; private set; } public string ProjectFile { get; private set; } public string ProjectDirectory { get; private set; } private string GetProjectRelativeFullPath(string path) { return Path.GetFullPath(Path.Combine(ProjectDirectory, path)); } } }
Move set-up and config code into t/c/f block - this will handle 'unhandled exeptions' that hapen outside of the OWIN pipeline.
using System; using System.IO; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Formatting.Json; namespace Experimentation.Api { public class Program { public static void Main(string[] args) { var env = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}"; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env}.json", optional: true) .AddEnvironmentVariables() .Build(); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.RollingFile(new JsonFormatter(), "Logs/log-{Date}.json") .CreateLogger(); try { Log.Information("Firing up the experimentation api..."); BuildWebHost(args, builder).Run(); } catch (Exception e) { Log.Fatal(e, "Api terminated unexpectedly"); } finally { Log.CloseAndFlush(); } } private static IWebHost BuildWebHost(string[] args, IConfiguration builder) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .UseConfiguration(builder) .Build(); } }
using System; using System.IO; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Formatting.Json; namespace Experimentation.Api { public class Program { public static void Main(string[] args) { try { var env = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}"; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env}.json", optional: true) .AddEnvironmentVariables() .Build(); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.RollingFile(new JsonFormatter(), "Logs/log-{Date}.json") .CreateLogger(); Log.Information("Firing up the experimentation api..."); BuildWebHost(args, builder).Run(); } catch (Exception e) { Log.Fatal(e, "Api terminated unexpectedly"); } finally { Log.CloseAndFlush(); } } private static IWebHost BuildWebHost(string[] args, IConfiguration builder) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .UseConfiguration(builder) .Build(); } }
Use a lifetime scope for resolution
using Autofac; using System.Management.Automation; namespace PoshGit2.Cmdlets { public class DICmdlet : Cmdlet { protected override void BeginProcessing() { base.BeginProcessing(); PoshGit2Container.Instance.InjectUnsetProperties(this); } } }
using Autofac; using System; using System.Management.Automation; namespace PoshGit2.Cmdlets { public class DICmdlet : PSCmdlet, IDisposable { private readonly ILifetimeScope _lifetimeScope; public DICmdlet() { _lifetimeScope = PoshGit2Container.Instance.BeginLifetimeScope(builder => { builder.Register<SessionState>(_ => SessionState).AsSelf(); }); } protected override void BeginProcessing() { base.BeginProcessing(); // TODO: This needs to be here for now, otherwise SessionState is not defined yet. // TODO: Is this called on each time something is piped through? _lifetimeScope.InjectUnsetProperties(this); } private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _lifetimeScope.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
Fix loop condition on Deserialize-Tilemap.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class DeserializeTilemapCmd : CliCommand { public DeserializeTilemapCmd() : base("Deserialize-Tilemap") { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Deserializing tilemap..."); workbench.Stream.Position = 0; workbench.Tilemap = new Tilemap(); int bpe = 2; // bytes per tile entry byte[] buffer = new byte[bpe]; while (workbench.Stream.Read(buffer, 0, 2) != bpe) { int scrn = buffer[0] | (buffer[1] << 8); TileEntry te = new TileEntry() { TileNumber = scrn & 0x3FF, HFlip = (scrn & (1 << 10)) != 0, VFlip = (scrn & (1 << 11)) != 0, PaletteNumber = (scrn >> 12) & 0xF }; workbench.Tilemap.TileEntries.Add(te); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class DeserializeTilemapCmd : CliCommand { public DeserializeTilemapCmd() : base("Deserialize-Tilemap") { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Deserializing tilemap..."); workbench.Stream.Position = 0; workbench.Tilemap = new Tilemap(); int bpe = 2; // bytes per tile entry byte[] buffer = new byte[bpe]; while (workbench.Stream.Read(buffer, 0, 2) == bpe) { int scrn = buffer[0] | (buffer[1] << 8); TileEntry te = new TileEntry() { TileNumber = scrn & 0x3FF, HFlip = (scrn & (1 << 10)) != 0, VFlip = (scrn & (1 << 11)) != 0, PaletteNumber = (scrn >> 12) & 0xF }; workbench.Tilemap.TileEntries.Add(te); } } } }
Add TODO to remove extracted file after translating it
using System; using System.IO; using Newtonsoft.Json; using SmartMeter.Business.Extractor; using SmartMeter.Business.Interface; using SmartMeter.Business.Interface.Extractor; using SmartMeter.Business.Interface.Translator; namespace SmartMeter.Business.Translator { public class TranslatorService { public void Execute() { FileInfo[] extractedFiles = _ListExtractedFiles(); foreach (FileInfo extractedFile in extractedFiles) { try { ITranslateFile fileTranslator = new FileTranslator(); ITelegram telegram = fileTranslator.Translate(extractedFile); string serializedTelegram = JsonConvert.SerializeObject(telegram); IWriteFile fileWriter = new FileWriter(); fileWriter .WithPath(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "translated")) .WithFilename(_CreateFilename(extractedFile)) .WithContents(serializedTelegram) .Write(); } catch (Exception ex) { Console.WriteLine($"An error occured while translating file '{extractedFile.FullName}': {ex}"); } } } private FileInfo[] _ListExtractedFiles() { DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "extracted")); //TODO: Filter for specific file extensions to prevent reading uncompleted files return directoryInfo.GetFiles(); } private string _CreateFilename(FileInfo extractedFile) { return $"{Path.GetFileNameWithoutExtension(extractedFile.Name)}.telegram"; } } }
using System; using System.IO; using Newtonsoft.Json; using SmartMeter.Business.Extractor; using SmartMeter.Business.Interface; using SmartMeter.Business.Interface.Extractor; using SmartMeter.Business.Interface.Translator; namespace SmartMeter.Business.Translator { public class TranslatorService { public void Execute() { FileInfo[] extractedFiles = _ListExtractedFiles(); foreach (FileInfo extractedFile in extractedFiles) { try { ITranslateFile fileTranslator = new FileTranslator(); ITelegram telegram = fileTranslator.Translate(extractedFile); string serializedTelegram = JsonConvert.SerializeObject(telegram); IWriteFile fileWriter = new FileWriter(); fileWriter .WithPath(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "translated")) .WithFilename(_CreateFilename(extractedFile)) .WithContents(serializedTelegram) .Write(); //TODO: Remove extracted file after created translated file } catch (Exception ex) { Console.WriteLine($"An error occured while translating file '{extractedFile.FullName}': {ex}"); } } } private FileInfo[] _ListExtractedFiles() { DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Directory.GetDirectoryRoot(AppContext.BaseDirectory), "applicationdata", "smartmeter", "extracted")); //TODO: Filter for specific file extensions to prevent reading uncompleted files return directoryInfo.GetFiles(); } private string _CreateFilename(FileInfo extractedFile) { return $"{Path.GetFileNameWithoutExtension(extractedFile.Name)}.telegram"; } } }
Update the TryGetJointPose docs to accurately describe the set of inputs it can take.
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Try to find the first matching hand controller and return the pose of the requested joint for that hand. /// </summary> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Input { public static class HandJointUtils { /// <summary> /// Tries to get the the pose of the requested joint for the first controller with the specified handedness. /// </summary> /// <param name="joint">The requested joint</param> /// <param name="handedness">The specific hand of interest. This should be either Handedness.Left or Handedness.Right</param> /// <param name="pose">The output pose data</param> public static bool TryGetJointPose(TrackedHandJoint joint, Handedness handedness, out MixedRealityPose pose) { IMixedRealityHand hand = FindHand(handedness); if (hand != null) { return hand.TryGetJoint(joint, out pose); } pose = MixedRealityPose.ZeroIdentity; return false; } /// <summary> /// Find the first detected hand controller with matching handedness. /// </summary> /// <remarks> /// The given handeness should be either Handedness.Left or Handedness.Right. /// </remarks> public static IMixedRealityHand FindHand(Handedness handedness) { foreach (var detectedController in MixedRealityToolkit.InputSystem.DetectedControllers) { var hand = detectedController as IMixedRealityHand; if (hand != null) { if (detectedController.ControllerHandedness == handedness) { return hand; } } } return null; } } }
Update the Empty module template.
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName); var installModel = new InstallModel(); Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext); moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer; moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName; moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password; ModuleInfo.Save(moduleInfo); // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
Add using for Template class.
using ExoWeb; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using ExoWeb.Templates; using System.IO; using System.Linq; namespace ExoWeb.UnitTests.Server { /// <summary> ///This is a test class for ExoWebTest and is intended ///to contain all ExoWebTest Unit Tests ///</summary> [TestClass()] public class ExoWebTest { [TestMethod] public void ParseTemplate() { var templates = Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates", "*.htm").Union( Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates\sections", "*.htm")) .Where(p => !p.Contains("Reports.htm")) .SelectMany(p => Template.Load(p)); foreach (var template in templates) Console.WriteLine(template); } } }
using System; using System.IO; using System.Linq; using ExoWeb.Templates.MicrosoftAjax; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ExoWeb.UnitTests.Server { /// <summary> ///This is a test class for ExoWebTest and is intended ///to contain all ExoWebTest Unit Tests ///</summary> [TestClass()] public class ExoWebTest { [TestMethod] public void ParseTemplate() { var templates = Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates", "*.htm").Union( Directory.GetFiles(@"C:\Users\thomasja\Projects\VC3.TestView\Mainline\VC3.TestView.WebUI\Common\templates\sections", "*.htm")) .Where(p => !p.Contains("Reports.htm")) .SelectMany(p => Template.Load(p)); foreach (var template in templates) Console.WriteLine(template); } } }
Fix loader pushing children screens before it is displayed itself
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Menu; using OpenTK; namespace osu.Game.Screens { public class Loader : OsuScreen { public override bool ShowOverlays => false; public Loader() { ValidForResume = false; } protected override void LogoArriving(OsuLogo logo, bool resuming) { base.LogoArriving(logo, resuming); logo.RelativePositionAxes = Axes.Both; logo.Triangles = false; logo.Position = new Vector2(0.9f); logo.Scale = new Vector2(0.2f); logo.FadeInFromZero(5000, Easing.OutQuint); } [BackgroundDependencyLoader] private void load(OsuGameBase game) { if (game.IsDeployedBuild) LoadComponentAsync(new Disclaimer(), d => Push(d)); else LoadComponentAsync(new Intro(), d => Push(d)); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Menu; using OpenTK; using osu.Framework.Screens; namespace osu.Game.Screens { public class Loader : OsuScreen { private bool showDisclaimer; public override bool ShowOverlays => false; public Loader() { ValidForResume = false; } protected override void LogoArriving(OsuLogo logo, bool resuming) { base.LogoArriving(logo, resuming); logo.RelativePositionAxes = Axes.None; logo.Triangles = false; logo.Origin = Anchor.BottomRight; logo.Anchor = Anchor.BottomRight; logo.Position = new Vector2(-40); logo.Scale = new Vector2(0.2f); logo.FadeInFromZero(5000, Easing.OutQuint); } protected override void OnEntering(Screen last) { base.OnEntering(last); if (showDisclaimer) LoadComponentAsync(new Disclaimer(), d => Push(d)); else LoadComponentAsync(new Intro(), d => Push(d)); } protected override void LogoSuspending(OsuLogo logo) { base.LogoSuspending(logo); logo.FadeOut(100).OnComplete(l => { l.Anchor = Anchor.TopLeft; l.Origin = Anchor.Centre; }); } [BackgroundDependencyLoader] private void load(OsuGameBase game) { showDisclaimer = game.IsDeployedBuild; } } }
Bump dev version to v0.11
using Mono.Addins; using Mono.Addins.Description; [assembly: Addin( "JustEnoughVi", Namespace = "JustEnoughVi", Version = "0.10" )] [assembly: AddinName("Just Enough Vi")] [assembly: AddinCategory("IDE extensions")] [assembly: AddinDescription("Simplified Vi/Vim mode for MonoDevelop/Xamarin Studio.")] [assembly: AddinAuthor("Toni Spets")]
using Mono.Addins; using Mono.Addins.Description; [assembly: Addin( "JustEnoughVi", Namespace = "JustEnoughVi", Version = "0.11" )] [assembly: AddinName("Just Enough Vi")] [assembly: AddinCategory("IDE extensions")] [assembly: AddinDescription("Simplified Vi/Vim mode for MonoDevelop/Xamarin Studio.")] [assembly: AddinAuthor("Toni Spets")]
Change of domain name to api.socketlabs.com
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Xml.Linq; namespace SocketLabs.OnDemand.Api { internal class Program { private static void Main(string[] args) { int accountId = 1000; // YOUR-ACCOUNT-ID string userName = "YOUR-USER-NAME"; string password = "YOUR-API-PASSWORD"; var apiUri = new Uri("https://api.email-od.com/messagesProcessed?type=xml&accountId=" + accountId); var creds = new NetworkCredential(userName, password); var auth = creds.GetCredential(apiUri, "Basic"); WebRequest request = WebRequest.Create(apiUri); request.Credentials = auth; using (WebResponse response = request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { XDocument apiResponse = XDocument.Load(reader); var addressResponses = from item in apiResponse.Descendants("collection").Descendants("item") select new { ToAddress = item.Element("ToAddress").Value, Response = item.Element("Response").Value }; foreach (var item in addressResponses) { Console.WriteLine(String.Format("**** (( {0} )) ****", item.ToAddress)); Console.WriteLine(item.Response); } } Console.Read(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Xml.Linq; namespace SocketLabs.OnDemand.Api { internal class Program { private static void Main(string[] args) { int accountId = 1000; // YOUR-ACCOUNT-ID string userName = "YOUR-USER-NAME"; string password = "YOUR-API-PASSWORD"; var apiUri = new Uri("https://api.socketlabs.com/messagesProcessed?type=xml&accountId=" + accountId); var creds = new NetworkCredential(userName, password); var auth = creds.GetCredential(apiUri, "Basic"); WebRequest request = WebRequest.Create(apiUri); request.Credentials = auth; using (WebResponse response = request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { XDocument apiResponse = XDocument.Load(reader); var addressResponses = from item in apiResponse.Descendants("collection").Descendants("item") select new { ToAddress = item.Element("ToAddress").Value, Response = item.Element("Response").Value }; foreach (var item in addressResponses) { Console.WriteLine(String.Format("**** (( {0} )) ****", item.ToAddress)); Console.WriteLine(item.Response); } } Console.Read(); } } }
Make Check Connectionstring via builder generic
using System; using System.Collections.Generic; using System.Data.SqlClient; namespace Dirtybase.App.Options.Validators { class SqlOptionsValidator : IOptionsValidator { public Errors Errors(DirtyOptions options) { var errors = new Errors(); if(string.IsNullOrWhiteSpace(options.ConnectionString)) { errors.Add(Constants.InvalidConnectionString); } errors.AddRange(CheckConnectionString(options.ConnectionString)); return errors; } private static IEnumerable<string> CheckConnectionString(string conncetionString) { try { new SqlConnectionStringBuilder(conncetionString); } catch(Exception) { return new Errors{Constants.InvalidConnectionString}; } return new Errors(); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; namespace Dirtybase.App.Options.Validators { class SqlOptionsValidator : IOptionsValidator { public Errors Errors(DirtyOptions options) { var errors = new Errors(); if(string.IsNullOrWhiteSpace(options.ConnectionString)) { errors.Add(Constants.InvalidConnectionString); } errors.AddRange(CheckConnectionString<SqlConnectionStringBuilder>(options.ConnectionString)); return errors; } private static IEnumerable<string> CheckConnectionString<TBuilder>(string conncetionString) where TBuilder : DbConnectionStringBuilder { try { Activator.CreateInstance(typeof(TBuilder), conncetionString); } catch(Exception) { return new Errors{Constants.InvalidConnectionString}; } return new Errors(); } } }
Fix memory leak when using the SDL2 clipboard
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern string SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { return SDL_GetClipboardText(); } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern string SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { string text = SDL_GetClipboardText(); IntPtr ptrToText = Marshal.StringToHGlobalAnsi(text); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
Send data always as application/octet-stream
//----------------------------------------------------------------------- // <copyright file="BackgroundUpload.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> // <author>Mark Junker</author> //----------------------------------------------------------------------- using System.IO; using System.Threading; using System.Threading.Tasks; using File = RestSharp.Portable.Google.Drive.Model.File; namespace FubarDev.FtpServer.FileSystem.GoogleDrive { internal class BackgroundUpload : IBackgroundTransfer { private readonly string _tempFileName; private readonly GoogleDriveFileSystem _fileSystem; private bool _disposedValue; public BackgroundUpload(string fullPath, File file, string tempFileName, GoogleDriveFileSystem fileSystem, long fileSize) { TransferId = fullPath; File = file; _tempFileName = tempFileName; _fileSystem = fileSystem; FileSize = fileSize; } public File File { get; } public long FileSize { get; } public string TransferId { get; } public async Task Start(CancellationToken cancellationToken) { using (var stream = new FileStream(_tempFileName, FileMode.Open)) { await _fileSystem.Service.UploadAsync(File, stream, cancellationToken); } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { System.IO.File.Delete(_tempFileName); _fileSystem.UploadFinished(File.Id); } _disposedValue = true; } } } }
//----------------------------------------------------------------------- // <copyright file="BackgroundUpload.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> // <author>Mark Junker</author> //----------------------------------------------------------------------- using System.IO; using System.Threading; using System.Threading.Tasks; using File = RestSharp.Portable.Google.Drive.Model.File; namespace FubarDev.FtpServer.FileSystem.GoogleDrive { internal class BackgroundUpload : IBackgroundTransfer { private readonly string _tempFileName; private readonly GoogleDriveFileSystem _fileSystem; private bool _disposedValue; public BackgroundUpload(string fullPath, File file, string tempFileName, GoogleDriveFileSystem fileSystem, long fileSize) { TransferId = fullPath; File = file; _tempFileName = tempFileName; _fileSystem = fileSystem; FileSize = fileSize; } public File File { get; } public long FileSize { get; } public string TransferId { get; } public async Task Start(CancellationToken cancellationToken) { using (var stream = new FileStream(_tempFileName, FileMode.Open)) { await _fileSystem.Service.UploadAsync(File.Id, stream, "application/octet-stream", cancellationToken); } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { System.IO.File.Delete(_tempFileName); _fileSystem.UploadFinished(File.Id); } _disposedValue = true; } } } }
Add handling of null values in the Papers property
using System.Collections.Generic; using Newtonsoft.Json; namespace PrintNode.Net { public class PrintNodePrinterCapabilities { [JsonProperty("bins")] public IEnumerable<string> Bins { get; set; } [JsonProperty("collate")] public bool Collate { get; set; } [JsonProperty("copies")] public int Copies { get; set; } [JsonProperty("color")] public bool Color { get; set; } [JsonProperty("dpis")] public IEnumerable<string> Dpis { get; set; } [JsonProperty("extent")] public int[][] Extent { get; set; } [JsonProperty("medias")] public IEnumerable<string> Medias { get; set; } [JsonProperty("nup")] public IEnumerable<int> Nup { get; set; } [JsonProperty("papers")] public Dictionary<string, int[]> Papers { get; set; } [JsonProperty("printRate")] public Dictionary<string, string> PrintRate { get; set; } [JsonProperty("supports_custom_paper_size")] public bool SupportsCustomPaperSize { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace PrintNode.Net { public class PrintNodePrinterCapabilities { [JsonProperty("bins")] public IEnumerable<string> Bins { get; set; } [JsonProperty("collate")] public bool Collate { get; set; } [JsonProperty("copies")] public int Copies { get; set; } [JsonProperty("color")] public bool Color { get; set; } [JsonProperty("dpis")] public IEnumerable<string> Dpis { get; set; } [JsonProperty("extent")] public int[][] Extent { get; set; } [JsonProperty("medias")] public IEnumerable<string> Medias { get; set; } [JsonProperty("nup")] public IEnumerable<int> Nup { get; set; } [JsonProperty("papers")] public Dictionary<string, int?[]> Papers { get; set; } [JsonProperty("printRate")] public Dictionary<string, string> PrintRate { get; set; } [JsonProperty("supports_custom_paper_size")] public bool SupportsCustomPaperSize { get; set; } } }
Add new overload to the Deserialize method
using System.IO; namespace Gigobyte.Mockaroo.Serialization { public interface ISerializable { Stream Serialize(); void Deserialize(Stream stream); } }
using System.IO; namespace Gigobyte.Mockaroo.Serialization { public interface ISerializable { Stream Serialize(); void Deserialize(byte[] bytes); void Deserialize(Stream stream); } }