Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Rephrase the Skipped sample to use runtime skips rather than declarative skips, demonstrating how runtime skips are superior: we have case-by-case skippability, implicit skips by conditionally avoiding executing a case, and the ability to avoid instantiating a test class if it is entirely marked as skipped. | namespace Fixie.Samples.Skipped
{
using System;
using System.Reflection;
public class CustomConvention : Convention
{
public CustomConvention()
{
Classes
.InTheSameNamespaceAs(typeof(CustomConvention))
.NameEndsWith("Tests");
Methods
.OrderBy(x => x.Name, StringComparer.Ordinal);
CaseExecution
.Skip(SkipDueToClassLevelSkipAttribute, @case => "Whole class skipped")
.Skip(SkipDueToMethodLevelSkipAttribute);
ClassExecution
.Lifecycle<CreateInstancePerClass>();
}
static bool SkipDueToClassLevelSkipAttribute(MethodInfo testMethod)
=> testMethod.DeclaringType.Has<SkipAttribute>();
static bool SkipDueToMethodLevelSkipAttribute(MethodInfo testMethod)
=> testMethod.Has<SkipAttribute>();
}
} | namespace Fixie.Samples.Skipped
{
using System;
public class CustomConvention : Convention
{
public CustomConvention()
{
Classes
.InTheSameNamespaceAs(typeof(CustomConvention))
.NameEndsWith("Tests");
Methods
.OrderBy(x => x.Name, StringComparer.Ordinal);
ClassExecution
.Lifecycle<SkipLifecycle>();
}
class SkipLifecycle : Lifecycle
{
public void Execute(TestClass testClass, Action<CaseAction> runCases)
{
var skipClass = testClass.Type.Has<SkipAttribute>();
var instance = skipClass ? null : testClass.Construct();
runCases(@case =>
{
var skipMethod = @case.Method.Has<SkipAttribute>();
if (skipClass)
@case.Skip("Whole class skipped");
else if (!skipMethod)
@case.Execute(instance);
});
instance.Dispose();
}
}
}
} |
Order the files and dirs | using DeveImageOptimizer.State.StoringProcessedDirectories;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace DeveImageOptimizer.Helpers
{
public static class FileHelperMethods
{
public static void SafeDeleteTempFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}");
}
}
public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null)
{
if (filter == null)
{
filter = t => true;
}
var files = Directory.GetFiles(directory).Where(filter).ToList();
foreach (var file in files)
{
yield return new FileAndCountOfFilesInDirectory()
{
FilePath = file,
DirectoryPath = directory,
CountOfFilesInDirectory = files.Count
};
}
var directories = Directory.GetDirectories(directory);
foreach (var subDirectory in directories)
{
var recursedFIles = RecurseFiles(subDirectory, filter);
foreach (var subFile in recursedFIles)
{
yield return subFile;
}
}
}
}
}
| using DeveImageOptimizer.State.StoringProcessedDirectories;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace DeveImageOptimizer.Helpers
{
public static class FileHelperMethods
{
public static void SafeDeleteTempFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}");
}
}
public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null)
{
if (filter == null)
{
filter = t => true;
}
var files = Directory.GetFiles(directory).Where(filter).OrderBy(t => t).ToList();
foreach (var file in files)
{
yield return new FileAndCountOfFilesInDirectory()
{
FilePath = file,
DirectoryPath = directory,
CountOfFilesInDirectory = files.Count
};
}
var directories = Directory.GetDirectories(directory).OrderBy(t => t).ToList();
foreach (var subDirectory in directories)
{
var recursedFIles = RecurseFiles(subDirectory, filter);
foreach (var subFile in recursedFIles)
{
yield return subFile;
}
}
}
}
}
|
Fix failing test for abstract get-set indexer | using System;
using System.CodeDom;
using Mono.Cecil;
namespace PublicApiGenerator
{
public static class PropertyNameBuilder
{
public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition,
MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes)
{
string name = propertyDefinition.Name;
if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface)
{
return name;
}
var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e =>
e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal));
return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name,
CodeNormalizer.PropertyModifierMarkerTemplate);
}
}
}
| using System;
using System.CodeDom;
using Mono.Cecil;
namespace PublicApiGenerator
{
public static class PropertyNameBuilder
{
public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition,
MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes)
{
string name = propertyDefinition.Name;
if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface || propertyDefinition.HasParameters)
{
return name;
}
var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e =>
e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal));
return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name,
CodeNormalizer.PropertyModifierMarkerTemplate);
}
}
}
|
Remove a test that tests Dictionary | // 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 Xunit;
namespace Microsoft.AspNet.Mvc
{
public class MvcOptionsTest
{
[Fact]
public void MaxValidationError_ThrowsIfValueIsOutOfRange()
{
// Arrange
var options = new MvcOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1);
Assert.Equal("value", ex.ParamName);
}
[Fact]
public void ThrowsWhenMultipleCacheProfilesWithSameNameAreAdded()
{
// Arrange
var options = new MvcOptions();
options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 10 });
// Act & Assert
var ex = Assert.Throws<ArgumentException>(
() => options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 5 }));
Assert.Equal("An item with the same key has already been added.", ex.Message);
}
}
} | // 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 Xunit;
namespace Microsoft.AspNet.Mvc
{
public class MvcOptionsTest
{
[Fact]
public void MaxValidationError_ThrowsIfValueIsOutOfRange()
{
// Arrange
var options = new MvcOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1);
Assert.Equal("value", ex.ParamName);
}
}
} |
Use correct queue name in length commands | using System;
using CommandLine;
namespace InEngine.Core.Queue.Commands
{
public class Length : AbstractCommand
{
public override void Run()
{
var broker = Broker.Make();
var leftPadding = 15;
Warning("Primary Queue:");
InfoText("Pending".PadLeft(leftPadding));
Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10));
InfoText("In-progress".PadLeft(leftPadding));
Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10));
ErrorText("Failed".PadLeft(leftPadding));
Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10));
Newline();
Warning("Secondary Queue:");
InfoText("Pending".PadLeft(leftPadding));
Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10));
InfoText("In-progress".PadLeft(leftPadding));
Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10));
ErrorText("Failed".PadLeft(leftPadding));
Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10));
Newline();
}
}
}
| using System;
using CommandLine;
namespace InEngine.Core.Queue.Commands
{
public class Length : AbstractCommand
{
public override void Run()
{
var broker = Broker.Make();
var leftPadding = 15;
Warning("Primary Queue:");
InfoText("Pending".PadLeft(leftPadding));
Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10));
InfoText("In-progress".PadLeft(leftPadding));
Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10));
ErrorText("Failed".PadLeft(leftPadding));
Line(broker.GetPrimaryFailedQueueLength().ToString().PadLeft(10));
Newline();
Warning("Secondary Queue:");
InfoText("Pending".PadLeft(leftPadding));
Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10));
InfoText("In-progress".PadLeft(leftPadding));
Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10));
ErrorText("Failed".PadLeft(leftPadding));
Line(broker.GetSecondaryFailedQueueLength().ToString().PadLeft(10));
Newline();
}
}
}
|
Rewrite existing test scene somewhat | // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneStarCounter : OsuTestScene
{
public TestSceneStarCounter()
{
StarCounter stars = new StarCounter
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Current = 5,
};
Add(stars);
SpriteText starsLabel = new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Scale = new Vector2(2),
Y = 50,
Text = stars.Current.ToString("0.00"),
};
Add(starsLabel);
AddRepeatStep(@"random value", delegate
{
stars.Current = RNG.NextSingle() * (stars.StarCount + 1);
starsLabel.Text = stars.Current.ToString("0.00");
}, 10);
AddStep(@"Stop animation", delegate
{
stars.StopAnimation();
});
AddStep(@"Reset", delegate
{
stars.Current = 0;
starsLabel.Text = stars.Current.ToString("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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneStarCounter : OsuTestScene
{
private readonly StarCounter starCounter;
private readonly OsuSpriteText starsLabel;
public TestSceneStarCounter()
{
starCounter = new StarCounter
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
};
Add(starCounter);
starsLabel = new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Scale = new Vector2(2),
Y = 50,
};
Add(starsLabel);
setStars(5);
AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10);
AddStep("stop animation", () => starCounter.StopAnimation());
AddStep("reset", () => setStars(0));
}
private void setStars(float stars)
{
starCounter.Current = stars;
starsLabel.Text = starCounter.Current.ToString("0.00");
}
}
}
|
Enable test parallelization on local. | using Xunit;
// This is a work-around for #11.
// https://github.com/CXuesong/WikiClientLibrary/issues/11
// We are using Bot Password on CI, which may naturally evade the issue.
#if !ENV_CI_BUILD
[assembly: CollectionBehavior(DisableTestParallelization = true)]
#endif
| using Xunit;
// This is a work-around for #11.
// https://github.com/CXuesong/WikiClientLibrary/issues/11
// We are using Bot Password on CI, which may naturally evade the issue.
// [assembly: CollectionBehavior(DisableTestParallelization = true)]
|
Remove expiration date of DesignScript | using System;
namespace ProtoCore.Utils
{
public class Validity
{
public static void Assert(bool cond)
{
if (!cond)
throw new Exceptions.CompilerInternalException("");
}
public static void Assert(bool cond, string message)
{
if (!cond)
throw new Exceptions.CompilerInternalException(message);
}
private static DateTime? mAppStartupTime = null;
public static void AssertExpiry()
{
//Expires on 30th September 2013
DateTime expires = new DateTime(2013, 9, 30);
if(!mAppStartupTime.HasValue)
mAppStartupTime = DateTime.Now;
if (mAppStartupTime.Value >= expires)
throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires);
}
}
public class ProductExpiredException : Exception
{
public ProductExpiredException(string message, DateTime expirydate)
: base(message)
{
ExpiryDate = expirydate;
}
public DateTime ExpiryDate { get; private set; }
}
}
| using System;
namespace ProtoCore.Utils
{
public class Validity
{
public static void Assert(bool cond)
{
if (!cond)
throw new Exceptions.CompilerInternalException("");
}
public static void Assert(bool cond, string message)
{
if (!cond)
throw new Exceptions.CompilerInternalException(message);
}
private static DateTime? mAppStartupTime = null;
public static void AssertExpiry()
{
//Expires on 30th September 2013
/*
DateTime expires = new DateTime(2013, 9, 30);
if(!mAppStartupTime.HasValue)
mAppStartupTime = DateTime.Now;
if (mAppStartupTime.Value >= expires)
throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires);
*/
}
}
public class ProductExpiredException : Exception
{
public ProductExpiredException(string message, DateTime expirydate)
: base(message)
{
ExpiryDate = expirydate;
}
public DateTime ExpiryDate { get; private set; }
}
}
|
Add HttpCode convenience property to exception | using System;
using System.Dynamic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace Rackspace.CloudOffice
{
public class ApiException : Exception
{
public dynamic Response { get; private set; }
public ApiException(WebException ex) : base(GetErrorMessage(ex), ex)
{
Response = ParseResponse(ex.Response);
}
static object ParseResponse(WebResponse response)
{
if (response == null)
return null;
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var raw = reader.ReadToEnd();
try
{
return JsonConvert.DeserializeObject<ExpandoObject>(raw);
}
catch
{
return raw;
}
}
}
static string GetErrorMessage(WebException ex)
{
var r = ex.Response as HttpWebResponse;
return r == null
? ex.Message
: $"{r.StatusCode:d} - {r.Headers["x-error-message"]}";
}
}
}
| using System;
using System.Dynamic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace Rackspace.CloudOffice
{
public class ApiException : Exception
{
public dynamic Response { get; private set; }
public HttpStatusCode? HttpCode { get; private set; }
public ApiException(WebException ex) : base(GetErrorMessage(ex), ex)
{
Response = ParseResponse(ex.Response);
var webResponse = ex.Response as HttpWebResponse;
if (webResponse != null)
HttpCode = webResponse.StatusCode;
}
static object ParseResponse(WebResponse response)
{
if (response == null)
return null;
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var raw = reader.ReadToEnd();
try
{
return JsonConvert.DeserializeObject<ExpandoObject>(raw);
}
catch
{
return raw;
}
}
}
static string GetErrorMessage(WebException ex)
{
var r = ex.Response as HttpWebResponse;
return r == null
? ex.Message
: $"{r.StatusCode:d} - {r.Headers["x-error-message"]}";
}
}
}
|
Modify the MeidoHook interface to allow communicating to the plugins they need to stop. That way they can release whatever resources they're holding or stop threads/timers to have running seperate from the main thread. This will make it possible to have MeidoBot stop the entire program from top-down. | using System;
using System.Collections.Generic;
namespace MeidoCommon
{
public interface IMeidoHook
{
string Name { get; }
string Version { get; }
Dictionary<string, string> Help { get; }
string Prefix { set; }
}
public interface IIrcMessage
{
string Message { get; }
string[] MessageArray { get; }
string Channel { get; }
string Nick { get; }
string Ident { get; }
string Host { get; }
}
public interface IMeidoComm
{
string ConfDir { get; }
}
public interface IIrcComm
{
void AddChannelMessageHandler(Action<IIrcMessage> handler);
void AddQueryMessageHandler(Action<IIrcMessage> handler);
void SendMessage(string target, string message);
void DoAction(string target, string action);
void SendNotice(string target, string message);
string[] GetChannels();
bool IsMe(string nick);
}
} | using System;
using System.Collections.Generic;
namespace MeidoCommon
{
public interface IMeidoHook
{
// Things the plugin provides us with.
string Name { get; }
string Version { get; }
Dictionary<string, string> Help { get; }
// Things we provide to the plugin.
string Prefix { set; }
// Method to signal to the plugins they need to stop whatever seperate threads they have running.
// As well as to save/deserialize whatever it needs to.
void Stop();
}
public interface IIrcMessage
{
string Message { get; }
string[] MessageArray { get; }
string Channel { get; }
string Nick { get; }
string Ident { get; }
string Host { get; }
}
public interface IMeidoComm
{
string ConfDir { get; }
}
public interface IIrcComm
{
void AddChannelMessageHandler(Action<IIrcMessage> handler);
void AddQueryMessageHandler(Action<IIrcMessage> handler);
void SendMessage(string target, string message);
void DoAction(string target, string action);
void SendNotice(string target, string message);
string[] GetChannels();
bool IsMe(string nick);
}
} |
Make method virtual so clients can decorate behavior. | using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
namespace AspNet.WebApi.HtmlMicrodataFormatter
{
public class DocumentationController : ApiController
{
public IDocumentationProviderEx DocumentationProvider { get; set; }
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
if (DocumentationProvider != null) return;
DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider))
as IDocumentationProviderEx;
if (DocumentationProvider == null)
{
var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.",
typeof(DocumentationController),
typeof(WebApiHtmlDocumentationProvider),
typeof(IDocumentationProvider));
throw new InvalidOperationException(msg);
}
}
public SimpleApiDocumentation GetDocumentation()
{
var apiExplorer = Configuration.Services.GetApiExplorer();
var documentation = new SimpleApiDocumentation();
foreach (var api in apiExplorer.ApiDescriptions)
{
var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor;
documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration));
documentation[controllerDescriptor.ControllerName].Documentation =
DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType);
}
return documentation;
}
}
} | using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
namespace AspNet.WebApi.HtmlMicrodataFormatter
{
public class DocumentationController : ApiController
{
public IDocumentationProviderEx DocumentationProvider { get; set; }
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
if (DocumentationProvider != null) return;
DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider))
as IDocumentationProviderEx;
if (DocumentationProvider == null)
{
var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.",
typeof(DocumentationController),
typeof(WebApiHtmlDocumentationProvider),
typeof(IDocumentationProvider));
throw new InvalidOperationException(msg);
}
}
public virtual SimpleApiDocumentation GetDocumentation()
{
var apiExplorer = Configuration.Services.GetApiExplorer();
var documentation = new SimpleApiDocumentation();
foreach (var api in apiExplorer.ApiDescriptions)
{
var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor;
documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration));
documentation[controllerDescriptor.ControllerName].Documentation =
DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType);
}
return documentation;
}
}
} |
Test directory creation access by creating a directory (not a file) | using System.IO;
using Arkivverket.Arkade.Core.Base;
using Arkivverket.Arkade.GUI.Properties;
namespace Arkivverket.Arkade.GUI.Util
{
public static class ArkadeProcessingAreaLocationSetting
{
public static string Get()
{
Settings.Default.Reload();
return Settings.Default.ArkadeProcessingAreaLocation;
}
public static void Set(string locationSetting)
{
Settings.Default.ArkadeProcessingAreaLocation = locationSetting;
Settings.Default.Save();
}
public static bool IsValid()
{
try
{
string definedLocation = Get();
return DirectoryIsWritable(definedLocation);
}
catch
{
return false; // Invalid path string in settings
}
}
public static bool IsApplied()
{
string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty;
string definedLocation = Get();
return appliedLocation.Equals(definedLocation);
}
private static bool DirectoryIsWritable(string directory)
{
if (string.IsNullOrWhiteSpace(directory))
return false;
string tmpFile = Path.Combine(directory, Path.GetRandomFileName());
try
{
using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose))
{
// Attempt to write temporary file to the directory
}
return true;
}
catch
{
return false;
}
}
}
}
| using System.IO;
using Arkivverket.Arkade.Core.Base;
using Arkivverket.Arkade.GUI.Properties;
namespace Arkivverket.Arkade.GUI.Util
{
public static class ArkadeProcessingAreaLocationSetting
{
public static string Get()
{
Settings.Default.Reload();
return Settings.Default.ArkadeProcessingAreaLocation;
}
public static void Set(string locationSetting)
{
Settings.Default.ArkadeProcessingAreaLocation = locationSetting;
Settings.Default.Save();
}
public static bool IsValid()
{
try
{
string definedLocation = Get();
return DirectoryIsWritable(definedLocation);
}
catch
{
return false; // Invalid path string in settings
}
}
public static bool IsApplied()
{
string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty;
string definedLocation = Get();
return appliedLocation.Equals(definedLocation);
}
private static bool DirectoryIsWritable(string directory)
{
if (string.IsNullOrWhiteSpace(directory))
return false;
string tmpDirectory = Path.Combine(directory, "arkade-writeaccess-test");
try
{
Directory.CreateDirectory(tmpDirectory);
return true;
}
catch
{
return false;
}
finally
{
if (Directory.Exists(tmpDirectory))
Directory.Delete(tmpDirectory);
}
}
}
}
|
Check for parent controller on same object too, not just parents | using Pear.InteractionEngine.Utils;
using System;
using UnityEditor;
using UnityEngine;
namespace Pear.InteractionEngine.Controllers {
[CustomEditor(typeof(ControllerBehaviorBase), true)]
[CanEditMultipleObjects]
public class ControllerBehaviorEditor : Editor {
// The controller property
SerializedProperty _controller;
void OnEnable()
{
_controller = serializedObject.FindProperty("_controller");
}
/// <summary>
/// Attempt to set the controller if it is not set
/// </summary>
public override void OnInspectorGUI()
{
serializedObject.Update();
// If a reference to the controller is not set
// try to find it on the game object
if (_controller.objectReferenceValue == null)
{
// Get the type of controller by examing the templated argument
// pased to the controller behavior
Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0];
// Check to see if this component has a parent controller.
Transform parent = ((Component)target).transform.parent;
while(_controller.objectReferenceValue == null && parent != null)
{
_controller.objectReferenceValue = parent.GetComponent(typeOfController);
if (_controller.objectReferenceValue == null)
parent = parent.parent;
}
}
serializedObject.ApplyModifiedProperties();
DrawDefaultInspector();
}
}
}
| using Pear.InteractionEngine.Utils;
using System;
using UnityEditor;
using UnityEngine;
namespace Pear.InteractionEngine.Controllers {
[CustomEditor(typeof(ControllerBehaviorBase), true)]
[CanEditMultipleObjects]
public class ControllerBehaviorEditor : Editor {
// The controller property
SerializedProperty _controller;
void OnEnable()
{
_controller = serializedObject.FindProperty("_controller");
}
/// <summary>
/// Attempt to set the controller if it is not set
/// </summary>
public override void OnInspectorGUI()
{
serializedObject.Update();
// If a reference to the controller is not set
// try to find it on the game object
if (_controller.objectReferenceValue == null)
{
// Get the type of controller by examing the templated argument
// pased to the controller behavior
Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0];
// Check to see if this component has a controller on the same gameobject or one of its parents.
Transform objTpCheck = ((Component)target).transform;
while(_controller.objectReferenceValue == null && objTpCheck != null)
{
_controller.objectReferenceValue = objTpCheck.GetComponent(typeOfController);
if (_controller.objectReferenceValue == null)
objTpCheck = objTpCheck.parent;
}
}
serializedObject.ApplyModifiedProperties();
DrawDefaultInspector();
}
}
}
|
Remove correct page on back button press | using System;
using System.Linq;
using Android.Content;
using Android.OS;
using Rg.Plugins.Popup.Droid.Impl;
using Rg.Plugins.Popup.Droid.Renderers;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace Rg.Plugins.Popup
{
public static class Popup
{
internal static event EventHandler OnInitialized;
internal static bool IsInitialized { get; private set; }
internal static Context Context { get; private set; }
public static void Init(Context context, Bundle bundle)
{
LinkAssemblies();
Context = context;
IsInitialized = true;
OnInitialized?.Invoke(null, EventArgs.Empty);
}
public static bool SendBackPressed(Action backPressedHandler = null)
{
var popupNavigationInstance = PopupNavigation.Instance;
if (popupNavigationInstance.PopupStack.Count > 0)
{
var lastPage = popupNavigationInstance.PopupStack.Last();
var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed();
if (!isPreventClose)
{
Device.BeginInvokeOnMainThread(async () =>
{
await popupNavigationInstance.PopAsync();
});
}
return true;
}
backPressedHandler?.Invoke();
return false;
}
private static void LinkAssemblies()
{
if (false.Equals(true))
{
var i = new PopupPlatformDroid();
var r = new PopupPageRenderer(null);
}
}
}
}
| using System;
using System.Linq;
using Android.Content;
using Android.OS;
using Rg.Plugins.Popup.Droid.Impl;
using Rg.Plugins.Popup.Droid.Renderers;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace Rg.Plugins.Popup
{
public static class Popup
{
internal static event EventHandler OnInitialized;
internal static bool IsInitialized { get; private set; }
internal static Context Context { get; private set; }
public static void Init(Context context, Bundle bundle)
{
LinkAssemblies();
Context = context;
IsInitialized = true;
OnInitialized?.Invoke(null, EventArgs.Empty);
}
public static bool SendBackPressed(Action backPressedHandler = null)
{
var popupNavigationInstance = PopupNavigation.Instance;
if (popupNavigationInstance.PopupStack.Count > 0)
{
var lastPage = popupNavigationInstance.PopupStack.Last();
var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed();
if (!isPreventClose)
{
Device.BeginInvokeOnMainThread(async () =>
{
await popupNavigationInstance.RemovePageAsync(lastPage);
});
}
return true;
}
backPressedHandler?.Invoke();
return false;
}
private static void LinkAssemblies()
{
if (false.Equals(true))
{
var i = new PopupPlatformDroid();
var r = new PopupPageRenderer(null);
}
}
}
}
|
Set window controls to right color | using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace OfflineWorkflowSample
{
public sealed partial class CustomAppTitleBar : UserControl, INotifyPropertyChanged
{
private string _title = "ArcGIS Maps Offline";
public string Title
{
get => _title;
set
{
_title = value;
OnPropertyChanged();
}
}
private Page _containingPage;
public CustomAppTitleBar()
{
this.InitializeComponent();
Window.Current.SetTitleBar(DraggablePart);
DataContext = this;
}
public void EnableBackButton(Page containingPage)
{
_containingPage = containingPage;
BackButton.Visibility = Visibility.Visible;
}
private void BackButton_OnClick(object sender, RoutedEventArgs e)
{
if (_containingPage?.Frame != null && _containingPage.Frame.CanGoBack)
{
_containingPage.Frame.GoBack();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace OfflineWorkflowSample
{
public sealed partial class CustomAppTitleBar : UserControl, INotifyPropertyChanged
{
private string _title = "ArcGIS Maps Offline";
public string Title
{
get => _title;
set
{
_title = value;
OnPropertyChanged();
}
}
private Page _containingPage;
public CustomAppTitleBar()
{
this.InitializeComponent();
Window.Current.SetTitleBar(DraggablePart);
ApplicationView.GetForCurrentView().TitleBar.ButtonForegroundColor = Colors.Black;
DataContext = this;
}
public void EnableBackButton(Page containingPage)
{
_containingPage = containingPage;
BackButton.Visibility = Visibility.Visible;
}
private void BackButton_OnClick(object sender, RoutedEventArgs e)
{
if (_containingPage?.Frame != null && _containingPage.Frame.CanGoBack)
{
_containingPage.Frame.GoBack();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
Fix typo and remove usings | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Espera.Core
{
/// <summary>
/// This class contains the used keys for Akavache
/// </summary>
public static class BlobCacheKeys
{
/// <summary>
/// This is the key prefix for song artworks. After the hyphe, the MD5 hash of the artwork
/// is attached.
/// </summary>
public const string Artwork = "artwork-";
/// <summary>
/// This is the key for the changelog that is shown after the application is updated.
/// </summary>
public const string Changelog = "changelog";
}
} | namespace Espera.Core
{
/// <summary>
/// This class contains the used keys for Akavache
/// </summary>
public static class BlobCacheKeys
{
/// <summary>
/// This is the key prefix for song artworks. After the hyphen, the MD5 hash of the artwork
/// is attached.
/// </summary>
public const string Artwork = "artwork-";
/// <summary>
/// This is the key for the changelog that is shown after the application is updated.
/// </summary>
public const string Changelog = "changelog";
}
} |
Adjust the name of the property that the data for a response goes into | using System.Collections.Generic;
using Glimpse.Core2.Extensibility;
using Glimpse.Core2.Framework;
namespace Glimpse.Core2.SerializationConverter
{
public class GlimpseMetadataConverter:SerializationConverter<GlimpseRequest>
{
public override IDictionary<string, object> Convert(GlimpseRequest request)
{
return new Dictionary<string, object>
{
{"clientId", request.ClientId},
{"dateTime", request.DateTime},
{"duration", request.Duration},
{"parentRequestId", request.ParentRequestId},
{"requestId", request.RequestId},
{"isAjax", request.RequestIsAjax},
{"method", request.RequestHttpMethod},
{"uri", request.RequestUri},
{"contentType", request.ResponseContentType},
{"statusCode", request.ResponseStatusCode},
{"plugins", request.PluginData},
{"userAgent", request.UserAgent}
};
}
}
} | using System.Collections.Generic;
using Glimpse.Core2.Extensibility;
using Glimpse.Core2.Framework;
namespace Glimpse.Core2.SerializationConverter
{
public class GlimpseMetadataConverter:SerializationConverter<GlimpseRequest>
{
public override IDictionary<string, object> Convert(GlimpseRequest request)
{
return new Dictionary<string, object>
{
{"clientId", request.ClientId},
{"dateTime", request.DateTime},
{"duration", request.Duration},
{"parentRequestId", request.ParentRequestId},
{"requestId", request.RequestId},
{"isAjax", request.RequestIsAjax},
{"method", request.RequestHttpMethod},
{"uri", request.RequestUri},
{"contentType", request.ResponseContentType},
{"statusCode", request.ResponseStatusCode},
{"data", request.PluginData},
{"userAgent", request.UserAgent}
};
}
}
} |
Mark IsCustomer and IsSupplier fields as readonly | using System;
namespace XeroApi.Model
{
public class Contact : ModelBase
{
[ItemId]
public Guid ContactID { get; set; }
[ItemNumber]
public string ContactNumber { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public string ContactStatus { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string SkypeUserName { get; set; }
public string BankAccountDetails { get; set; }
public string TaxNumber { get; set; }
public string AccountsReceivableTaxType { get; set; }
public string AccountsPayableTaxType { get; set; }
public Addresses Addresses { get; set; }
public Phones Phones { get; set; }
public ContactGroups ContactGroups { get; set; }
public bool IsSupplier { get; set; }
public bool IsCustomer { get; set; }
public string DefaultCurrency { get; set; }
}
public class Contacts : ModelList<Contact>
{
}
} | using System;
namespace XeroApi.Model
{
public class Contact : ModelBase
{
[ItemId]
public Guid ContactID { get; set; }
[ItemNumber]
public string ContactNumber { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public string ContactStatus { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string SkypeUserName { get; set; }
public string BankAccountDetails { get; set; }
public string TaxNumber { get; set; }
public string AccountsReceivableTaxType { get; set; }
public string AccountsPayableTaxType { get; set; }
public Addresses Addresses { get; set; }
public Phones Phones { get; set; }
public ContactGroups ContactGroups { get; set; }
[ReadOnly]
public bool IsSupplier { get; set; }
[ReadOnly]
public bool IsCustomer { get; set; }
public string DefaultCurrency { get; set; }
}
public class Contacts : ModelList<Contact>
{
}
} |
Use hash set to assert should fire | using System;
using System.Collections.Generic;
using System.Linq;
namespace Codestellation.Pulsar.Cron
{
public class CronCalendar
{
private readonly List<DateTime> _days;
public CronCalendar(IEnumerable<DateTime> scheduledDays)
{
_days = scheduledDays.ToList();
_days.Sort();
}
public IEnumerable<DateTime> ScheduledDays
{
get { return _days; }
}
public IEnumerable<DateTime> DaysAfter(DateTime point)
{
var date = point.Date;
for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++)
{
var candidate = _days[dayIndex];
if (date <= candidate)
{
yield return candidate;
}
}
}
public bool ShouldFire(DateTime date)
{
return _days.Contains(date);
}
public bool TryFindNextDay(DateTime date, out DateTime closest)
{
for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++)
{
var candidate = _days[dayIndex];
if (date < candidate)
{
closest = candidate;
return true;
}
}
closest = DateTime.MinValue;
return false;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Codestellation.Pulsar.Cron
{
public class CronCalendar
{
private readonly List<DateTime> _days;
private readonly HashSet<DateTime> _dayIndex;
public CronCalendar(IEnumerable<DateTime> scheduledDays)
{
_days = scheduledDays.ToList();
_days.Sort();
_dayIndex = new HashSet<DateTime>(_days);
}
public IEnumerable<DateTime> ScheduledDays
{
get { return _days; }
}
public IEnumerable<DateTime> DaysAfter(DateTime point)
{
var date = point.Date;
for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++)
{
var candidate = _days[dayIndex];
if (date <= candidate)
{
yield return candidate;
}
}
}
public bool ShouldFire(DateTime date)
{
return _dayIndex.Contains(date);
}
public bool TryFindNextDay(DateTime date, out DateTime closest)
{
for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++)
{
var candidate = _days[dayIndex];
if (date < candidate)
{
closest = candidate;
return true;
}
}
closest = DateTime.MinValue;
return false;
}
}
} |
Fix test issue with ContactOwners test. | using NuGetGallery.FunctionTests.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NuGetGallery.FunctionalTests
{
internal static class Constants
{
#region FormFields
internal const string ConfirmPasswordFormField = "ConfirmPassword";
internal const string EmailAddressFormField = "Register.EmailAddress";
internal const string RegisterPasswordFormField = "Register.Password";
internal const string PasswordFormField = "SignIn.Password";
internal const string ConfirmPasswordField = "ConfirmPassword";
internal const string UserNameFormField = "Register.Username";
internal const string UserNameOrEmailFormField = "SignIn.UserNameOrEmail";
internal const string AcceptTermsField = "AcceptTerms";
#endregion FormFields
#region PredefinedText
internal const string HomePageText = "What is NuGet?";
internal const string RegisterNewUserPendingConfirmationText = "Your account is now registered!";
internal const string UserAlreadyExistsText = "User already exists";
internal const string ReadOnlyModeRegisterNewUserText = "503 : Please try again later! (Read-only)";
internal const string SearchTerm = "elmah";
internal const string CreateNewAccountText = "Create A New Account";
internal const string StatsPageDefaultText = "Download statistics displayed on this page reflect the actual package downloads from the NuGet.org site";
internal const string ContactOwnersText = "Your message has been sent to the owners of ";
internal const string UnListedPackageText = "This package is unlisted and hidden from package listings";
internal const string TestPackageId = "BaseTestPackage";
#endregion PredefinedText
}
}
| using NuGetGallery.FunctionTests.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NuGetGallery.FunctionalTests
{
internal static class Constants
{
#region FormFields
internal const string ConfirmPasswordFormField = "ConfirmPassword";
internal const string EmailAddressFormField = "Register.EmailAddress";
internal const string RegisterPasswordFormField = "Register.Password";
internal const string PasswordFormField = "SignIn.Password";
internal const string ConfirmPasswordField = "ConfirmPassword";
internal const string UserNameFormField = "Register.Username";
internal const string UserNameOrEmailFormField = "SignIn.UserNameOrEmail";
internal const string AcceptTermsField = "AcceptTerms";
#endregion FormFields
#region PredefinedText
internal const string HomePageText = "What is NuGet?";
internal const string RegisterNewUserPendingConfirmationText = "Your account is now registered!";
internal const string UserAlreadyExistsText = "User already exists";
internal const string ReadOnlyModeRegisterNewUserText = "503 : Please try again later! (Read-only)";
internal const string SearchTerm = "elmah";
internal const string CreateNewAccountText = "Create A New Account";
internal const string StatsPageDefaultText = "Download statistics displayed on this page reflect the actual package downloads from the NuGet.org site";
internal const string ContactOwnersText = "Your message has been sent to the owners of";
internal const string UnListedPackageText = "This package is unlisted and hidden from package listings";
internal const string TestPackageId = "BaseTestPackage";
#endregion PredefinedText
}
}
|
Move helper to workspace layer | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's reference that can be used for display and navigation in an
/// editor. These generally reference items outside of the Roslyn <see cref="Solution"/> model
/// provided by external sources (for example: RichNav).
/// </summary>
internal abstract class ExternalReferenceItem
{
/// <summary>
/// The definition this reference corresponds to.
/// </summary>
public DefinitionItem Definition { get; }
public ExternalReferenceItem(
DefinitionItem definition,
string documentName,
object text,
string displayPath)
{
Definition = definition;
DocumentName = documentName;
Text = text;
DisplayPath = displayPath;
}
public string ProjectName { get; }
/// <remarks>
/// Must be of type Microsoft.VisualStudio.Text.Adornments.ImageElement or
/// Microsoft.VisualStudio.Text.Adornments.ContainerElement or
/// Microsoft.VisualStudio.Text.Adornments.ClassifiedTextElement or System.String
/// </remarks>
public object Text { get; }
public string DisplayPath { get; }
public abstract bool TryNavigateTo(Workspace workspace, bool isPreview);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's reference that can be used for display and navigation in an
/// editor. These generally reference items outside of the Roslyn <see cref="Solution"/> model
/// provided by external sources (for example: RichNav).
/// </summary>
internal abstract class ExternalReferenceItem
{
/// <summary>
/// The definition this reference corresponds to.
/// </summary>
public DefinitionItem Definition { get; }
public ExternalReferenceItem(
DefinitionItem definition,
string projectName,
object text,
string displayPath)
{
Definition = definition;
ProjectName = projectName;
Text = text;
DisplayPath = displayPath;
}
public string ProjectName { get; }
/// <remarks>
/// Must be of type Microsoft.VisualStudio.Text.Adornments.ImageElement or
/// Microsoft.VisualStudio.Text.Adornments.ContainerElement or
/// Microsoft.VisualStudio.Text.Adornments.ClassifiedTextElement or System.String
/// </remarks>
public object Text { get; }
public string DisplayPath { get; }
public abstract bool TryNavigateTo(Workspace workspace, bool isPreview);
}
}
|
Introduce helper methods to make test clearer | using System;
using CanoePoloLeagueOrganiser;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CanoePoloLeagueOrganiserTests
{
public class RubyInspiredListFunctionsTests
{
[Fact]
public void EachCons2()
{
var list = new List<int> { 1, 2, 3, 4 };
var actual = list.EachCons2();
Assert.Collection(actual,
(pair) => { Assert.Equal(1, pair.Item1); Assert.Equal(2, pair.Item2); },
(pair) => { Assert.Equal(2, pair.Item1); Assert.Equal(3, pair.Item2); },
(pair) => { Assert.Equal(3, pair.Item1); Assert.Equal(4, pair.Item2); }
);
}
[Fact]
public void EachCons3()
{
var list = new List<int> { 1, 2, 3, 4, 5 };
var actual = list.EachCons(3);
Assert.Collection(actual,
(triple) => Assert.Equal("1,2,3", string.Join(",", triple)),
(triple) => Assert.Equal("2,3,4", string.Join(",", triple)),
(triple) => Assert.Equal("3,4,5", string.Join(",", triple))
);
}
}
}
| using System;
using CanoePoloLeagueOrganiser;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CanoePoloLeagueOrganiserTests
{
public class RubyInspiredListFunctionsTests
{
[Fact]
public void EachCons2()
{
var list = new List<int> { 1, 2, 3, 4 };
var actual = list.EachCons2();
Assert.Collection(actual,
AssertPair(1, 2),
AssertPair(2, 3),
AssertPair(3, 4));
}
[Fact]
public void EachCons3()
{
var list = new List<int> { 1, 2, 3, 4, 5 };
var actual = list.EachCons(3);
Assert.Collection(actual,
AssertTriple("1,2,3"),
AssertTriple("2,3,4"),
AssertTriple("3,4,5"));
}
static Action<IEnumerable<int>> AssertTriple(string csvTriple) =>
(triple) => Assert.Equal(csvTriple, string.Join(",", triple));
static Action<Tuple<int, int>> AssertPair(int firstValue, int secondValue)
{
return (pair) =>
{
Assert.Equal(firstValue, pair.Item1);
Assert.Equal(secondValue, pair.Item2);
};
}
}
}
|
Remove high performance GC setting | // 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.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Performance
{
public class HighPerformanceSession : Component
{
private readonly IBindable<bool> localUserPlaying = new Bindable<bool>();
private GCLatencyMode originalGCMode;
[BackgroundDependencyLoader]
private void load(OsuGame game)
{
localUserPlaying.BindTo(game.LocalUserPlaying);
}
protected override void LoadComplete()
{
base.LoadComplete();
localUserPlaying.BindValueChanged(playing =>
{
if (playing.NewValue)
EnableHighPerformanceSession();
else
DisableHighPerformanceSession();
}, true);
}
protected virtual void EnableHighPerformanceSession()
{
originalGCMode = GCSettings.LatencyMode;
GCSettings.LatencyMode = GCLatencyMode.LowLatency;
}
protected virtual void DisableHighPerformanceSession()
{
if (GCSettings.LatencyMode == GCLatencyMode.LowLatency)
GCSettings.LatencyMode = originalGCMode;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Performance
{
public class HighPerformanceSession : Component
{
private readonly IBindable<bool> localUserPlaying = new Bindable<bool>();
[BackgroundDependencyLoader]
private void load(OsuGame game)
{
localUserPlaying.BindTo(game.LocalUserPlaying);
}
protected override void LoadComplete()
{
base.LoadComplete();
localUserPlaying.BindValueChanged(playing =>
{
if (playing.NewValue)
EnableHighPerformanceSession();
else
DisableHighPerformanceSession();
}, true);
}
protected virtual void EnableHighPerformanceSession()
{
}
protected virtual void DisableHighPerformanceSession()
{
}
}
}
|
Revert "added BsPager HtmlHelper with settings" | using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using BForms.Grid;
using BForms.Models;
namespace BForms.Html
{
public static class BsPagerExtensions
{
public static BsGridPagerBuilder BsPager(this HtmlHelper html, BsPagerModel model, BsPagerSettings pagerSettings)
{
var builder = new BsGridPagerBuilder(model, pagerSettings, null) { viewContext = html.ViewContext };
return builder;
}
public static BsGridPagerBuilder BsPager(this HtmlHelper html, BsPagerModel model)
{
var builder = BsPager(html, model, null);
return builder;
}
public static BsGridPagerBuilder BsPagerFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, BsPagerModel>> expression)
{
var model = expression.Compile().Invoke(html.ViewData.Model);
return BsPager(html, model);
}
}
}
| using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using BForms.Grid;
using BForms.Models;
namespace BForms.Html
{
public static class BsPagerExtensions
{
public static BsGridPagerBuilder BsPager(this HtmlHelper html, BsPagerModel model)
{
var builder = new BsGridPagerBuilder(model, new BsPagerSettings(), null) { viewContext = html.ViewContext };
return builder;
}
public static BsGridPagerBuilder BsPagerFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, BsPagerModel>> expression)
{
var model = expression.Compile().Invoke(html.ViewData.Model);
return BsPager(html, model);
}
}
}
|
Update to avoid now internal API | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main (string[] args)
{
string addr;
if (args.Length == 0)
addr = Address.Session;
else {
if (args[0] == "--session")
addr = Address.Session;
else if (args[0] == "--system")
addr = Address.System;
else
addr = args[0];
}
Connection conn = Connection.Open (addr);
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
IBus bus = conn.GetObject<IBus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
string myName = bus.Hello ();
Console.WriteLine ("myName: " + myName);
Console.WriteLine ();
string xmlData = bus.Introspect ();
Console.WriteLine ("xmlData: " + xmlData);
Console.WriteLine ();
foreach (string n in bus.ListNames ())
Console.WriteLine (n);
Console.WriteLine ();
foreach (string n in bus.ListNames ())
Console.WriteLine ("Name " + n + " has owner: " + bus.NameHasOwner (n));
Console.WriteLine ();
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main (string[] args)
{
Connection conn;
if (args.Length == 0)
conn = Bus.Session;
else {
if (args[0] == "--session")
conn = Bus.Session;
else if (args[0] == "--system")
conn = Bus.System;
else
conn = Connection.Open (args[0]);
}
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
IBus bus = conn.GetObject<IBus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
Console.WriteLine ();
string xmlData = bus.Introspect ();
Console.WriteLine ("xmlData: " + xmlData);
Console.WriteLine ();
foreach (string n in bus.ListNames ())
Console.WriteLine (n);
Console.WriteLine ();
foreach (string n in bus.ListNames ())
Console.WriteLine ("Name " + n + " has owner: " + bus.NameHasOwner (n));
Console.WriteLine ();
}
}
|
Add utility to determine if the active tab is provisional | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class Shell_InProc : InProcComponent
{
public static Shell_InProc Create() => new Shell_InProc();
public string GetActiveWindowCaption()
=> InvokeOnUIThread(() => GetDTE().ActiveWindow.Caption);
public int GetHWnd()
=> GetDTE().MainWindow.HWnd;
public bool IsActiveTabProvisional()
=> InvokeOnUIThread(() =>
{
var shellMonitorSelection = GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>();
if (!ErrorHandler.Succeeded(shellMonitorSelection.GetCurrentElementValue((uint) VSConstants.VSSELELEMID.SEID_DocumentFrame, out var windowFrameObject)))
{
throw new InvalidOperationException("Tried to get the active document frame but no documents were open.");
}
var windowFrame = (IVsWindowFrame)windowFrameObject;
if (!ErrorHandler.Succeeded(windowFrame.GetProperty((int) VsFramePropID.IsProvisional, out var isProvisionalObject)))
{
throw new InvalidOperationException("The active window frame did not have an 'IsProvisional' property.");
}
return (bool) isProvisionalObject;
});
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class Shell_InProc : InProcComponent
{
public static Shell_InProc Create() => new Shell_InProc();
public string GetActiveWindowCaption()
=> InvokeOnUIThread(() => GetDTE().ActiveWindow.Caption);
public int GetHWnd()
=> GetDTE().MainWindow.HWnd;
public bool IsActiveTabProvisional()
=> InvokeOnUIThread(() =>
{
var shellMonitorSelection = GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>();
if (!ErrorHandler.Succeeded(shellMonitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var windowFrameObject)))
{
throw new InvalidOperationException("Tried to get the active document frame but no documents were open.");
}
var windowFrame = (IVsWindowFrame)windowFrameObject;
if (!ErrorHandler.Succeeded(windowFrame.GetProperty((int)VsFramePropID.IsProvisional, out var isProvisionalObject)))
{
throw new InvalidOperationException("The active window frame did not have an 'IsProvisional' property.");
}
return (bool)isProvisionalObject;
});
}
}
|
Use Debugger.IsAttached instead of IsDevelopment to control developer mode | namespace Microsoft.AspNetCore.Hosting
{
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
internal class DefaultApplicationInsightsServiceConfigureOptions : IConfigureOptions<ApplicationInsightsServiceOptions>
{
private readonly IHostingEnvironment hostingEnvironment;
public DefaultApplicationInsightsServiceConfigureOptions(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
public void Configure(ApplicationInsightsServiceOptions options)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(this.hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true)
.AddEnvironmentVariables();
ApplicationInsightsExtensions.AddTelemetryConfiguration(configBuilder.Build(), options);
if (this.hostingEnvironment.IsDevelopment())
{
options.DeveloperMode = true;
}
}
}
} | namespace Microsoft.AspNetCore.Hosting
{
using System.Diagnostics;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
internal class DefaultApplicationInsightsServiceConfigureOptions : IConfigureOptions<ApplicationInsightsServiceOptions>
{
private readonly IHostingEnvironment hostingEnvironment;
public DefaultApplicationInsightsServiceConfigureOptions(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
public void Configure(ApplicationInsightsServiceOptions options)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(this.hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true)
.AddEnvironmentVariables();
ApplicationInsightsExtensions.AddTelemetryConfiguration(configBuilder.Build(), options);
if (Debugger.IsAttached)
{
options.DeveloperMode = true;
}
}
}
} |
Enhance version number to `v1.1.1' after inclusion of Fabio's patch. | using System;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.terranova
{
public class VersioningInfo
{
/// <summary>
/// Gets the version number.
///
/// Here are the stack of versions with a brief description:
///
/// v1.1.0: introduce pressure regulator gadget for edges.
///
/// v1.0.1: enhancement to tackle turbolent behavior due to
/// Reynolds number.
///
/// v1.0.0: basic version with checker about negative pressures
/// associated to nodes with load gadget.
///
/// </summary>
/// <value>The version number.</value>
public String VersionNumber {
get {
return "v1.1.0";
}
}
public String EngineIdentifier {
get {
return "Network Reasoner, stlab.dsi.unifi.it";
}
}
}
}
| using System;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.terranova
{
public class VersioningInfo
{
/// <summary>
/// Gets the version number.
///
/// Here are the stack of versions with a brief description:
///
/// v1.1.1: tuning computational parameter to handle middle and low pressure networks.
///
/// v1.1.0: introduce pressure regulator gadget for edges.
///
/// v1.0.1: enhancement to tackle turbolent behavior due to
/// Reynolds number.
///
/// v1.0.0: basic version with checker about negative pressures
/// associated to nodes with load gadget.
///
/// </summary>
/// <value>The version number.</value>
public String VersionNumber {
get {
return "v1.1.1";
}
}
public String EngineIdentifier {
get {
return "Network Reasoner, stlab.dsi.unifi.it";
}
}
}
}
|
Apply stlye classes to the rejectec status tag | @model SFA.DAS.EmployerAccounts.Web.ViewModels.VacancyViewModel
<section class="dashboard-section">
<h2 class="section-heading heading-large">
Your apprenticeship advert
</h2>
<p>You have created a vacancy for your apprenticeship.</p>
<table class="responsive">
<tr>
<th scope="row" class="tw-35">
Title
</th>
<td class="tw-65">
@(Model?.Title)
</td>
</tr>
<tr>
<th scope="row">
Status
</th>
<td>
<span>REJECTED</span>
</td>
</tr>
</table>
<p>
<a href="@Model.ManageVacancyUrl" role="button" draggable="false" class="button">
Review your vacancy
</a>
</p>
</section> | @model SFA.DAS.EmployerAccounts.Web.ViewModels.VacancyViewModel
<section class="dashboard-section">
<h2 class="section-heading heading-large">
Your apprenticeship advert
</h2>
<p>You have created a vacancy for your apprenticeship.</p>
<table class="responsive">
<tr>
<th scope="row" class="tw-35">
Title
</th>
<td class="tw-65">
@(Model?.Title)
</td>
</tr>
<tr>
<th scope="row">
Status
</th>
<td>
<strong class="govuk-tag govuk-tag--error">REJECTED</strong>
</td>
</tr>
</table>
<p>
<a href="@Model.ManageVacancyUrl" role="button" draggable="false" class="button">
Review your vacancy
</a>
</p>
</section> |
Adjust health increase for drum roll tick to match new max result | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoDrumRollTickJudgement : TaikoJudgement
{
public override HitResult MaxResult => HitResult.SmallTickHit;
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
case HitResult.Great:
return 0.15;
default:
return 0;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoDrumRollTickJudgement : TaikoJudgement
{
public override HitResult MaxResult => HitResult.SmallTickHit;
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
case HitResult.SmallTickHit:
return 0.15;
default:
return 0;
}
}
}
}
|
Add start log to commands | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using GeoChallenger.Commands.Commands;
using GeoChallenger.Commands.Config;
using NLog;
namespace GeoChallenger.Commands
{
class Program
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
// NOTE: Only one command is supported at this moement.
static void Main(string[] args)
{
try {
var mapperConfiguration = MapperConfig.CreateMapperConfiguration();
var container = DIConfig.RegisterDI(mapperConfiguration);
// All components have single instance scope.
using (var scope = container.BeginLifetimeScope()) {
var command = scope.Resolve<ReindexCommand>();
command.RunAsync().Wait();
}
} catch (Exception ex) {
_log.Error(ex, "Command is failed.");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using GeoChallenger.Commands.Commands;
using GeoChallenger.Commands.Config;
using NLog;
using NLog.Fluent;
namespace GeoChallenger.Commands
{
class Program
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
// NOTE: Only one command is supported at this moement.
static void Main(string[] args)
{
_log.Info("Start GeoChallenger.Commands");
try {
var mapperConfiguration = MapperConfig.CreateMapperConfiguration();
var container = DIConfig.RegisterDI(mapperConfiguration);
// All components have single instance scope.
using (var scope = container.BeginLifetimeScope()) {
var command = scope.Resolve<ReindexCommand>();
command.RunAsync().Wait();
}
} catch (Exception ex) {
_log.Error(ex, "Command is failed.");
}
_log.Info("End GeoChallenger.Commands");
}
}
}
|
Add `current_period_*` filters when listing Invoices | namespace Stripe
{
using Newtonsoft.Json;
public class SubscriptionListOptions : ListOptionsWithCreated
{
/// <summary>
/// The billing mode of the subscriptions to retrieve. One of <see cref="Billing" />.
/// </summary>
[JsonProperty("billing")]
public Billing? Billing { get; set; }
/// <summary>
/// The ID of the customer whose subscriptions will be retrieved.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// The ID of the plan whose subscriptions will be retrieved.
/// </summary>
[JsonProperty("plan")]
public string PlanId { get; set; }
/// <summary>
/// The status of the subscriptions to retrieve. One of <see cref="SubscriptionStatuses"/> or <c>all</c>. Passing in a value of <c>canceled</c> will return all canceled subscriptions, including those belonging to deleted customers. Passing in a value of <c>all</c> will return subscriptions of all statuses.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
public class SubscriptionListOptions : ListOptionsWithCreated
{
/// <summary>
/// The billing mode of the subscriptions to retrieve. One of <see cref="Billing" />.
/// </summary>
[JsonProperty("billing")]
public Billing? Billing { get; set; }
/// <summary>
/// A filter on the list based on the object current_period_end field.
/// </summary>
[JsonProperty("current_period_end")]
public DateTime? CurrentPeriodEnd { get; set; }
/// <summary>
/// A filter on the list based on the object current_period_end field.
/// </summary>
[JsonProperty("current_period_end")]
public DateRangeOptions CurrentPeriodEndRange { get; set; }
/// <summary>
/// A filter on the list based on the object current_period_start field.
/// </summary>
[JsonProperty("current_period_start")]
public DateTime? CurrentPeriodStart { get; set; }
/// <summary>
/// A filter on the list based on the object current_period_start field.
/// </summary>
[JsonProperty("current_period_start")]
public DateRangeOptions CurrentPeriodStartRange { get; set; }
/// <summary>
/// The ID of the customer whose subscriptions will be retrieved.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// The ID of the plan whose subscriptions will be retrieved.
/// </summary>
[JsonProperty("plan")]
public string PlanId { get; set; }
/// <summary>
/// The status of the subscriptions to retrieve. One of <see cref="SubscriptionStatuses"/> or <c>all</c>. Passing in a value of <c>canceled</c> will return all canceled subscriptions, including those belonging to deleted customers. Passing in a value of <c>all</c> will return subscriptions of all statuses.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
|
Remove whitespace (leave the newline). | using System.Collections.Generic;
using System.Linq;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Abp.Authorization;
namespace AbpCompanyName.AbpProjectName.Web.Host.Startup
{
public class SecurityRequirementsOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var actionAttrs = context.ApiDescription.ActionAttributes();
if (actionAttrs.OfType<AbpAllowAnonymousAttribute>().Any())
{
return;
}
var controllerAttrs = context.ApiDescription.ControllerAttributes();
var actionAbpAuthorizeAttrs = actionAttrs.OfType<AbpAuthorizeAttribute>();
if (!actionAbpAuthorizeAttrs.Any() && controllerAttrs.OfType<AbpAllowAnonymousAttribute>().Any())
{
return;
}
var controllerAbpAuthorizeAttrs = controllerAttrs.OfType<AbpAuthorizeAttribute>();
if (controllerAbpAuthorizeAttrs.Any() || actionAbpAuthorizeAttrs.Any())
{
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
var permissions = controllerAbpAuthorizeAttrs.Union(actionAbpAuthorizeAttrs)
.SelectMany(p => p.Permissions)
.Distinct();
if (permissions.Any())
{
operation.Responses.Add("403", new Response { Description = "Forbidden" });
}
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>>
{
{ "bearerAuth", permissions }
}
};
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Abp.Authorization;
namespace AbpCompanyName.AbpProjectName.Web.Host.Startup
{
public class SecurityRequirementsOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var actionAttrs = context.ApiDescription.ActionAttributes();
if (actionAttrs.OfType<AbpAllowAnonymousAttribute>().Any())
{
return;
}
var controllerAttrs = context.ApiDescription.ControllerAttributes();
var actionAbpAuthorizeAttrs = actionAttrs.OfType<AbpAuthorizeAttribute>();
if (!actionAbpAuthorizeAttrs.Any() && controllerAttrs.OfType<AbpAllowAnonymousAttribute>().Any())
{
return;
}
var controllerAbpAuthorizeAttrs = controllerAttrs.OfType<AbpAuthorizeAttribute>();
if (controllerAbpAuthorizeAttrs.Any() || actionAbpAuthorizeAttrs.Any())
{
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
var permissions = controllerAbpAuthorizeAttrs.Union(actionAbpAuthorizeAttrs)
.SelectMany(p => p.Permissions)
.Distinct();
if (permissions.Any())
{
operation.Responses.Add("403", new Response { Description = "Forbidden" });
}
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>>
{
{ "bearerAuth", permissions }
}
};
}
}
}
}
|
Fix manual KMS snippet (LocationName breaking change is expected) | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using System;
using Xunit;
namespace Google.Cloud.Kms.V1.Snippets
{
[Collection(nameof(KeyManagementServiceFixture))]
[SnippetOutputCollector]
public class KeyManagementServiceClientSnippets
{
private readonly KeyManagementServiceFixture _fixture;
public KeyManagementServiceClientSnippets(KeyManagementServiceFixture fixture) =>
_fixture = fixture;
[Fact]
public void ListGlobalKeyRings()
{
string projectId = _fixture.ProjectId;
// Sample: ListGlobalKeyRings
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
LocationName globalLocation = new LocationName(projectId, "global");
foreach (KeyRing keyRing in client.ListKeyRings(globalLocation))
{
Console.WriteLine(keyRing.Name);
}
// End sample
}
}
}
| // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax.ResourceNames;
using Google.Cloud.ClientTesting;
using System;
using Xunit;
namespace Google.Cloud.Kms.V1.Snippets
{
[Collection(nameof(KeyManagementServiceFixture))]
[SnippetOutputCollector]
public class KeyManagementServiceClientSnippets
{
private readonly KeyManagementServiceFixture _fixture;
public KeyManagementServiceClientSnippets(KeyManagementServiceFixture fixture) =>
_fixture = fixture;
[Fact]
public void ListGlobalKeyRings()
{
string projectId = _fixture.ProjectId;
// Sample: ListGlobalKeyRings
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
LocationName globalLocation = new LocationName(projectId, "global");
foreach (KeyRing keyRing in client.ListKeyRings(globalLocation))
{
Console.WriteLine(keyRing.Name);
}
// End sample
}
}
}
|
Package updates is now fully implemented | using System.Collections.Generic;
namespace Glimpse.Core.Framework
{
public class GlimpseMetadata
{
public GlimpseMetadata()
{
Plugins = new Dictionary<string, PluginMetadata>();
Resources = new Dictionary<string, string>//TODO: once the resources below are implemented, this constructor should just instantiate variable.
{
{"glimpse_packageUpdates", "//getGlimpse.com/{?packages*}"},
{"paging", "NEED TO IMPLMENT RESOURCE Pager"},//TODO: Implement resource
{"tab", "NEED TO IMPLMENT RESOURCE test-popup.html"},//TODO: Implement resource
};
}
public string Version { get; set; }
public IDictionary<string,PluginMetadata> Plugins { get; set; }
public IDictionary<string,string> Resources { get; set; }
}
public class PluginMetadata
{
public string DocumentationUri { get; set; }
public bool HasMetadata { get { return !string.IsNullOrEmpty(DocumentationUri); } }
}
} | using System.Collections.Generic;
namespace Glimpse.Core.Framework
{
public class GlimpseMetadata
{
public GlimpseMetadata()
{
Plugins = new Dictionary<string, PluginMetadata>();
Resources = new Dictionary<string, string>//TODO: once the resources below are implemented, this constructor should just instantiate variable.
{
{"paging", "NEED TO IMPLMENT RESOURCE Pager"},//TODO: Implement resource
{"tab", "NEED TO IMPLMENT RESOURCE test-popup.html"},//TODO: Implement resource
};
}
public string Version { get; set; }
public IDictionary<string,PluginMetadata> Plugins { get; set; }
public IDictionary<string,string> Resources { get; set; }
}
public class PluginMetadata
{
public string DocumentationUri { get; set; }
public bool HasMetadata { get { return !string.IsNullOrEmpty(DocumentationUri); } }
}
} |
Undo change of this file. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor
{
internal static class ContentTypeNames
{
public const string CSharpContentType = "CSharp";
public const string CSharpSignatureHelpContentType = "CSharp Signature Help";
public const string RoslynContentType = "Roslyn Languages";
public const string VisualBasicContentType = "Basic";
public const string VisualBasicSignatureHelpContentType = "Basic Signature Help";
public const string XamlContentType = "XAML";
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor
{
internal static class ContentTypeNames
{
public const string CSharpContentType = "CSharp";
public const string CSharpSignatureHelpContentType = "CSharp Signature Help";
public const string RoslynContentType = "Roslyn Languages";
public const string VisualBasicContentType = "Basic";
public const string VisualBasicSignatureHelpContentType = "Basic Signature Help";
public const string XamlContentType = "XAML";
public const string JavaScriptContentTypeName = "JavaScript";
public const string TypeScriptContentTypeName = "TypeScript";
}
}
|
Set default for bindable in object initializer | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
internal class VisibilitySection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
private readonly IssueType[] configurableIssueTypes =
{
IssueType.Warning,
IssueType.Error,
IssueType.Negligible
};
private BindableList<IssueType> hiddenIssueTypes;
protected override string Header => "Visibility";
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy();
foreach (IssueType issueType in configurableIssueTypes)
{
var checkbox = new SettingsCheckbox
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
LabelText = issueType.ToString()
};
checkbox.Current.Default = !hiddenIssueTypes.Contains(issueType);
checkbox.Current.SetDefault();
checkbox.Current.BindValueChanged(state =>
{
if (!state.NewValue)
hiddenIssueTypes.Add(issueType);
else
hiddenIssueTypes.Remove(issueType);
});
Flow.Add(checkbox);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
internal class VisibilitySection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
private readonly IssueType[] configurableIssueTypes =
{
IssueType.Warning,
IssueType.Error,
IssueType.Negligible
};
private BindableList<IssueType> hiddenIssueTypes;
protected override string Header => "Visibility";
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy();
foreach (IssueType issueType in configurableIssueTypes)
{
var checkbox = new SettingsCheckbox
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
LabelText = issueType.ToString(),
Current = { Default = !hiddenIssueTypes.Contains(issueType) }
};
checkbox.Current.SetDefault();
checkbox.Current.BindValueChanged(state =>
{
if (!state.NewValue)
hiddenIssueTypes.Add(issueType);
else
hiddenIssueTypes.Remove(issueType);
});
Flow.Add(checkbox);
}
}
}
}
|
Fix crash in UWP design mode | using System;
using System.ComponentModel;
using Windows.ApplicationModel;
#if WINDOWS_UWP
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
public abstract class WindowsBasePage : Windows.UI.Xaml.Controls.Page
{
public WindowsBasePage()
{
Windows.UI.Xaml.Application.Current.Suspending += OnApplicationSuspending;
Windows.UI.Xaml.Application.Current.Resuming += OnApplicationResuming;
}
protected Platform Platform { get; private set; }
protected abstract Platform CreatePlatform();
protected void LoadApplication(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
Application.Current = application;
Platform = CreatePlatform();
Platform.SetPage(Application.Current.MainPage);
application.PropertyChanged += OnApplicationPropertyChanged;
Application.Current.SendStart();
}
void OnApplicationPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MainPage")
Platform.SetPage(Application.Current.MainPage);
}
void OnApplicationResuming(object sender, object e)
{
Application.Current.SendResume();
}
async void OnApplicationSuspending(object sender, SuspendingEventArgs e)
{
SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
await Application.Current.SendSleepAsync();
deferral.Complete();
}
}
} | using System;
using System.ComponentModel;
using Windows.ApplicationModel;
#if WINDOWS_UWP
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
public abstract class WindowsBasePage : Windows.UI.Xaml.Controls.Page
{
public WindowsBasePage()
{
if (!DesignMode.DesignModeEnabled)
{
Windows.UI.Xaml.Application.Current.Suspending += OnApplicationSuspending;
Windows.UI.Xaml.Application.Current.Resuming += OnApplicationResuming;
}
}
protected Platform Platform { get; private set; }
protected abstract Platform CreatePlatform();
protected void LoadApplication(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
Application.Current = application;
Platform = CreatePlatform();
Platform.SetPage(Application.Current.MainPage);
application.PropertyChanged += OnApplicationPropertyChanged;
Application.Current.SendStart();
}
void OnApplicationPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MainPage")
Platform.SetPage(Application.Current.MainPage);
}
void OnApplicationResuming(object sender, object e)
{
Application.Current.SendResume();
}
async void OnApplicationSuspending(object sender, SuspendingEventArgs e)
{
SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
await Application.Current.SendSleepAsync();
deferral.Complete();
}
}
} |
Allow parameters for get authorization uri | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chq.OAuth.Credentials;
namespace Chq.OAuth
{
public sealed class Client
{
private OAuthContext _context;
public OAuthContext Context
{
get { return _context; }
}
public TokenContainer RequestToken { get; set; }
public TokenContainer AccessToken { get; set; }
public Client(OAuthContext context)
{
_context = context;
}
public OAuthRequest MakeRequest(string method)
{
return new OAuthRequest(method, Context);
}
public Uri GetAuthorizationUri()
{
return new Uri(Context.AuthorizationUri.ToString() + "?oauth_token=" + RequestToken.Token);
}
public void Reset()
{
RequestToken = null;
AccessToken = null;
}
public OAuthState State()
{
if (RequestToken == null) return OAuthState.RequestRequired;
else if (AccessToken == null) return OAuthState.TokenRequired;
else return OAuthState.Ready;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chq.OAuth.Credentials;
using System.Reflection;
namespace Chq.OAuth
{
public sealed class Client
{
private OAuthContext _context;
public OAuthContext Context
{
get { return _context; }
}
public TokenContainer RequestToken { get; set; }
public TokenContainer AccessToken { get; set; }
public Client(OAuthContext context)
{
_context = context;
}
public OAuthRequest MakeRequest(string method)
{
return new OAuthRequest(method, Context);
}
public Uri GetAuthorizationUri()
{
return GetAuthorizationUri(null);
}
public Uri GetAuthorizationUri(object parameters)
{
string queryString = String.Empty;
if (parameters != null)
{
Dictionary<string, string> queryParameters = new Dictionary<string, string>();
#if WINMD
foreach (var parameter in parameters.GetType().GetTypeInfo().DeclaredProperties)
{
if (queryParameters.ContainsKey(parameter.Name)) queryParameters.Remove(parameter.Name);
queryParameters.Add(parameter.Name, parameter.GetValue(parameters).ToString());
}
#else
foreach (var parameter in parameters.GetType().GetProperties())
{
if (queryParameters.ContainsKey(parameter.Name)) queryParameters.Remove(parameter.Name);
queryParameters.Add(parameter.Name, parameter.GetValue(parameters, null).ToString());
}
#endif
foreach (var parameter in queryParameters)
{
queryString = String.Format("{0}&{1}={2}", queryString, parameter.Key, Uri.EscapeDataString(parameter.Value));
}
}
return new Uri(Context.AuthorizationUri.ToString() + "?oauth_token=" + RequestToken.Token + queryString);
}
public void Reset()
{
RequestToken = null;
AccessToken = null;
}
public OAuthState State()
{
if (RequestToken == null) return OAuthState.RequestRequired;
else if (AccessToken == null) return OAuthState.TokenRequired;
else return OAuthState.Ready;
}
}
}
|
Add the most basic score calculation for catch | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit>
{
public CatchScoreProcessor()
{
}
public CatchScoreProcessor(RulesetContainer<CatchBaseHit> rulesetContainer)
: base(rulesetContainer)
{
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit>
{
public CatchScoreProcessor(RulesetContainer<CatchBaseHit> rulesetContainer)
: base(rulesetContainer)
{
}
protected override void SimulateAutoplay(Beatmap<CatchBaseHit> beatmap)
{
foreach (var obj in beatmap.HitObjects)
{
var fruit = obj as Fruit;
if (fruit != null)
AddJudgement(new CatchJudgement { Result = HitResult.Perfect });
}
base.SimulateAutoplay(beatmap);
}
}
}
|
Fix broken ASP.NET Core integration. | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using MQTTnet.Adapter;
using MQTTnet.Diagnostics;
using MQTTnet.Server;
namespace MQTTnet.AspNetCore
{
public class MqttHostedServer : MqttServer, IHostedService
{
private readonly MqttServerOptions _options;
public MqttHostedServer(MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(adapters, logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public Task StartAsync(CancellationToken cancellationToken)
{
return StartAsync(_options);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return StopAsync();
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using MQTTnet.Adapter;
using MQTTnet.Diagnostics;
using MQTTnet.Server;
namespace MQTTnet.AspNetCore
{
public class MqttHostedServer : MqttServer, IHostedService
{
private readonly IMqttServerOptions _options;
public MqttHostedServer(IMqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(adapters, logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public Task StartAsync(CancellationToken cancellationToken)
{
return StartAsync(_options);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return StopAsync();
}
}
}
|
Divide Functions of mixing and setting instructions | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace War
{
class VesselSetter
{
private List<Vessel> _Vessels;
private int _ProcessorsNumber;
public VesselSetter(List<Instruction> instructions)
{
_ProcessorsNumber = Environment.ProcessorCount;
_Vessels = new List<Vessel>();
createVessels();
setAndMixVesselsInstructions(instructions);
}
private void createVessels()
{
int processorCounter= _ProcessorsNumber;
for (; processorCounter > 0; processorCounter--)
{
Vessel vessel = new Vessel();
_Vessels.Add(vessel);
}
}
private void setAndMixVesselsInstructions(List<Instruction> instructions)
{
try
{
Parallel.ForEach(_Vessels, currentVessel =>
{
foreach (Instruction instruction in instructions)
{
if (instruction.Id == currentVessel.Id || instruction.Id % 10 == currentVessel.Id % 10)
{
currentVessel.addInstruction(instruction);
}
}
currentVessel.mixInstructions();
}
);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public List<Vessel> vessels
{
get{
return _Vessels;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace War
{
class VesselSetter
{
private List<Vessel> _Vessels;
private int _ProcessorsNumber;
public VesselSetter(List<Instruction> instructions)
{
_ProcessorsNumber = Environment.ProcessorCount;
_Vessels = new List<Vessel>();
createVessels();
setVesselsInstructions(instructions);
mixInstructions();
}
private void createVessels()
{
int processorCounter= _ProcessorsNumber;
for (; processorCounter > 0; processorCounter--)
{
Vessel vessel = new Vessel();
_Vessels.Add(vessel);
}
}
private void setVesselsInstructions(List<Instruction> instructions)
{
try
{
Parallel.ForEach(_Vessels, currentVessel =>
{
foreach (Instruction instruction in instructions)
{
if (instruction.Id == currentVessel.Id || instruction.Id % 10 == currentVessel.Id % 10)
{
currentVessel.addInstruction(instruction);
}
}
}
);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void mixInstructions()
{
try
{
Parallel.ForEach(_Vessels, currentVessel =>
{
currentVessel.mixInstructions();
}
);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public List<Vessel> vessels
{
get{
return _Vessels;
}
}
}
}
|
Fix index out of range error | using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace portalbot.Commands
{
public class AskModule : ModuleBase
{
private List<string> _answers = new List<string>
{
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes, definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
private readonly Random _random;
public AskModule(Random random)
{
_random = random;
}
[Command("ask"), Summary("Ask a question.")]
public async Task Ask([Remainder, Summary("Your question")] string question)
{
var answer = _answers[_random.Next(21)];
var userInfo = Context.User;
await ReplyAsync($"{userInfo.Username} asked, \"{question}\" Magic 8-ball says: ***\"{answer}\"***");
}
}
}
| using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace portalbot.Commands
{
public class AskModule : ModuleBase
{
private List<string> _answers = new List<string>
{
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes, definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."
};
private readonly Random _random;
public AskModule(Random random)
{
_random = random;
}
[Command("ask"), Summary("Ask a question.")]
public async Task Ask([Remainder, Summary("Your question")] string question)
{
var answer = _answers[_random.Next(20)];
var userInfo = Context.User;
await ReplyAsync($"{userInfo.Username} asked, \"{question}\" Magic 8-ball says: ***\"{answer}\"***");
}
}
}
|
Leverage 'GuardIsNotNullOrWhiteSpace' method instead of 'GuardIsNotNull' | using System.Collections.Generic;
using System.Linq;
using Spk.Common.Helpers.Guard;
namespace Spk.Common.Helpers.Service
{
public class ServiceResult
{
public IEnumerable<string> Errors => _internalErrors;
private readonly List<string> _internalErrors = new List<string>();
public IEnumerable<string> Warnings => _internalWarnings;
private readonly List<string> _internalWarnings = new List<string>();
public bool Success => !Errors.Any();
public bool HasWarnings => Warnings.Any();
public void AddError(string error)
{
error.GuardIsNotNull(nameof(error));
_internalErrors.Add(error);
}
public string GetFirstError()
{
return Errors.FirstOrDefault();
}
public void AddWarning(string warning)
{
warning.GuardIsNotNull(nameof(warning));
_internalWarnings.Add(warning);
}
public string GetFirstWarning()
{
return Warnings.FirstOrDefault();
}
}
public class ServiceResult<T> : ServiceResult
{
public T Data { get; private set; }
public ServiceResult(T data)
{
SetData(data.GuardIsNotNull(nameof(data)));
}
public ServiceResult()
{
}
public void SetData(T data)
{
Data = data;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Spk.Common.Helpers.Guard;
namespace Spk.Common.Helpers.Service
{
public class ServiceResult
{
public IEnumerable<string> Errors => _internalErrors;
private readonly List<string> _internalErrors = new List<string>();
public IEnumerable<string> Warnings => _internalWarnings;
private readonly List<string> _internalWarnings = new List<string>();
public bool Success => !Errors.Any();
public bool HasWarnings => Warnings.Any();
public void AddError(string error)
{
error.GuardIsNotNullOrWhiteSpace(nameof(error));
_internalErrors.Add(error);
}
public string GetFirstError()
{
return Errors.FirstOrDefault();
}
public void AddWarning(string warning)
{
warning.GuardIsNotNullOrWhiteSpace(nameof(warning));
_internalWarnings.Add(warning);
}
public string GetFirstWarning()
{
return Warnings.FirstOrDefault();
}
}
public class ServiceResult<T> : ServiceResult
{
public T Data { get; private set; }
public ServiceResult(T data)
{
SetData(data.GuardIsNotNull(nameof(data)));
}
public ServiceResult()
{
}
public void SetData(T data)
{
Data = data;
}
}
}
|
Add t=0 display to notes. | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
public class DrawableNote : DrawableManiaHitObject<Note>
{
private NotePiece headPiece;
public DrawableNote(Note hitObject)
: base(hitObject)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Add(headPiece = new NotePiece
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre
});
}
public override Color4 AccentColour
{
get { return AccentColour; }
set
{
if (base.AccentColour == value)
return;
base.AccentColour = value;
headPiece.AccentColour = value;
}
}
protected override void UpdateState(ArmedState state)
{
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
public class DrawableNote : DrawableManiaHitObject<Note>
{
private NotePiece headPiece;
public DrawableNote(Note hitObject)
: base(hitObject)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Add(headPiece = new NotePiece
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre
});
}
public override Color4 AccentColour
{
get { return AccentColour; }
set
{
if (base.AccentColour == value)
return;
base.AccentColour = value;
headPiece.AccentColour = value;
}
}
protected override void Update()
{
if (Time.Current > HitObject.StartTime)
Colour = Color4.Green;
}
protected override void UpdateState(ArmedState state)
{
}
}
}
|
Tweak delete cloned build chain routine. | using System.Linq;
using System.Threading.Tasks;
using TeamCityApi.Helpers;
using TeamCityApi.Logging;
namespace TeamCityApi.UseCases
{
public class DeleteClonedBuildChainUseCase
{
private static readonly ILog Log = LogProvider.GetLogger(typeof(DeleteClonedBuildChainUseCase));
private readonly ITeamCityClient _client;
public DeleteClonedBuildChainUseCase(ITeamCityClient client)
{
_client = client;
}
public async Task Execute(string buildConfigId, bool simulate = false)
{
Log.InfoFormat("Delete Cloned Build Chain.");
var buildConfig = await _client.BuildConfigs.GetByConfigurationId(buildConfigId);
var buildChainId = buildConfig.Parameters[ParameterName.BuildConfigChainId].Value;
var buildConfigChain = new BuildConfigChain(_client.BuildConfigs, buildConfig);
await DeleteClonedBuildChain(buildConfigChain, buildChainId, simulate);
}
private async Task DeleteClonedBuildChain(BuildConfigChain buildConfigChain, string buildChainId, bool simulate)
{
foreach (var node in buildConfigChain.Nodes.Where(node => node.Value.Parameters[ParameterName.BuildConfigChainId].Value == buildChainId))
{
Log.InfoFormat("Deleting buildConfigId: {0}", node.Value.Id);
if (!simulate)
{
await _client.BuildConfigs.DeleteBuildConfig(node.Value.Id);
}
}
}
}
} | using System.Linq;
using System.Threading.Tasks;
using TeamCityApi.Helpers;
using TeamCityApi.Logging;
namespace TeamCityApi.UseCases
{
public class DeleteClonedBuildChainUseCase
{
private static readonly ILog Log = LogProvider.GetLogger(typeof(DeleteClonedBuildChainUseCase));
private readonly ITeamCityClient _client;
public DeleteClonedBuildChainUseCase(ITeamCityClient client)
{
_client = client;
}
public async Task Execute(string buildConfigId, bool simulate = false)
{
Log.InfoFormat("Delete Cloned Build Chain.");
var buildConfig = await _client.BuildConfigs.GetByConfigurationId(buildConfigId);
var buildChainId = buildConfig.Parameters[ParameterName.BuildConfigChainId].Value;
var buildConfigChain = new BuildConfigChain(_client.BuildConfigs, buildConfig);
await DeleteClonedBuildChain(buildConfigChain, buildChainId, simulate);
}
private async Task DeleteClonedBuildChain(BuildConfigChain buildConfigChain, string buildChainId, bool simulate)
{
var buildConfigIdsToDelete = buildConfigChain.Nodes
.Where(node => node.Value.Parameters[ParameterName.BuildConfigChainId].Value == buildChainId)
.Select(n => n.Value.Id)
.ToList();
buildConfigIdsToDelete.Reverse(); //to start deletion from leafs
foreach (var buildConfigId in buildConfigIdsToDelete)
{
Log.InfoFormat("Deleting buildConfigId: {0}", buildConfigId);
if (!simulate)
{
await _client.BuildConfigs.DeleteBuildConfig(buildConfigId);
}
}
}
}
} |
Rewrite this to be shorter & consistent | using System;
using System.Web;
namespace Stampsy.ImageSource
{
public class AssetDescription : IDescription
{
public enum AssetImageKind
{
Thumbnail,
FullResolution
}
public AssetImageKind Kind { get; private set; }
public string AssetUrl { get; private set; }
public string Extension { get; private set; }
private Uri _url;
public Uri Url {
get { return _url; }
set {
_url = value;
Kind = ParseImageKind (value);
AssetUrl = GenerateAssetUrl (value, Kind);
Extension = ParseExtension (value);
}
}
static string GenerateAssetUrl (Uri url, AssetImageKind size)
{
if (size == AssetImageKind.Thumbnail)
return url.AbsoluteUri.Replace ("thumbnail", "asset");
return url.AbsoluteUri;
}
static AssetImageKind ParseImageKind (Uri url)
{
return url.Host == "thumbnail"
? AssetImageKind.Thumbnail
: AssetImageKind.FullResolution;
}
static string ParseExtension (Uri url)
{
var ext = HttpUtility.ParseQueryString (url.AbsoluteUri) ["ext"];
if (!string.IsNullOrEmpty (ext))
ext = "." + ext.ToLower ();
return ext;
}
}
}
| using System;
using System.Web;
namespace Stampsy.ImageSource
{
public class AssetDescription : IDescription
{
public enum AssetImageKind
{
Thumbnail,
FullResolution
}
public AssetImageKind Kind { get; private set; }
public string AssetUrl { get; private set; }
public string Extension { get; private set; }
private Uri _url;
public Uri Url {
get { return _url; }
set {
_url = value;
Kind = ParseImageKind (value);
AssetUrl = GenerateAssetUrl (value, Kind);
Extension = ParseExtension (value);
}
}
static string GenerateAssetUrl (Uri url, AssetImageKind size)
{
var builder = new UriBuilder (url);
builder.Host = "asset";
return builder.ToString ();
}
static AssetImageKind ParseImageKind (Uri url)
{
return url.Host == "thumbnail"
? AssetImageKind.Thumbnail
: AssetImageKind.FullResolution;
}
static string ParseExtension (Uri url)
{
var ext = HttpUtility.ParseQueryString (url.AbsoluteUri) ["ext"];
if (!string.IsNullOrEmpty (ext))
ext = "." + ext.ToLower ();
return ext;
}
}
}
|
Change UseCsla extension method from HostBuilder to IHostBuilder for: !NET40 and !NET45, as its not available for those. | //-----------------------------------------------------------------------
// <copyright file="WebConfiguration.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Implement extension methods for .NET Core configuration</summary>
//-----------------------------------------------------------------------
using System;
using Microsoft.Extensions.Hosting;
namespace Csla.Configuration
{
/// <summary>
/// Implement extension methods for .NET Core configuration
/// </summary>
public static class WindowsConfigurationExtensions
{
/// <summary>
/// Configures the application to use CSLA .NET
/// </summary>
/// <param name="builder">IHostBuilder instance</param>
public static HostBuilder UseCsla(this HostBuilder builder)
{
UseCsla(builder, null);
return builder;
}
/// <summary>
/// Configures the application to use CSLA .NET
/// </summary>
/// <param name="builder">IHostBuilder instance</param>
/// <param name="config">Implement to configure CSLA .NET</param>
public static HostBuilder UseCsla(
this HostBuilder builder, Action<CslaConfiguration> config)
{
CslaConfiguration.Configure().
ContextManager(typeof(Csla.Windows.ApplicationContextManager));
config?.Invoke(CslaConfiguration.Configure());
return builder;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="WebConfiguration.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Implement extension methods for .NET Core configuration</summary>
//-----------------------------------------------------------------------
using System;
using Microsoft.Extensions.Hosting;
namespace Csla.Configuration
{
/// <summary>
/// Implement extension methods for .NET Core configuration
/// </summary>
public static class WindowsConfigurationExtensions
{
/// <summary>
/// Configures the application to use CSLA .NET
/// </summary>
/// <param name="builder">IHostBuilder instance</param>
public static IHostBuilder UseCsla(this IHostBuilder builder)
{
UseCsla(builder, null);
return builder;
}
/// <summary>
/// Configures the application to use CSLA .NET
/// </summary>
/// <param name="builder">IHostBuilder instance</param>
/// <param name="config">Implement to configure CSLA .NET</param>
public static IHostBuilder UseCsla(
this IHostBuilder builder, Action<CslaConfiguration> config)
{
CslaConfiguration.Configure().
ContextManager(typeof(Csla.Windows.ApplicationContextManager));
config?.Invoke(CslaConfiguration.Configure());
return builder;
}
}
}
|
Add missing interface for FindPlayerById | using System.Collections.Generic;
namespace Oxide.Core.Libraries.Covalence
{
/// <summary>
/// Represents a generic player manager
/// </summary>
public interface IPlayerManager
{
#region Player Finding
/// <summary>
/// Gets all players
/// </summary>
/// <returns></returns>
IEnumerable<IPlayer> All { get; }
/// <summary>
/// Gets all connected players
/// </summary>
/// <returns></returns>
IEnumerable<IPlayer> Connected { get; }
/// <summary>
/// Finds a single player given a partial name or unique ID (case-insensitive, wildcards accepted, multiple matches returns null)
/// </summary>
/// <param name="partialNameOrId"></param>
/// <returns></returns>
IPlayer FindPlayer(string partialNameOrId);
/// <summary>
/// Finds any number of players given a partial name or unique ID (case-insensitive, wildcards accepted)
/// </summary>
/// <param name="partialNameOrId"></param>
/// <returns></returns>
IEnumerable<IPlayer> FindPlayers(string partialNameOrId);
#endregion
}
}
| using System.Collections.Generic;
namespace Oxide.Core.Libraries.Covalence
{
/// <summary>
/// Represents a generic player manager
/// </summary>
public interface IPlayerManager
{
#region Player Finding
/// <summary>
/// Gets all players
/// </summary>
/// <returns></returns>
IEnumerable<IPlayer> All { get; }
/// <summary>
/// Gets all connected players
/// </summary>
/// <returns></returns>
IEnumerable<IPlayer> Connected { get; }
/// <summary>
/// Finds a single player given unique ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
IPlayer FindPlayerById(string id);
/// <summary>
/// Finds a single player given a partial name or unique ID (case-insensitive, wildcards accepted, multiple matches returns null)
/// </summary>
/// <param name="partialNameOrId"></param>
/// <returns></returns>
IPlayer FindPlayer(string partialNameOrId);
/// <summary>
/// Finds any number of players given a partial name or unique ID (case-insensitive, wildcards accepted)
/// </summary>
/// <param name="partialNameOrId"></param>
/// <returns></returns>
IEnumerable<IPlayer> FindPlayers(string partialNameOrId);
#endregion
}
}
|
Add some extra options to the agent broker interface | using System;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public interface IAgentBroker
{
IObservable<MessageListenerOptions> Listen<T>();
IObservable<MessageListenerOptions> ListenIncludeLatest<T>();
void SendMessage(object message);
}
} | using System;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public interface IAgentBroker
{
IObservable<MessageListenerOptions> Listen<T>();
IObservable<MessageListenerOptions> ListenIncludeLatest<T>();
IObservable<MessageListenerOptions> ListenAll();
IObservable<MessageListenerOptions> ListenAllIncludeLatest();
void SendMessage(object message);
}
} |
Add some more message types | namespace Curse.NET.SocketModel
{
public enum RequestType
{
Login = -2101997347,
}
public enum ResponseType
{
UserActivityChange = 1260535191,
ChannelReference = -695526586,
ChatMessage = -635182161,
Login = -815187584,
UnknownChange = 149631008
}
}
// | namespace Curse.NET.SocketModel
{
public enum RequestType
{
Login = -2101997347,
}
public enum ResponseType
{
ChannelStatusChanged = 72981382,
UserActivityChange = 1260535191,
ChannelMarkedRead = -695526586,
ChatMessage = -635182161,
Login = -815187584,
MessageChanged = 149631008,
Unknown1 = 705131365
}
}
// |
Add test for authorization requirement in TraktUserApproveFollowerRequest | namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users;
[TestClass]
public class TraktUserApproveFollowerRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsNotAbstract()
{
typeof(TraktUserApproveFollowerRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsSealed()
{
typeof(TraktUserApproveFollowerRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsSubclassOfATraktSingleItemBodylessPostByIdRequest()
{
typeof(TraktUserApproveFollowerRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostByIdRequest<TraktUserFollower>)).Should().BeTrue();
}
}
}
| namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserApproveFollowerRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsNotAbstract()
{
typeof(TraktUserApproveFollowerRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsSealed()
{
typeof(TraktUserApproveFollowerRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestIsSubclassOfATraktSingleItemBodylessPostByIdRequest()
{
typeof(TraktUserApproveFollowerRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostByIdRequest<TraktUserFollower>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserApproveFollowerRequestHasAuthorizationRequired()
{
var request = new TraktUserApproveFollowerRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
|
Fix YuukaWater drop creating errors on contact |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NitorInc.Utility;
namespace NitorInc.YuukaWater {
public class YuukaWaterWaterdrop : MonoBehaviour {
public float scaleSpeed = 1.0f;
public GameObject sprayEffect;
Rigidbody2D rigid;
private Vector2 yuukaVel;
void Start() {
rigid = GetComponent<Rigidbody2D>();
TimerManager.NewTimer(2.0f, SelfDestruct, 0);
}
public void SetInitialForce(Vector2 vel, Vector2 yuukaVel)
{
this.yuukaVel = yuukaVel;
if (rigid == null)
rigid = GetComponent<Rigidbody2D>();
rigid.velocity = vel + yuukaVel;
Update();
}
void SelfDestruct() {
if (this != null) {
Destroy(gameObject);
}
}
// Update is called once per frame
void Update() {
transform.up = (rigid.velocity - yuukaVel) * -1.0f;
transform.localScale += transform.localScale * scaleSpeed * Time.deltaTime;
}
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.GetComponentInParent<YuukaWaterWaterdrop>() == null) {
Instantiate(sprayEffect, collision.contacts[0].point, Quaternion.identity);
Destroy(gameObject);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NitorInc.Utility;
namespace NitorInc.YuukaWater {
public class YuukaWaterWaterdrop : MonoBehaviour {
public float scaleSpeed = 1.0f;
public GameObject sprayEffect;
Rigidbody2D rigid;
private Vector2 yuukaVel;
void Start() {
rigid = GetComponent<Rigidbody2D>();
TimerManager.NewTimer(2.0f, SelfDestruct, 0);
}
public void SetInitialForce(Vector2 vel, Vector2 yuukaVel)
{
this.yuukaVel = yuukaVel;
if (rigid == null)
rigid = GetComponent<Rigidbody2D>();
rigid.velocity = vel + yuukaVel;
Update();
}
void SelfDestruct() {
if (this != null) {
Destroy(gameObject);
}
}
// Update is called once per frame
void Update() {
transform.up = (rigid.velocity - yuukaVel) * -1.0f;
transform.localScale += transform.localScale * scaleSpeed * Time.deltaTime;
}
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.GetComponentInParent<YuukaWaterWaterdrop>() == null) {
if (collision.contacts.Length > 0)
Instantiate(sprayEffect, collision.contacts[0].point, Quaternion.identity);
Destroy(gameObject);
}
}
}
}
|
Adjust locations where to look for wwwroot. | using System.IO;
using Microsoft.AspNetCore.Hosting;
using NLog;
namespace HelloWorldApp
{
public class Program
{
// Entry point for the application.
public static void Main(string[] args)
{
SetupNLog();
var host = new WebHostBuilder()
.UseKestrel()
.UseWebRoot(FindWebRoot())
.UseStartup<Startup>()
.Build();
host.Run();
}
private static void SetupNLog()
{
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
location = location.Substring(0, location.LastIndexOf(Path.DirectorySeparatorChar));
location = location + Path.DirectorySeparatorChar + "nlog.config";
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(location, true);
}
private static string FindWebRoot()
{
var currentDir = Directory.GetCurrentDirectory();
var webRoot = currentDir + Path.DirectorySeparatorChar +
".." + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
"ui" + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
".." + Path.DirectorySeparatorChar +
"ui" + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
"wwwroot";
return webRoot;
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
using NLog;
namespace HelloWorldApp
{
public class Program
{
// Entry point for the application.
public static void Main(string[] args)
{
SetupNLog();
var host = new WebHostBuilder()
.UseKestrel()
.UseWebRoot(FindWebRoot())
.UseStartup<Startup>()
.Build();
host.Run();
}
private static void SetupNLog()
{
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
location = location.Substring(0, location.LastIndexOf(Path.DirectorySeparatorChar));
location = location + Path.DirectorySeparatorChar + "nlog.config";
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(location, true);
}
private static string FindWebRoot()
{
var currentDir = Directory.GetCurrentDirectory();
var webRoot = currentDir + Path.DirectorySeparatorChar +
".." + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
"ui" + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
".." + Path.DirectorySeparatorChar +
".." + Path.DirectorySeparatorChar +
"ui" + Path.DirectorySeparatorChar +
"wwwroot";
if (!Directory.Exists(webRoot))
webRoot = currentDir + Path.DirectorySeparatorChar +
"wwwroot";
return webRoot;
}
}
}
|
Update mapping config with service profile. | using AutoMapper;
using Baskerville.App.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Baskerville.App
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
Mapper.Initialize(c => c.AddProfile<MappingProfile>());
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using AutoMapper;
using Baskerville.App.App_Start;
using Baskerville.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Baskerville.App
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
Mapper.Initialize(p =>
{
p.AddProfile<MappingProfile>();
p.AddProfile<ServiceMappingProfile>();
});
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
|
Use Expression-bodied members and never execeeds its capacity | using System;
using System.Collections.Generic;
public class CircularBuffer<T>
{
private readonly Queue<T> _buffer;
private readonly int _capacity;
public CircularBuffer(int capacity)
{
_buffer = new Queue<T>(capacity);
_capacity = capacity;
}
public T Read()
{
return _buffer.Dequeue();
}
public void Write(T value)
{
_buffer.Enqueue(value);
if (_buffer.Count > _capacity)
{
throw new InvalidOperationException();
}
}
public void Overwrite(T value)
{
_buffer.Enqueue(value);
if (_buffer.Count > _capacity)
{
_buffer.Dequeue();
}
}
public void Clear()
{
_buffer.Clear();
}
} | using System;
using System.Collections.Generic;
public class CircularBuffer<T>
{
private readonly Queue<T> _buffer;
private readonly int _capacity;
public CircularBuffer(int capacity)
{
_buffer = new Queue<T>(capacity);
_capacity = capacity;
}
public T Read() => _buffer.Dequeue();
public void Write(T value)
{
if (_buffer.Count + 1 > _capacity)
{
throw new InvalidOperationException();
}
_buffer.Enqueue(value);
}
public void Overwrite(T value)
{
if (_buffer.Count + 1 > _capacity)
{
_buffer.Dequeue();
}
_buffer.Enqueue(value);
}
public void Clear() => _buffer.Clear();
} |
Index processor to store result, not enumerable, on definition | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MongoDB.Bson.Serialization;
using MongoFramework.Attributes;
namespace MongoFramework.Infrastructure.Mapping.Processors
{
public class IndexProcessor : IMappingProcessor
{
public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
{
definition.Indexes = definition.TraverseProperties().SelectMany(p =>
p.PropertyInfo.GetCustomAttributes<IndexAttribute>().Select(a => new EntityIndex
{
Property = p,
IndexName = a.Name,
IsUnique = a.IsUnique,
SortOrder = a.SortOrder,
IndexPriority = a.IndexPriority,
IndexType = a.IndexType
})
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MongoDB.Bson.Serialization;
using MongoFramework.Attributes;
namespace MongoFramework.Infrastructure.Mapping.Processors
{
public class IndexProcessor : IMappingProcessor
{
public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
{
definition.Indexes = definition.TraverseProperties().SelectMany(p =>
p.PropertyInfo.GetCustomAttributes<IndexAttribute>().Select(a => new EntityIndex
{
Property = p,
IndexName = a.Name,
IsUnique = a.IsUnique,
SortOrder = a.SortOrder,
IndexPriority = a.IndexPriority,
IndexType = a.IndexType
})
).ToArray();
}
}
}
|
Use enum for scope type | using System;
using Platform.Validation;
using Shaolinq;
namespace IdentityServer3.Shaolinq.DataModel
{
[DataAccessObject(Name = "Scope")]
public abstract class DbScope : DataAccessObject<Guid>
{
[PersistedMember]
public abstract bool Enabled { get; set; }
[PersistedMember]
[ValueRequired]
[SizeConstraint(MaximumLength = 200)]
public abstract string Name { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string DisplayName { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string Description { get; set; }
[PersistedMember]
public abstract bool Required { get; set; }
[PersistedMember]
public abstract bool Emphasize { get; set; }
[PersistedMember]
public abstract int Type { get; set; }
[RelatedDataAccessObjects]
public abstract RelatedDataAccessObjects<DbScopeClaim> ScopeClaims { get; }
[PersistedMember]
public abstract bool IncludeAllClaimsForUser { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string ClaimsRule { get; set; }
[PersistedMember]
public abstract bool ShowInDiscoveryDocument { get; set; }
}
} | using System;
using IdentityServer3.Core.Models;
using Platform.Validation;
using Shaolinq;
namespace IdentityServer3.Shaolinq.DataModel
{
[DataAccessObject(Name = "Scope")]
public abstract class DbScope : DataAccessObject<Guid>
{
[PersistedMember]
public abstract bool Enabled { get; set; }
[PersistedMember]
[ValueRequired]
[SizeConstraint(MaximumLength = 200)]
public abstract string Name { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string DisplayName { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string Description { get; set; }
[PersistedMember]
public abstract bool Required { get; set; }
[PersistedMember]
public abstract bool Emphasize { get; set; }
[PersistedMember]
public abstract ScopeType Type { get; set; }
[RelatedDataAccessObjects]
public abstract RelatedDataAccessObjects<DbScopeClaim> ScopeClaims { get; }
[PersistedMember]
public abstract bool IncludeAllClaimsForUser { get; set; }
[PersistedMember]
[SizeConstraint(MaximumLength = 200)]
public abstract string ClaimsRule { get; set; }
[PersistedMember]
public abstract bool ShowInDiscoveryDocument { get; set; }
}
} |
Update ARM assembly and file version to 2.0.0 | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
|
Fix showing window at boot | using System;
using System.Collections.Generic;
using System.Linq;
using PEPlugin;
namespace WeightedOffsetBlend
{
public class Plugin : PEPluginClass
{
private static MainForm FormInstance { get; set; }
public override string Name
{
get { return "重み付きオフセット付加"; }
}
public override IPEPluginOption Option
{
get
{
return new PEPluginOption(bootup: true);
}
}
public override void Run(IPERunArgs args)
{
if (args.IsBootup)
{
FormInstance = new MainForm(args.Host);
FormInstance.Visible = false;
FormInstance.Show();
return;
}
FormInstance.Visible = true;
FormInstance.BringToFront();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using PEPlugin;
namespace WeightedOffsetBlend
{
public class Plugin : PEPluginClass
{
private static MainForm FormInstance { get; set; }
public override string Name
{
get { return "重み付きオフセット付加"; }
}
public override IPEPluginOption Option
{
get
{
return new PEPluginOption(bootup: true);
}
}
public override void Run(IPERunArgs args)
{
if (args.IsBootup)
{
FormInstance = new MainForm(args.Host);
FormInstance.Show();
FormInstance.Visible = false;
return;
}
FormInstance.Visible = true;
FormInstance.BringToFront();
}
}
}
|
Add SA1400 test for local functions | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.MaintainabilityRules
{
using StyleCop.Analyzers.Test.MaintainabilityRules;
public class SA1400CSharp7UnitTests : SA1400UnitTests
{
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.MaintainabilityRules
{
using System.Threading;
using System.Threading.Tasks;
using StyleCop.Analyzers.Test.MaintainabilityRules;
using Xunit;
public class SA1400CSharp7UnitTests : SA1400UnitTests
{
/// <summary>
/// Verifies that local functions, which do not support access modifiers, do not trigger SA1400.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestLocalFunctionAsync()
{
var testCode = @"
internal class ClassName
{
public void MethodName()
{
void LocalFunction()
{
}
}
}
";
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
|
Use a location name in ClusterManagerClient snippet | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using System;
using Xunit;
// TODO: Use location instead of zone when building the request.
// The Container API config is being revisited to make all of this simpler.
namespace Google.Cloud.Container.V1.Snippets
{
[SnippetOutputCollector]
[Collection(nameof(ContainerSnippetFixture))]
public class ClusterManagerClientSnippets
{
private readonly ContainerSnippetFixture _fixture;
public ClusterManagerClientSnippets(ContainerSnippetFixture fixture) =>
_fixture = fixture;
[Fact]
public void ListAllClusters()
{
string projectId = _fixture.ProjectId;
// Sample: ListAllClusters
ClusterManagerClient client = ClusterManagerClient.Create();
// You can list clusters in a single zone, or specify "-" for all zones.
ListClustersResponse zones = client.ListClusters(projectId, zone: "-");
foreach (Cluster cluster in zones.Clusters)
{
Console.WriteLine($"Cluster {cluster.Name} in {cluster.Location}");
}
// End sample
}
}
}
| // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax.ResourceNames;
using Google.Cloud.ClientTesting;
using System;
using Xunit;
namespace Google.Cloud.Container.V1.Snippets
{
[SnippetOutputCollector]
[Collection(nameof(ContainerSnippetFixture))]
public class ClusterManagerClientSnippets
{
private readonly ContainerSnippetFixture _fixture;
public ClusterManagerClientSnippets(ContainerSnippetFixture fixture) =>
_fixture = fixture;
[Fact]
public void ListAllClusters()
{
string projectId = _fixture.ProjectId;
// Sample: ListAllClusters
ClusterManagerClient client = ClusterManagerClient.Create();
// You can list clusters in a single zone, or specify "-" for all zones.
LocationName location = new LocationName(projectId, locationId: "-");
ListClustersResponse zones = client.ListClusters(location.ToString());
foreach (Cluster cluster in zones.Clusters)
{
Console.WriteLine($"Cluster {cluster.Name} in {cluster.Location}");
}
// End sample
}
}
}
|
Move GetProjectInstance to the task | using System;
namespace Clarius.TransformOnBuild.MSBuild.Task
{
public class TransformOnBuildTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Build.Execution;
namespace Clarius.TransformOnBuild.MSBuild.Task
{
public class TransformOnBuildTask : Microsoft.Build.Utilities.Task
{
private ProjectInstance _projectInstance;
private Dictionary<string, string> _properties;
const BindingFlags BindingFlags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;
public override bool Execute()
{
_projectInstance = GetProjectInstance();
_properties = _projectInstance.Properties.ToDictionary(p => p.Name, p => p.EvaluatedValue);
return true;
}
/// <summary>
/// Inspired by http://stackoverflow.com/questions/3043531/when-implementing-a-microsoft-build-utilities-task-how-to-i-get-access-to-the-va
/// </summary>
/// <returns></returns>
private ProjectInstance GetProjectInstance()
{
var buildEngineType = BuildEngine.GetType();
var targetBuilderCallbackField = buildEngineType.GetField("targetBuilderCallback", BindingFlags);
if (targetBuilderCallbackField == null)
throw new Exception("Could not extract targetBuilderCallback from " + buildEngineType.FullName);
var targetBuilderCallback = targetBuilderCallbackField.GetValue(BuildEngine);
var targetCallbackType = targetBuilderCallback.GetType();
var projectInstanceField = targetCallbackType.GetField("projectInstance", BindingFlags);
if (projectInstanceField == null)
throw new Exception("Could not extract projectInstance from " + targetCallbackType.FullName);
return (ProjectInstance) projectInstanceField.GetValue(targetBuilderCallback);
}
}
}
|
Add endpoint for getting log files | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
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 async Task<IActionResult> Scrub()
{
// Go through each soldier and fix casing on their name
foreach(var soldier in db.Soldiers)
{
soldier.FirstName = soldier.FirstName.ToTitleCase();
soldier.MiddleName = soldier.MiddleName.ToTitleCase();
soldier.LastName = soldier.LastName.ToTitleCase();
}
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
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()
{
var data = System.IO.File.ReadAllBytes($@"logs\{DateTime.Today:yyyyMMdd}.log");
var mimeType = "text/plain";
return File(data, mimeType);
}
}
} |
Set login screen as main | using System;
using System.Windows.Forms;
namespace HospitalAutomation.GUI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormHomePage());
}
}
}
| using System;
using System.Windows.Forms;
namespace HospitalAutomation.GUI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginForm());
}
}
}
|
Fix bug introduced with commit about screen scale | using System;
using UIKit;
namespace FFImageLoading.Extensions
{
public static class UnitsExtensions
{
private static nfloat _screenScale;
static UnitsExtensions()
{
UIScreen.MainScreen.InvokeOnMainThread(() =>
{
_screenScale = _screenScale;
});
}
public static int PointsToPixels(this double points)
{
return (int)Math.Floor(points * _screenScale);
}
public static int PixelsToPoints(this double px)
{
if (px == 0d)
return 0;
return (int)Math.Floor(px / UIScreen.MainScreen.Scale);
}
public static int PointsToPixels(this int points)
{
return PointsToPixels((double)points);
}
public static int PixelsToPoints(this int px)
{
return PixelsToPoints((double)px);
}
}
}
| using System;
using UIKit;
namespace FFImageLoading.Extensions
{
public static class UnitsExtensions
{
private static nfloat _screenScale;
static UnitsExtensions()
{
UIScreen.MainScreen.InvokeOnMainThread(() =>
{
_screenScale = UIScreen.MainScreen.Scale;
});
}
public static int PointsToPixels(this double points)
{
return (int)Math.Floor(points * _screenScale);
}
public static int PixelsToPoints(this double px)
{
if (px == 0d)
return 0;
return (int)Math.Floor(px / UIScreen.MainScreen.Scale);
}
public static int PointsToPixels(this int points)
{
return PointsToPixels((double)points);
}
public static int PixelsToPoints(this int px)
{
return PixelsToPoints((double)px);
}
}
}
|
Add default handlers for built in holdables | using System.Collections;
/// <summary>Contains commands for holdables (including the freeplay case and the missions binder).</summary>
public static class HoldableCommands
{
#region Commands
[Command("help")]
public static bool Help(TwitchHoldable holdable, string user, bool isWhisper) => holdable.PrintHelp(user, isWhisper);
[Command("(hold|pick up)")]
public static IEnumerator Hold(TwitchHoldable holdable) => holdable.Hold();
[Command("(drop|let go|put down)")]
public static IEnumerator Drop(TwitchHoldable holdable) => holdable.Drop();
[Command(@"(turn|turn round|turn around|rotate|flip|spin)")]
public static IEnumerator Flip(TwitchHoldable holdable) => holdable.Turn();
[Command(null)]
public static IEnumerator DefaultCommand(TwitchHoldable holdable, string user, bool isWhisper, string cmd) => holdable.RespondToCommand(user, cmd, isWhisper);
#endregion
}
| using System.Collections;
/// <summary>Contains commands for holdables (including the freeplay case and the missions binder).</summary>
public static class HoldableCommands
{
#region Commands
[Command("help")]
public static bool Help(TwitchHoldable holdable, string user, bool isWhisper) => holdable.PrintHelp(user, isWhisper);
[Command("(hold|pick up)")]
public static IEnumerator Hold(TwitchHoldable holdable) => holdable.Hold();
[Command("(drop|let go|put down)")]
public static IEnumerator Drop(TwitchHoldable holdable) => holdable.Drop();
[Command(@"(turn|turn round|turn around|rotate|flip|spin)")]
public static IEnumerator Flip(TwitchHoldable holdable) => holdable.Turn();
[Command(null)]
public static IEnumerator DefaultCommand(TwitchHoldable holdable, string user, bool isWhisper, string cmd)
{
if (holdable.CommandType == typeof(AlarmClockCommands))
return AlarmClockCommands.Snooze(holdable, user, isWhisper);
if (holdable.CommandType == typeof(IRCConnectionManagerCommands) ||
holdable.CommandType == typeof(MissionBinderCommands) ||
holdable.CommandType == typeof(FreeplayCommands))
return holdable.RespondToCommand(user, isWhisper);
return holdable.RespondToCommand(user, cmd, isWhisper);
}
#endregion
}
|
Add PlayerPrefs Value Search Func | using UnityEditor;
using UnityEngine;
public class PlayerPrefsEditor {
[MenuItem("Tools/PlayerPrefs/DeleteAll")]
static void DeleteAll(){
PlayerPrefs.DeleteAll();
Debug.Log("Delete All Data Of PlayerPrefs!!");
}
}
| using UnityEditor;
using UnityEngine;
public class PlayerPrefsEditor : EditorWindow {
string stringKey = "";
string intKey = "";
string floatKey = "";
[MenuItem("Tools/PlayerPrefs/DeleteAll")]
static void DeleteAll(){
PlayerPrefs.DeleteAll();
Debug.Log("Delete All Data Of PlayerPrefs!!");
}
[MenuItem("Tools/PlayerPrefs/OpenEditor")]
static void OpenEditor(){
EditorWindow.GetWindow<PlayerPrefsEditor>("PlayrePrefsEditor");
}
void OnGUI(){
GUILayout.Label( "Input PlayerPrefs Key Here" );
GUILayout.Label( "String Value" );
stringKey = GUILayout.TextField( stringKey );
if(PlayerPrefs.HasKey(stringKey)){
string data = PlayerPrefs.GetString(stringKey);
GUILayout.Label(data);
}
GUILayout.Label("Int Value");
intKey = GUILayout.TextField(intKey);
if(PlayerPrefs.HasKey(intKey)){
string data = PlayerPrefs.GetInt(intKey).ToString();
GUILayout.Label(data);
}
GUILayout.Label("Float Value");
floatKey = GUILayout.TextField(floatKey);
if(PlayerPrefs.HasKey(floatKey)){
string data = PlayerPrefs.GetFloat(floatKey).ToString();
GUILayout.Label(data);
}
}
}
|
Use correct Lib call in tests. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NugetAuditor;
namespace NugetAuditor.Tests
{
[TestClass]
public class NugetAuditorLibTests
{
[TestMethod]
public void CanAuditFiles()
{
var f3 = Path.Combine("TestFiles", "packages.config.example.3");
Assert.IsTrue(File.Exists(f3));
var results = Lib.NugetAuditor.AuditPackages(f3, 0);
Assert.AreNotEqual(0, results.Count(r => r.MatchedVulnerabilities > 0));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NugetAuditor;
namespace NugetAuditor.Tests
{
[TestClass]
public class NugetAuditorLibTests
{
[TestMethod]
public void CanAuditFiles()
{
var f3 = Path.Combine("TestFiles", "packages.config.example.3");
Assert.IsTrue(File.Exists(f3));
var results = Lib.NugetAuditor.AuditPackages(f3, 0, new NuGet.Common.NullLogger());
Assert.AreNotEqual(0, results.Count(r => r.MatchedVulnerabilities > 0));
}
}
}
|
Fix display issue for dateTime cells | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Scalar.Presentation
{
public class DateTimePresenter : BasePresenter
{
protected override string PresentNotNull(object value)
{
switch (value)
{
case DateTime x: return PresentDateTime(x);
case string x: return PresentString(x);
default:
return PresentString(value.ToString());
}
}
protected string PresentDateTime(DateTime value)
{
if (value.TimeOfDay.Ticks == 0)
return value.ToString("yyyy-MM-dd");
else if (value.Millisecond == 0)
return value.ToString("yyyy-MM-dd hh:mm:ss");
else
return value.ToString("yyyy-MM-dd hh:mm:ss.fff");
}
protected string PresentString(string value)
{
DateTime valueDateTime = DateTime.MinValue;
if (DateTime.TryParse(value, out valueDateTime))
return PresentDateTime(valueDateTime);
else
return value;
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Scalar.Presentation
{
public class DateTimePresenter : BasePresenter
{
protected override string PresentNotNull(object value)
{
switch (value)
{
case DateTime x: return PresentDateTime(x);
case string x: return PresentString(x);
default:
return PresentString(value.ToString());
}
}
protected string PresentDateTime(DateTime value)
{
if (value.TimeOfDay.Ticks == 0)
return value.ToString("yyyy-MM-dd");
else if (value.Millisecond == 0)
return value.ToString("yyyy-MM-dd HH:mm:ss");
else
return value.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
protected string PresentString(string value)
{
DateTime valueDateTime = DateTime.MinValue;
if (DateTime.TryParse(value, out valueDateTime))
return PresentDateTime(valueDateTime);
else
return value;
}
}
}
|
Include context in SMSService sending | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(TwilioConfig config)
{
this._twilioAccountSId = config.AccountSid;
this._twilioAuthToken = config.AuthToken;
this._twilioSourceNumber = config.SourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
public class TwilioConfig
{
public String AccountSid { get; set; }
public String AuthToken { get; set; }
public String SourceNumber { get; set; }
}
}
} | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(TwilioConfig config)
{
this._twilioAccountSId = config.AccountSid;
this._twilioAuthToken = config.AuthToken;
this._twilioSourceNumber = config.SourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync", context: notification))
{
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
public class TwilioConfig
{
public String AccountSid { get; set; }
public String AuthToken { get; set; }
public String SourceNumber { get; set; }
}
}
} |
Add Smart Watch to device | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
namespace Wangkanai.Detection.Models
{
[Flags]
public enum Device
{
Desktop = 0, // Windows, Mac, Linux
Tablet = 1 << 0, // iPad, Android
Mobile = 1 << 1, // iPhone, Android
Tv = 1 << 2, // Samsung, LG
Console = 1 << 3, // XBox, Play Station
Car = 1 << 4, // Ford, Toyota
IoT = 1 << 5 // Raspberry Pi
}
}
| // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
namespace Wangkanai.Detection.Models
{
[Flags]
public enum Device
{
Desktop = 0, // Windows, Mac, Linux
Tablet = 1 << 0, // iPad, Android
Mobile = 1 << 1, // iPhone, Android
Watch = 1 << 2, // Smart Watchs
Tv = 1 << 3, // Samsung, LG
Console = 1 << 4, // XBox, Play Station
Car = 1 << 5, // Ford, Toyota
IoT = 1 << 6 // Raspberry Pi
}
}
|
Add processing projects in solution folders | using EnvDTE;
using System;
using System.Linq;
namespace T4TS
{
public class ProjectTraverser
{
public Action<CodeNamespace> WithNamespace { get; private set; }
public ProjectTraverser(Project project, Action<CodeNamespace> withNamespace)
{
if (project == null)
throw new ArgumentNullException("project");
if (withNamespace == null)
throw new ArgumentNullException("withNamespace");
WithNamespace = withNamespace;
if (project.ProjectItems != null)
Traverse(project.ProjectItems);
}
private void Traverse(ProjectItems items)
{
foreach (ProjectItem pi in items)
{
if (pi.FileCodeModel != null)
{
var codeElements = pi.FileCodeModel.CodeElements;
foreach (var ns in codeElements.OfType<CodeNamespace>())
WithNamespace(ns);
}
if (pi.ProjectItems != null)
Traverse(pi.ProjectItems);
}
}
}
}
| using EnvDTE;
using System;
using System.Linq;
namespace T4TS
{
public class ProjectTraverser
{
public Action<CodeNamespace> WithNamespace { get; private set; }
public ProjectTraverser(Project project, Action<CodeNamespace> withNamespace)
{
if (project == null)
throw new ArgumentNullException("project");
if (withNamespace == null)
throw new ArgumentNullException("withNamespace");
WithNamespace = withNamespace;
if (project.ProjectItems != null)
Traverse(project.ProjectItems);
}
private void Traverse(ProjectItems items)
{
foreach (ProjectItem pi in items)
{
if (pi.FileCodeModel != null)
{
var codeElements = pi.FileCodeModel.CodeElements;
foreach (var ns in codeElements.OfType<CodeNamespace>())
WithNamespace(ns);
}
if (pi.ProjectItems != null)
Traverse(pi.ProjectItems);
/* LionSoft: Process projects in solution folders */
else if (pi.SubProject != null && pi.SubProject.ProjectItems != null)
{
Traverse(pi.SubProject.ProjectItems);
}
/* --- */
}
}
}
}
|
Remove obsoleted & Unenforced PermissionSet | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: AssemblyProduct("Python for .NET")]
[assembly: AssemblyVersion("2.4.2.7")]
[assembly: AssemblyTitle("Python Console")]
[assembly: AssemblyDefaultAlias("python.exe")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: PermissionSet(SecurityAction.RequestMinimum, Name = "FullTrust")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyFileVersion("2.0.0.4")]
[assembly: NeutralResourcesLanguage("en")]
| using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: AssemblyProduct("Python for .NET")]
[assembly: AssemblyVersion("2.4.2.7")]
[assembly: AssemblyTitle("Python Console")]
[assembly: AssemblyDefaultAlias("python.exe")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyFileVersion("2.0.0.4")]
[assembly: NeutralResourcesLanguage("en")]
|
Change default exception to CallNotReceivedException and CallReceivedException in NSubtitute adapter. | using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Machine.Fakes.Sdk;
using NSubstitute;
namespace Machine.Fakes.Adapters.NSubstitute
{
internal class NSubstituteMethodCallOccurance<TFake> : IMethodCallOccurance where TFake : class
{
private readonly TFake _fake;
private readonly Expression<Action<TFake>> _func;
public NSubstituteMethodCallOccurance(TFake fake, Expression<Action<TFake>> func)
{
Guard.AgainstArgumentNull(fake, "fake");
Guard.AgainstArgumentNull(func, "func");
_fake = fake;
_func = func;
_func.Compile().Invoke(_fake.Received());
}
#region IMethodCallOccurance Members
public void Times(int numberOfTimesTheMethodShouldHaveBeenCalled)
{
if (CountCalls() < numberOfTimesTheMethodShouldHaveBeenCalled)
throw new Exception();
}
public void OnlyOnce()
{
if (CountCalls() != 1)
throw new Exception();
}
private int CountCalls()
{
var method = ((MethodCallExpression) _func.Body).Method;
return _fake
.ReceivedCalls()
.Select(x => x.GetMethodInfo())
.Where(x => x == method)
.Count();
}
public void Twice()
{
Times(2);
}
#endregion
}
} | using System;
using System.Linq;
using System.Linq.Expressions;
using Machine.Fakes.Sdk;
using NSubstitute;
using NSubstitute.Exceptions;
namespace Machine.Fakes.Adapters.NSubstitute
{
internal class NSubstituteMethodCallOccurance<TFake> : IMethodCallOccurance where TFake : class
{
private readonly TFake _fake;
private readonly Expression<Action<TFake>> _func;
public NSubstituteMethodCallOccurance(TFake fake, Expression<Action<TFake>> func)
{
Guard.AgainstArgumentNull(fake, "fake");
Guard.AgainstArgumentNull(func, "func");
_fake = fake;
_func = func;
_func.Compile().Invoke(_fake.Received());
}
#region IMethodCallOccurance Members
public void Times(int numberOfTimesTheMethodShouldHaveBeenCalled)
{
var calls = CountCalls();
if (calls < numberOfTimesTheMethodShouldHaveBeenCalled)
throw new CallNotReceivedException(
string.Format("Expected {0} calls to the method but received {1}",
numberOfTimesTheMethodShouldHaveBeenCalled, calls));
}
public void OnlyOnce()
{
var calls = CountCalls();
if (calls != 1)
throw new CallReceivedException(
string.Format("Expected only 1 call to the method but received {0}", calls));
}
public void Twice()
{
Times(2);
}
#endregion
private int CountCalls()
{
var method = ((MethodCallExpression) _func.Body).Method;
return _fake
.ReceivedCalls()
.Select(x => x.GetMethodInfo())
.Where(x => x == method)
.Count();
}
}
} |
Add library credits to "About" text | using System.Text;
using DesktopWidgets.Classes;
using DesktopWidgets.Properties;
namespace DesktopWidgets.Helpers
{
public static class AboutHelper
{
public static string AboutText
{
get
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"{AssemblyInfo.Title} ({AssemblyInfo.Version})");
stringBuilder.AppendLine();
stringBuilder.AppendLine($"Project: {Resources.GitHubMainPage}");
stringBuilder.AppendLine($"Changes: {Resources.GitHubCommits}");
stringBuilder.AppendLine($"Issues: {Resources.GitHubIssues}");
stringBuilder.AppendLine();
stringBuilder.AppendLine($"Icon made by {IconCredits}");
stringBuilder.AppendLine();
stringBuilder.Append(AssemblyInfo.Copyright);
return stringBuilder.ToString();
}
}
private static string IconCredits { get; } =
"Freepik (http://www.freepik.com) from www.flaticon.com" +
" is licensed under CC BY 3.0 (http://creativecommons.org/licenses/by/3.0/)";
}
} | using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesktopWidgets.Classes;
using DesktopWidgets.Properties;
namespace DesktopWidgets.Helpers
{
public static class AboutHelper
{
public static string AboutText
{
get
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"{AssemblyInfo.Title} ({AssemblyInfo.Version})");
stringBuilder.AppendLine();
stringBuilder.AppendLine($"Project: {Resources.GitHubMainPage}");
stringBuilder.AppendLine($"Changes: {Resources.GitHubCommits}");
stringBuilder.AppendLine($"Issues: {Resources.GitHubIssues}");
stringBuilder.AppendLine();
stringBuilder.AppendLine($"Icon made by {IconCredits}");
stringBuilder.AppendLine();
stringBuilder.AppendLine("Libraries:");
foreach (var library in Libraries
.Select(x => $" {x.Key}: {x.Value}"))
{
stringBuilder.AppendLine(library);
}
stringBuilder.AppendLine();
stringBuilder.Append(AssemblyInfo.Copyright);
return stringBuilder.ToString();
}
}
private static string IconCredits { get; } =
"Freepik (http://www.freepik.com) from www.flaticon.com" +
" is licensed under CC BY 3.0 (http://creativecommons.org/licenses/by/3.0/)";
private static Dictionary<string, string> Libraries => new Dictionary<string, string>
{
{"Common Service Locator", "commonservicelocator.codeplex.com"},
{"Extended WPF Toolkit", "wpftoolkit.codeplex.com"},
{"NotifyIcon", "hardcodet.net/projects/wpf-notifyicon"},
{"MVVM Light", "galasoft.ch/mvvm"},
{"Json.NET", "newtonsoft.com/json"},
{"NHotkey", "github.com/thomaslevesque/NHotkey"},
{"WpfAppBar", "github.com/PhilipRieck/WpfAppBar"}
};
}
} |
Fix nullreference when try to call disabled component | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClipPlane : MonoBehaviour
{
// input objects
public Slider slider;
public Material clipPlaneMaterial;
// private objects
private Renderer cube;
private float clipX;
void Start()
{
cube = GetComponent<Renderer>();
}
public void ClipPlaneOnValueChanged(float value)
{
clipX = value - 0.5f;
cube.sharedMaterial = clipPlaneMaterial;
cube.sharedMaterial.SetFloat("_ClipX", clipX);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClipPlane : MonoBehaviour
{
// input objects
public Slider slider;
public Material clipPlaneMaterial;
// private objects
private Renderer cube;
private float clipX;
void Start()
{
cube = GetComponent<Renderer>();
}
public void ClipPlaneOnValueChanged(float value)
{
clipX = value - 0.5f;
if (cube != null)
{
cube.sharedMaterial = clipPlaneMaterial;
cube.sharedMaterial.SetFloat("_ClipX", clipX);
}
}
}
|
Add code to create XML file | using System;
using System.Collections.Generic;
using System.IO;
namespace CreateXMLFile
{
internal static class Program
{
private static void Main()
{
const string fileName = "quotes.txt";
Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
List<string> quotesList = new List<string>();
StreamReader sr = new StreamReader(fileName);
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
quotesList.Add(line);
}
for (int i = 0; i < quotesList.Count; i = i + 2)
{
if (!dicoQuotes.ContainsKey(quotesList[i]))
{
dicoQuotes.Add(quotesList[i], quotesList[i + 1]);
}
else
{
Console.WriteLine(quotesList[i]);
}
}
Console.WriteLine("Press a key to exit:");
Console.ReadKey();
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
namespace CreateXMLFile
{
internal static class Program
{
private static void Main()
{
const string fileName = "quotes-cleaned.txt";
const string XmlFileName = "quotes-XML.txt";
Dictionary<string, string> dicoQuotes = new Dictionary<string, string>();
dicoQuotes = LoadDictionary(fileName);
// create XML file
if (!File.Exists(XmlFileName))
{
StreamWriter sw2 = new StreamWriter(XmlFileName, false);
sw2.WriteLine(string.Empty);
sw2.Close();
}
StreamWriter sw = new StreamWriter(XmlFileName, false);
foreach (KeyValuePair<string, string> keyValuePair in dicoQuotes)
{
sw.WriteLine(string.Empty);
}
sw.Close();
Console.WriteLine("Press a key to exit:");
Console.ReadKey();
}
private static string AddTag(string msg)
{
string result = string.Empty;
/*
*<Quote>
<Author></Author>
<Language>French</Language>
<QuoteValue></QuoteValue>
</Quote>
*/
return result;
}
private static Dictionary<string, string> LoadDictionary(string fileName)
{
Dictionary<string, string> result = new Dictionary<string, string>();
if (!File.Exists(fileName)) return result;
List<string> quotesList = new List<string>();
StreamReader sr = new StreamReader(fileName);
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
quotesList.Add(line);
}
for (int i = 0; i < quotesList.Count; i = i + 2)
{
if (!result.ContainsKey(quotesList[i]))
{
result.Add(quotesList[i], quotesList[i + 1]);
}
//else
//{
// Console.WriteLine(quotesList[i]);
//}
}
return result;
}
}
} |
Add wallet journal and transaction endpoints. | using ESISharp.Web;
namespace ESISharp.ESIPath.Character
{
/// <summary>Authenticated Character Wallet paths</summary>
public class CharacterWallet
{
protected ESIEve EasyObject;
internal CharacterWallet(ESIEve EasyEve)
{
EasyObject = EasyEve;
}
/// <summary>Get Character's wallets and balances</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWallets(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallets/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
}
}
| using ESISharp.Web;
namespace ESISharp.ESIPath.Character
{
/// <summary>Authenticated Character Wallet paths</summary>
public class CharacterWallet
{
protected ESIEve EasyObject;
internal CharacterWallet(ESIEve EasyEve)
{
EasyObject = EasyEve;
}
/// <summary>Get Character's wallets and balances</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWallets(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallets/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
/// <summary>Get Character's wallet journal</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWalletJounal(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallet/journal/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
/// <summary>Get Character's wallet transactions</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWalletTransactions(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallet/transactions/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
}
}
|
Clean up ToComment so it handles a few edge cases a bit better | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;
namespace StackExchange.DataExplorer.Models {
public partial class Query {
public string BodyWithoutComments {
get {
ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
return pq.ExecutionSql;
}
}
public void UpdateQueryBodyComment() {
StringBuilder buffer = new StringBuilder();
if (Name != null) {
buffer.Append(ToComment(Name));
buffer.Append("\n");
}
if (Description != null) {
buffer.Append(ToComment(Description));
buffer.Append("\n");
}
buffer.Append("\n");
buffer.Append(BodyWithoutComments);
QueryBody = buffer.ToString();
}
private string ToComment(string text) {
string rval = text.Replace("\r\n", "\n");
rval = "-- " + rval;
rval = rval.Replace("\n", "\n-- ");
if (rval.Contains("\n--")) {
rval = rval.Substring(0, rval.Length - 3);
}
return rval;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;
namespace StackExchange.DataExplorer.Models {
public partial class Query {
public string BodyWithoutComments {
get {
ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
return pq.ExecutionSql;
}
}
public void UpdateQueryBodyComment() {
StringBuilder buffer = new StringBuilder();
if (Name != null) {
buffer.Append(ToComment(Name));
buffer.Append("\n");
}
if (Description != null) {
buffer.Append(ToComment(Description));
buffer.Append("\n");
}
buffer.Append("\n");
buffer.Append(BodyWithoutComments);
QueryBody = buffer.ToString();
}
private string ToComment(string text) {
if (string.IsNullOrEmpty(text)) return "";
if (text != null) text = text.Trim();
string rval = text.Replace("\r\n", "\n");
rval = "-- " + rval;
rval = rval.Replace("\n", "\n-- ");
return rval;
}
}
} |
Add new test case for Range.Ints() | namespace RangeIt.Tests.Ranges
{
using FluentAssertions;
using RangeIt.Ranges;
using Xunit;
[Collection("Range.Ints.Tests")]
public class Range_Ints_Tests
{
[Fact]
public void Test_Range_Ints()
{
var range = Range.Ints(10);
range.Should().NotBeNull()
.And.NotBeEmpty()
.And.HaveCount(10)
.And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
[Fact]
public void Test_Range_Ints_WithZeroCount()
{
var range = Range.Ints(0);
range.Should().NotBeNull().And.BeEmpty();
}
[Fact]
public void Test_Range_Ints_WithStartValue()
{
var range = Range.Ints(5, 10);
range.Should().NotBeNull()
.And.NotBeEmpty()
.And.HaveCount(10)
.And.ContainInOrder(5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
}
}
}
| namespace RangeIt.Tests.Ranges
{
using FluentAssertions;
using RangeIt.Ranges;
using Xunit;
[Collection("Range.Ints.Tests")]
public class Range_Ints_Tests
{
[Fact]
public void Test_Range_Ints()
{
var range = Range.Ints(10);
range.Should().NotBeNull()
.And.NotBeEmpty()
.And.HaveCount(10)
.And.ContainInOrder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
[Fact]
public void Test_Range_Ints_WithZeroCount()
{
var range = Range.Ints(0);
range.Should().NotBeNull().And.BeEmpty();
}
[Fact]
public void Test_Range_Ints_WithStartValue()
{
var range = Range.Ints(5, 10);
range.Should().NotBeNull()
.And.NotBeEmpty()
.And.HaveCount(10)
.And.ContainInOrder(5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
}
[Fact]
public void Test_Range_Ints_WithStartValue_WithZeroCount()
{
var range = Range.Ints(5, 0);
range.Should().NotBeNull().And.BeEmpty();
}
}
}
|
Add last disposed drawable to global statistics | // 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 System.Threading.Tasks;
namespace osu.Framework.Allocation
{
/// <summary>
/// A queue which batches object disposal on threadpool threads.
/// </summary>
internal static class AsyncDisposalQueue
{
private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();
private static Task runTask;
public static void Enqueue(IDisposable disposable)
{
lock (disposal_queue)
disposal_queue.Enqueue(disposable);
if (runTask?.Status < TaskStatus.Running)
return;
runTask = Task.Run(() =>
{
lock (disposal_queue)
{
while (disposal_queue.Count > 0)
disposal_queue.Dequeue().Dispose();
}
});
}
}
}
| // 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 System.Threading.Tasks;
using osu.Framework.Statistics;
namespace osu.Framework.Allocation
{
/// <summary>
/// A queue which batches object disposal on threadpool threads.
/// </summary>
internal static class AsyncDisposalQueue
{
private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal");
private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>();
private static Task runTask;
public static void Enqueue(IDisposable disposable)
{
lock (disposal_queue)
disposal_queue.Enqueue(disposable);
if (runTask?.Status < TaskStatus.Running)
return;
runTask = Task.Run(() =>
{
lock (disposal_queue)
{
while (disposal_queue.Count > 0)
{
var toDispose = disposal_queue.Dequeue();
toDispose.Dispose();
last_disposal.Value = toDispose.ToString();
}
}
});
}
}
}
|
Remove AlwaysPresent (not actually required) | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverSounds : CompositeDrawable
{
private SampleChannel sampleHover;
protected readonly HoverSampleSet SampleSet;
public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
{
SampleSet = sampleSet;
RelativeSizeAxes = Axes.Both;
AlwaysPresent = true;
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
}
public enum HoverSampleSet
{
[Description("")]
Loud,
[Description("-soft")]
Normal,
[Description("-softer")]
Soft
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverSounds : CompositeDrawable
{
private SampleChannel sampleHover;
protected readonly HoverSampleSet SampleSet;
public HoverSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal)
{
SampleSet = sampleSet;
RelativeSizeAxes = Axes.Both;
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
}
public enum HoverSampleSet
{
[Description("")]
Loud,
[Description("-soft")]
Normal,
[Description("-softer")]
Soft
}
}
|
Refactor to use card extensions | using Hearts.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Hearts.Scoring;
namespace Hearts.Extensions
{
public static class CardListExtensions
{
public static void Log(this IEnumerable<Card> self, string name)
{
int padToLength = 38;
Logging.Log.ToBlue();
Console.Write(" " + name.PadLeft(Logging.Log.Options.NamePad) + " ");
foreach (var suit in new List<Suit> { Suit.Hearts, Suit.Spades, Suit.Diamonds, Suit.Clubs })
{
var cardsOfSuit = self.Where(i => i.Suit == suit);
foreach (var card in cardsOfSuit.OrderBy(i => i.Kind))
{
Logging.Log.Card(card);
Console.Write(" ");
}
Console.Write(new string(' ', padToLength - cardsOfSuit.Count() * 3));
}
Logging.Log.NewLine();
}
public static int Score(this IEnumerable<Card> self)
{
return new ScoreEvaluator().CalculateScore(self);
}
public static string ToDebugString(this IEnumerable<Card> self)
{
return string.Join(",", self);
}
}
} | using Hearts.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Hearts.Scoring;
namespace Hearts.Extensions
{
public static class CardListExtensions
{
public static void Log(this IEnumerable<Card> self, string name)
{
int padToLength = 38;
Logging.Log.ToBlue();
Console.Write(" " + name.PadLeft(Logging.Log.Options.NamePad) + " ");
foreach (var suit in new List<Suit> { Suit.Hearts, Suit.Spades, Suit.Diamonds, Suit.Clubs })
{
var cardsOfSuit = self.OfSuit(suit);
foreach (var card in cardsOfSuit.Ascending())
{
Logging.Log.Card(card);
Console.Write(" ");
}
Console.Write(new string(' ', padToLength - cardsOfSuit.Count() * 3));
}
Logging.Log.NewLine();
}
public static int Score(this IEnumerable<Card> self)
{
return new ScoreEvaluator().CalculateScore(self);
}
public static string ToDebugString(this IEnumerable<Card> self)
{
return string.Join(",", self);
}
}
} |
Use `TestCase` attribute in parser tests. | using NUnit.Framework;
using Pash.ParserIntrinsics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParserTests
{
[TestFixture]
public class ParserTests
{
[Test]
public void IfTest()
{
var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {}");
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
[Test]
public void IfElseTest()
{
var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} else {}");
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
[Test]
public void IfElseIfTest()
{
var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif ($true) {} ");
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
[Test, Explicit("bug")]
public void IfElseIfElseTest()
{
var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif {$true) {} else {}");
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
[Test, Explicit("bug")]
public void IfElseifElseTest()
{
var parseTree = PowerShellGrammar.Parser.Parse(@"if ($true) {} elseif ($true) {} elseif ($true) else {}");
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
}
}
| using NUnit.Framework;
using Pash.ParserIntrinsics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParserTests
{
[TestFixture]
public class ParserTests
{
[Test]
[TestCase(@"if ($true) {} else {}")]
[TestCase(@"if ($true) {} elseif ($true) {} ")]
[TestCase(@"if ($true) {} elseif {$true) {} else {}", Explicit = true)]
[TestCase(@"if ($true) {} elseif ($true) {} elseif ($true) else {}", Explicit = true)]
public void IfElseSyntax(string input)
{
var parseTree = PowerShellGrammar.Parser.Parse(input);
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
}
}
|
Fix icons on session details page | @page "{id}"
@model SessionModel
<ol class="breadcrumb">
<li><a asp-page="/Index">Agenda</a></li>
<li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li>
<li class="active">@Model.Session.Title</li>
</ol>
<h1>@Model.Session.Title</h1>
<span class="label label-default">@Model.Session.Track?.Name</span>
@foreach (var speaker in Model.Session.Speakers)
{
<em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em>
}
<p>@Html.Raw(Model.Session.Abstract)</p>
<form method="post">
<input type="hidden" name="sessionId" value="@Model.Session.ID" />
<p>
<a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a>
@if (Model.IsInPersonalAgenda)
{
<button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button>
}
else
{
<button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button>
}
</p>
</form> | @page "{id}"
@model SessionModel
<ol class="breadcrumb">
<li><a asp-page="/Index">Agenda</a></li>
<li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li>
<li class="active">@Model.Session.Title</li>
</ol>
<h1>@Model.Session.Title</h1>
<span class="label label-default">@Model.Session.Track?.Name</span>
@foreach (var speaker in Model.Session.Speakers)
{
<em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em>
}
<p>@Html.Raw(Model.Session.Abstract)</p>
<form method="post">
<input type="hidden" name="sessionId" value="@Model.Session.ID" />
<p>
<a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a>
@if (Model.IsInPersonalAgenda)
{
<button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-star" aria-hidden="true"></span></button>
}
else
{
<button authz="true" type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span></button>
}
</p>
</form> |
Rename test shim method name | using System.Linq;
using System.Reflection;
using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/*
* Howdy,
*
* This is NSpec's DebuggerShim. It will allow you to use TestDriven.Net or Resharper's test runner to run
* NSpec tests that are in the same Assembly as this class.
*
* It's DEFINITELY worth trying specwatchr (http://nspec.org/continuoustesting). Specwatchr automatically
* runs tests for you.
*
* If you ever want to debug a test when using Specwatchr, simply put the following line in your test:
*
* System.Diagnostics.Debugger.Launch()
*
* Visual Studio will detect this and will give you a window which you can use to attach a debugger.
*/
[TestClass]
public class DebuggerShim
{
[TestMethod]
public void debug()
{
var tagOrClassName = "class_or_tag_you_want_to_debug";
var types = GetType().Assembly.GetTypes();
// OR
// var types = new Type[]{typeof(Some_Type_Containg_some_Specs)};
var finder = new SpecFinder(types, "");
var builder = new ContextBuilder(finder, new Tags().Parse(tagOrClassName), new DefaultConventions());
var runner = new ContextRunner(builder, new ConsoleFormatter(), false);
var results = runner.Run(builder.Contexts().Build());
//assert that there aren't any failures
Assert.AreEqual(0, results.Failures().Count());
}
}
| using System.Linq;
using System.Reflection;
using NSpec;
using NSpec.Domain;
using NSpec.Domain.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/*
* Howdy,
*
* This is NSpec's DebuggerShim. It will allow you to use TestDriven.Net or Resharper's test runner to run
* NSpec tests that are in the same Assembly as this class.
*
* It's DEFINITELY worth trying specwatchr (http://nspec.org/continuoustesting). Specwatchr automatically
* runs tests for you.
*
* If you ever want to debug a test when using Specwatchr, simply put the following line in your test:
*
* System.Diagnostics.Debugger.Launch()
*
* Visual Studio will detect this and will give you a window which you can use to attach a debugger.
*/
[TestClass]
public class DebuggerShim
{
[TestMethod]
public void NSpec_Tests()
{
var tagOrClassName = "class_or_tag_you_want_to_debug";
var types = GetType().Assembly.GetTypes();
// OR
// var types = new Type[]{typeof(Some_Type_Containg_some_Specs)};
var finder = new SpecFinder(types, "");
var builder = new ContextBuilder(finder, new Tags().Parse(tagOrClassName), new DefaultConventions());
var runner = new ContextRunner(builder, new ConsoleFormatter(), false);
var results = runner.Run(builder.Contexts().Build());
//assert that there aren't any failures
Assert.AreEqual(0, results.Failures().Count());
}
}
|
Update EmbeddedFileProvider to reflect project name change | using System;
using System.Reflection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Swashbuckle.AspNetCore.SwaggerUi;
namespace Microsoft.AspNetCore.Builder
{
public static class SwaggerUiBuilderExtensions
{
public static IApplicationBuilder UseSwaggerUi(
this IApplicationBuilder app,
Action<SwaggerUiOptions> setupAction = null)
{
var options = new SwaggerUiOptions();
setupAction?.Invoke(options);
// Enable redirect from basePath to indexPath
app.UseMiddleware<RedirectMiddleware>(options.BaseRoute, options.IndexPath);
// Serve indexPath via middleware
app.UseMiddleware<SwaggerUiMiddleware>(options);
// Serve everything else via static file server
var fileServerOptions = new FileServerOptions
{
RequestPath = $"/{options.BaseRoute}",
EnableDefaultFiles = false,
FileProvider = new EmbeddedFileProvider(typeof(SwaggerUiBuilderExtensions).GetTypeInfo().Assembly,
"Swashbuckle.SwaggerUi.bower_components.swagger_ui.dist")
};
fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
app.UseFileServer(fileServerOptions);
return app;
}
}
}
| using System;
using System.Reflection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Swashbuckle.AspNetCore.SwaggerUi;
namespace Microsoft.AspNetCore.Builder
{
public static class SwaggerUiBuilderExtensions
{
public static IApplicationBuilder UseSwaggerUi(
this IApplicationBuilder app,
Action<SwaggerUiOptions> setupAction = null)
{
var options = new SwaggerUiOptions();
setupAction?.Invoke(options);
// Enable redirect from basePath to indexPath
app.UseMiddleware<RedirectMiddleware>(options.BaseRoute, options.IndexPath);
// Serve indexPath via middleware
app.UseMiddleware<SwaggerUiMiddleware>(options);
// Serve everything else via static file server
var fileServerOptions = new FileServerOptions
{
RequestPath = $"/{options.BaseRoute}",
EnableDefaultFiles = false,
FileProvider = new EmbeddedFileProvider(typeof(SwaggerUiBuilderExtensions).GetTypeInfo().Assembly,
"Swashbuckle.AspNetCore.SwaggerUi.bower_components.swagger_ui.dist")
};
fileServerOptions.StaticFileOptions.ContentTypeProvider = new FileExtensionContentTypeProvider();
app.UseFileServer(fileServerOptions);
return app;
}
}
}
|
Drop unused streaming write option. | #region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Feature.StreamingStorage
{
[Flags]
public enum StreamingWriteOptions
{
None,
/// <summary>
/// We'll compress data if possible.
/// </summary>
CompressIfPossible = 0x01,
/// <summary>
/// Be default we are optimizing for small read operations. Use this as a hint
/// </summary>
OptimizeForLargeWrites = 0x02
}
} | #region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
namespace Lokad.Cqrs.Feature.StreamingStorage
{
[Flags]
public enum StreamingWriteOptions
{
None,
/// <summary>
/// We'll compress data if possible.
/// </summary>
CompressIfPossible = 0x01,
}
} |
Improve naming of tests to clearly indicate the feature to be tested | #region Copyright and license
// // <copyright file="NullTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// // </license>
#endregion
namespace Delizious.Filtering
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class NullTests
{
[TestMethod]
public void Succeed__When_Value_Is_Null()
{
Assert.IsTrue(Match.Null<GenericParameterHelper>().Matches(null));
}
[TestMethod]
public void Fail__When_Value_Is_An_Instance()
{
Assert.IsFalse(Match.Null<GenericParameterHelper>().Matches(new GenericParameterHelper()));
}
}
}
| #region Copyright and license
// // <copyright file="NullTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
// // </license>
#endregion
namespace Delizious.Filtering
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class NullTests
{
[TestMethod]
public void Match_Succeeds_When_Value_To_Match_Is_Null()
{
Assert.IsTrue(Match.Null<GenericParameterHelper>().Matches(null));
}
[TestMethod]
public void Match_Fails_When_Value_To_Match_Is_An_Instance()
{
Assert.IsFalse(Match.Null<GenericParameterHelper>().Matches(new GenericParameterHelper()));
}
}
}
|
Update the extension method test case | using System;
public class Herp
{
public Herp(int X)
{
this.X = X;
}
public int X { get; private set; }
}
public static class HerpExtensions
{
public static void PrintX(this Herp Value)
{
Console.WriteLine(Value.X);
}
}
public static class Program
{
public static void Main()
{
var herp = new Herp(20);
herp.PrintX();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
public class Herp
{
public Herp(int X)
{
this.X = X;
}
public int X { get; private set; }
}
public static class HerpExtensions
{
public static void PrintX(this Herp Value)
{
Console.WriteLine(Value.X);
}
}
public static class Program
{
public static void Main()
{
var herp = new Herp(20);
herp.PrintX();
var items = new List<int>();
items.Add(10);
items.Add(20);
items.Add(30);
// Note that ToArray<int> is actually a generic extension method:
// Enumerable.ToArray<T>.
foreach (var x in items.ToArray<int>())
{
Console.WriteLine(x);
}
}
}
|
Set dialog flag as Router.NavigationStack.CollectionChanged observable in blocked by _isClosing | using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogVisible;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogVisible = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogVisible).Subscribe(x =>
{
if (!x)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogVisible
{
get => _isDialogVisible;
set => this.RaiseAndSetIfChanged(ref _isDialogVisible, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
Router.NavigationStack.Clear();
}
_isClosing = false;
}
}
}
} | using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogVisible;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogVisible = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogVisible).Subscribe(x =>
{
if (!x)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogVisible
{
get => _isDialogVisible;
set => this.RaiseAndSetIfChanged(ref _isDialogVisible, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
Router.NavigationStack.Clear();
IsDialogVisible = false;
}
_isClosing = false;
}
}
}
} |
Fix compilation error on kh.tools.imgz | using kh.kh2;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Xe.Tools;
using Xe.Tools.Wpf;
namespace kh.tools.imgz.Models
{
public class ImageModel : BaseNotifyPropertyChanged
{
private Imgd imgd;
public ImageModel(Imgd imgd)
{
Imgd = imgd;
}
public Imgd Imgd
{
get => imgd;
set => LoadImgd(imgd = value);
}
public BitmapSource Image { get; set; }
public string DisplayName => $"{Image.PixelWidth}x{Image.PixelHeight}";
private void LoadImgd(Imgd imgd)
{
LoadImage(imgd.GetBitmap(), imgd.Size.Width, imgd.Size.Height);
}
private void LoadImage(byte[] data, int width, int height)
{
Image = BitmapSource.Create(width, height, 96.0, 96.0, PixelFormats.Bgra32, null, data, width * 4);
OnPropertyChanged(nameof(Image));
}
}
}
| using kh.Imaging;
using kh.kh2;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Xe.Tools;
using Xe.Tools.Wpf;
namespace kh.tools.imgz.Models
{
public class ImageModel : BaseNotifyPropertyChanged
{
private Imgd imgd;
public ImageModel(Imgd imgd)
{
Imgd = imgd;
}
public Imgd Imgd
{
get => imgd;
set => LoadImgd(imgd = value);
}
public BitmapSource Image { get; set; }
public string DisplayName => $"{Image.PixelWidth}x{Image.PixelHeight}";
private void LoadImgd(Imgd imgd)
{
LoadImage(imgd);
}
private void LoadImage(IImageRead imageRead)
{
var size = imageRead.Size;
var data = imageRead.ToBgra32();
Image = BitmapSource.Create(size.Width, size.Height, 96.0, 96.0, PixelFormats.Bgra32, null, data, size.Width * 4);
OnPropertyChanged(nameof(Image));
}
}
}
|
Print to STDOUT - 2> is broken on Mono/OS X | using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
| using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
|
Increase PERFECT from 320 to 350 score | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class ManiaJudgement : Judgement
{
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Meh:
return 50;
case HitResult.Ok:
return 100;
case HitResult.Good:
return 200;
case HitResult.Great:
return 300;
case HitResult.Perfect:
return 320;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class ManiaJudgement : Judgement
{
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Meh:
return 50;
case HitResult.Ok:
return 100;
case HitResult.Good:
return 200;
case HitResult.Great:
return 300;
case HitResult.Perfect:
return 350;
}
}
}
}
|
Refactor seq for empty vectors | namespace ClojSharp.Core.Forms
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Language;
public class Seq : BaseUnaryForm
{
public override object EvaluateForm(IContext context, IList<object> arguments)
{
var arg = arguments[0];
if (arg == null)
return null;
if (arg is Vector)
return List.FromEnumerable(((Vector)arg).Elements);
if (arg is EmptyList)
return null;
if (arg is List)
return arg;
return EnumerableSeq.MakeSeq((IEnumerable)arg);
}
}
}
| namespace ClojSharp.Core.Forms
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClojSharp.Core.Language;
public class Seq : BaseUnaryForm
{
public override object EvaluateForm(IContext context, IList<object> arguments)
{
var arg = arguments[0];
if (arg == null)
return null;
if (arg is Vector)
{
var vector = (Vector)arg;
if (vector.Elements == null || vector.Elements.Count == 0)
return null;
return EnumerableSeq.MakeSeq(vector.Elements);
}
if (arg is EmptyList)
return null;
if (arg is List)
return arg;
return EnumerableSeq.MakeSeq((IEnumerable)arg);
}
}
}
|
Add docs about limitation of this option | // 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.Collections.Generic;
using System.Linq;
namespace Microsoft.AspNetCore.Razor.Language
{
public abstract class RazorParserOptions
{
public static RazorParserOptions Create(IEnumerable<DirectiveDescriptor> directives, bool designTime)
{
if (directives == null)
{
throw new ArgumentNullException(nameof(directives));
}
return new DefaultRazorParserOptions(directives.ToArray(), designTime, parseOnlyLeadingDirectives: false);
}
public static RazorParserOptions Create(IEnumerable<DirectiveDescriptor> directives, bool designTime, bool parseOnlyLeadingDirectives)
{
if (directives == null)
{
throw new ArgumentNullException(nameof(directives));
}
return new DefaultRazorParserOptions(directives.ToArray(), designTime, parseOnlyLeadingDirectives);
}
public static RazorParserOptions CreateDefault()
{
return new DefaultRazorParserOptions(Array.Empty<DirectiveDescriptor>(), designTime: false, parseOnlyLeadingDirectives: false);
}
public abstract bool DesignTime { get; }
public abstract IReadOnlyCollection<DirectiveDescriptor> Directives { get; }
public abstract bool ParseOnlyLeadingDirectives { get; }
}
}
| // 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.Collections.Generic;
using System.Linq;
namespace Microsoft.AspNetCore.Razor.Language
{
public abstract class RazorParserOptions
{
public static RazorParserOptions Create(IEnumerable<DirectiveDescriptor> directives, bool designTime)
{
if (directives == null)
{
throw new ArgumentNullException(nameof(directives));
}
return new DefaultRazorParserOptions(directives.ToArray(), designTime, parseOnlyLeadingDirectives: false);
}
public static RazorParserOptions Create(IEnumerable<DirectiveDescriptor> directives, bool designTime, bool parseOnlyLeadingDirectives)
{
if (directives == null)
{
throw new ArgumentNullException(nameof(directives));
}
return new DefaultRazorParserOptions(directives.ToArray(), designTime, parseOnlyLeadingDirectives);
}
public static RazorParserOptions CreateDefault()
{
return new DefaultRazorParserOptions(Array.Empty<DirectiveDescriptor>(), designTime: false, parseOnlyLeadingDirectives: false);
}
public abstract bool DesignTime { get; }
public abstract IReadOnlyCollection<DirectiveDescriptor> Directives { get; }
/// <summary>
/// Gets a value which indicates whether the parser will parse only the leading directives. If <c>true</c>
/// the parser will halt at the first HTML content or C# code block. If <c>false</c> the whole document is parsed.
/// </summary>
/// <remarks>
/// Currently setting this option to <c>true</c> will result in only the first line of directives being parsed.
/// In a future release this may be updated to include all leading directive content.
/// </remarks>
public abstract bool ParseOnlyLeadingDirectives { get; }
}
}
|
Use ValidationHelper for email regex | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using Abp.Auditing;
using Abp.Authorization.Users;
using Abp.Extensions;
namespace AbpCompanyName.AbpProjectName.Web.Models.Account
{
public class RegisterViewModel : IValidatableObject
{
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
[DisableAuditing]
public string Password { get; set; }
public bool IsExternalLogin { get; set; }
public string ExternalLoginAuthSchema { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!UserName.IsNullOrEmpty())
{
var emailRegex = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
if (!UserName.Equals(EmailAddress) && emailRegex.IsMatch(UserName))
{
yield return new ValidationResult("Username cannot be an email address unless it's the same as your email address!");
}
}
}
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Auditing;
using Abp.Authorization.Users;
using Abp.Extensions;
using AbpCompanyName.AbpProjectName.Validation;
namespace AbpCompanyName.AbpProjectName.Web.Models.Account
{
public class RegisterViewModel : IValidatableObject
{
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
[DisableAuditing]
public string Password { get; set; }
public bool IsExternalLogin { get; set; }
public string ExternalLoginAuthSchema { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!UserName.IsNullOrEmpty())
{
if (!UserName.Equals(EmailAddress) && ValidationHelper.IsEmail(UserName))
{
yield return new ValidationResult("Username cannot be an email address unless it's the same as your email address!");
}
}
}
}
}
|
Hide titlebar in Android visual test activity | // 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 Android.App;
using Android.Content.PM;
using osu.Framework.Android;
namespace osu.Framework.Tests.Android
{
[Activity(MainLauncher = true, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, Theme = "@android:style/Theme.NoTitleBar")]
public class TestGameActivity : AndroidGameActivity
{
protected override Game CreateGame()
=> new VisualTestGame();
}
}
| // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Framework.Tests.Android
{
[Activity(MainLauncher = true, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, Theme = "@android:style/Theme.NoTitleBar")]
public class TestGameActivity : AndroidGameActivity
{
protected override Game CreateGame()
=> new VisualTestGame();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
}
}
}
|
Add stubs for APFT controller | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace BatteryCommander.Web.Controllers
{
[Authorize]
public class APFTController : Controller
{
private readonly Database db;
public APFTController(Database db)
{
this.db = db;
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[Authorize]
public class APFTController : Controller
{
private readonly Database db;
public APFTController(Database db)
{
this.db = db;
}
public async Task<IActionResult> List()
{
throw new NotImplementedException();
}
public async Task<IActionResult> Details(int id)
{
throw new NotImplementedException();
}
public IActionResult New()
{
throw new NotImplementedException();
}
public async Task<IActionResult> Edit(int id)
{
throw new NotImplementedException();
}
public async Task<IActionResult> Save(dynamic model)
{
// If EXISTS, Update
// Else, Create New
await db.SaveChangesAsync();
return RedirectToAction(nameof(Details), model.Id);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.