Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix to the last commit. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations;
using JetBrains.Util;
namespace AgentHeisenbug.Annotations {
#if DEBUG
[PsiComponent]
public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider {
[NotNull] private readonly FileSystemPath _path;
public HeisenbugDebugExternalAnnotationFileProvider() {
_path = FileSystemPath.Parse(Assembly.GetExecutingAssembly().Location)
.Combine("../../../#annotations");
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) {
if (assemblyName == null)
return Enumerable.Empty<FileSystemPath>();
var directoryForAssembly = _path.Combine(assemblyName.Name);
if (!directoryForAssembly.ExistsDirectory)
return Enumerable.Empty<FileSystemPath>();
return directoryForAssembly.GetDirectoryEntries("*.xml", true);
}
}
#endif
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations;
using JetBrains.Util;
namespace AgentHeisenbug.Annotations {
#if DEBUG
[PsiComponent]
public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider {
[NotNull] private readonly FileSystemPath _path;
public HeisenbugDebugExternalAnnotationFileProvider() {
_path = FileSystemPath.Parse(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).NotNull())
.Combine("../../../#annotations");
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) {
if (assemblyName == null)
return Enumerable.Empty<FileSystemPath>();
var directoryForAssembly = _path.Combine(assemblyName.Name);
if (!directoryForAssembly.ExistsDirectory)
return Enumerable.Empty<FileSystemPath>();
return directoryForAssembly.GetDirectoryEntries("*.xml", true);
}
}
#endif
}
|
Fix path too long bug | using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Audiotica.Core.Utils
{
public static class StringExtensions
{
public static string CleanForFileName(this string str, string invalidMessage)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
/*
* A filename cannot contain any of the following characters:
* \ / : * ? " < > |
*/
var name =
str.Replace("\\", string.Empty)
.Replace("/", string.Empty)
.Replace(":", " ")
.Replace("*", string.Empty)
.Replace("?", string.Empty)
.Replace("\"", "'")
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace("|", " ");
return string.IsNullOrEmpty(name) ? invalidMessage : name;
}
public static async Task<T> DeserializeAsync<T>(this string json)
{
return await Task.Factory.StartNew(
() =>
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch
{
return default(T);
}
}).ConfigureAwait(false);
}
public static string StripHtmlTags(this string str)
{
return HtmlRemoval.StripTagsRegex(str);
}
}
} | using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Audiotica.Core.Utils
{
public static class StringExtensions
{
public static string CleanForFileName(this string str, string invalidMessage)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
if (str.Length > 35)
{
str = str.Substring(0, 35);
}
/*
* A filename cannot contain any of the following characters:
* \ / : * ? " < > |
*/
var name =
str.Replace("\\", string.Empty)
.Replace("/", string.Empty)
.Replace(":", " ")
.Replace("*", string.Empty)
.Replace("?", string.Empty)
.Replace("\"", "'")
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace("|", " ");
return string.IsNullOrEmpty(name) ? invalidMessage : name;
}
public static async Task<T> DeserializeAsync<T>(this string json)
{
return await Task.Factory.StartNew(
() =>
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch
{
return default(T);
}
}).ConfigureAwait(false);
}
public static string StripHtmlTags(this string str)
{
return HtmlRemoval.StripTagsRegex(str);
}
}
} |
Remove tray icon on safe exit. | using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void CreateTrayMenu()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return;
var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));
var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");
if (favicon != null)
{
menu.Icon = new Icon(favicon);
menu.Visible = true;
}
}
}
}
| using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void CreateTrayMenu()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return;
var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));
var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");
if (favicon != null)
{
menu.Icon = new Icon(favicon);
menu.Visible = true;
}
ApplicationExit += delegate
{
menu.Visible = false;
menu.Dispose();
};
}
}
}
|
Comment out logging for debugging purposes | // 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.
#nullable disable
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
/// <summary>
/// Calculates the colour coefficient of taiko difficulty.
/// </summary>
public class Colour : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double StrainDecayBase => 0.4;
public Colour(Mod[] mods)
: base(mods)
{
}
protected override double StrainValueOf(DifficultyHitObject current)
{
TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
if (current != null && colour != null)
{
ColourEncoding[] payload = colour.Encoding.Payload;
string payloadDisplay = "";
for (int i = 0; i < payload.Length; ++i)
{
payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
}
System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
}
return difficulty;
}
}
}
| // 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.
#nullable disable
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
/// <summary>
/// Calculates the colour coefficient of taiko difficulty.
/// </summary>
public class Colour : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double StrainDecayBase => 0.4;
public Colour(Mod[] mods)
: base(mods)
{
}
protected override double StrainValueOf(DifficultyHitObject current)
{
TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
// if (current != null && colour != null)
// {
// ColourEncoding[] payload = colour.Encoding.Payload;
// string payloadDisplay = "";
// for (int i = 0; i < payload.Length; ++i)
// {
// payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
// }
// System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
// }
return difficulty;
}
}
}
|
Allow virtual SampleChannels to count towards 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.
namespace osu.Framework.Audio.Sample
{
/// <summary>
/// A <see cref="SampleChannel"/> which explicitly plays no audio.
/// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
/// </summary>
public sealed class SampleChannelVirtual : SampleChannel
{
public SampleChannelVirtual()
: base(new SampleVirtual(), _ => { })
{
}
public override bool Playing => false;
protected override void UpdateState()
{
// empty override to avoid affecting sample channel count in frame statistics
}
private class SampleVirtual : Sample
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Audio.Sample
{
/// <summary>
/// A <see cref="SampleChannel"/> which explicitly plays no audio.
/// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
/// </summary>
public sealed class SampleChannelVirtual : SampleChannel
{
public SampleChannelVirtual()
: base(new SampleVirtual(), _ => { })
{
}
public override bool Playing => false;
private class SampleVirtual : Sample
{
}
}
}
|
Fix problem with invalid whitespaces and lower characters in input license key code | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
string key = KeyInputField.text;
key = key.ToUpper().Trim();
_keyLicense = new KeyLicense
{
Key = KeyInputField.text
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
string key = KeyInputField.text;
key = key.ToUpper().Trim();
_keyLicense = new KeyLicense
{
Key = key
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} |
Order by filename ASC, so that detached versions appear always after the original photo, even if Reverse Order is used | /*
* FSpot.Query.OrderByTime.cs
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using System;
using FSpot.Utils;
namespace FSpot.Query {
public class OrderByTime : IQueryCondition, IOrderCondition
{
public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
public static OrderByTime OrderByTimeDesc = new OrderByTime (false);
bool asc;
public bool Asc {
get { return asc; }
}
public OrderByTime (bool asc)
{
this.asc = asc;
}
public string SqlClause ()
{
return String.Format (" time {0}, filename {0} ", asc ? "ASC" : "DESC");
}
}
}
| /*
* FSpot.Query.OrderByTime.cs
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using System;
using FSpot.Utils;
namespace FSpot.Query {
public class OrderByTime : IQueryCondition, IOrderCondition
{
public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
public static OrderByTime OrderByTimeDesc = new OrderByTime (false);
bool asc;
public bool Asc {
get { return asc; }
}
public OrderByTime (bool asc)
{
this.asc = asc;
}
public string SqlClause ()
{
// filenames must always appear in alphabetical order if times are the same
return String.Format (" time {0}, filename ASC ", asc ? "ASC" : "DESC");
}
}
}
|
Add some comments to the new PhotosDirectory field so users understand how it is used. | using System.Threading.Tasks;
namespace MetaMediaPlugin.Abstractions
{
public interface IMediaService
{
bool IsCameraAvailable { get; }
bool IsTakePhotoSupported { get; }
bool IsPickPhotoSupported { get; }
string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
Task<IMediaFile> PickPhotoAsync();
Task<IMediaFile> TakePhotoAsync();
}
} | using System.Threading.Tasks;
namespace MetaMediaPlugin.Abstractions
{
public interface IMediaService
{
bool IsCameraAvailable { get; }
bool IsTakePhotoSupported { get; }
bool IsPickPhotoSupported { get; }
/// <summary>
/// Specify the photo directory to use for your app.
/// In iOS, this has no effect.
/// In Android, this will be the name of the subdirectory within the shared photos directory.
/// </summary>
/// <value>The photos directory.</value>
string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
Task<IMediaFile> PickPhotoAsync();
Task<IMediaFile> TakePhotoAsync();
}
} |
Set verbosity to diagnostic on hosted build. | using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;
namespace StructuredLogViewer
{
public class HostedBuild
{
private string projectFilePath;
public HostedBuild(string projectFilePath)
{
this.projectFilePath = projectFilePath;
}
public Task<Build> BuildAndGetResult(BuildProgress progress)
{
var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
var loggerDll = typeof(StructuredLogger).Assembly.Location;
var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
progress.MSBuildCommandLine = commandLine;
StructuredLogger.SaveLogToDisk = false;
return System.Threading.Tasks.Task.Run(() =>
{
try
{
var result = MSBuildApp.Execute(commandLine);
return StructuredLogger.CurrentBuild;
}
catch (Exception ex)
{
var build = new Build();
build.Succeeded = false;
build.AddChild(new Message() { Text = "Exception occurred during build:" });
build.AddChild(new Error() { Text = ex.ToString() });
return build;
}
});
}
}
}
| using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;
namespace StructuredLogViewer
{
public class HostedBuild
{
private string projectFilePath;
public HostedBuild(string projectFilePath)
{
this.projectFilePath = projectFilePath;
}
public Task<Build> BuildAndGetResult(BuildProgress progress)
{
var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
var loggerDll = typeof(StructuredLogger).Assembly.Location;
var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /v:diag /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
progress.MSBuildCommandLine = commandLine;
StructuredLogger.SaveLogToDisk = false;
return System.Threading.Tasks.Task.Run(() =>
{
try
{
var result = MSBuildApp.Execute(commandLine);
return StructuredLogger.CurrentBuild;
}
catch (Exception ex)
{
var build = new Build();
build.Succeeded = false;
build.AddChild(new Message() { Text = "Exception occurred during build:" });
build.AddChild(new Error() { Text = ex.ToString() });
return build;
}
});
}
}
}
|
Fix bug that was preventing transation of some items. | namespace Grabacr07.KanColleWrapper.Translation
{
public static class ItemTranslationHelper
{
public static string TranslateItemName(string name)
{
string stripped = TranslationHelper.StripInvalidCharacters(name);
string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));
return (string.IsNullOrEmpty(translated) ? name : translated);
}
}
}
| namespace Grabacr07.KanColleWrapper.Translation
{
public static class ItemTranslationHelper
{
public static string TranslateItemName(string name)
{
string stripped = name;
string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));
return (string.IsNullOrEmpty(translated) ? name : translated);
}
}
}
|
Handle HttpException explicitly and include comments for workaround | using System;
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;
namespace Abp.Web.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
try
{
return HttpContext.Current?.Request.Url.AbsoluteUri;
}
catch (Exception ex)
{
Logger.Warn(ex.ToString(), ex);
return null;
}
}
}
public HttpRequestEntityChangeSetReasonProvider(
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
}
}
}
| using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;
namespace Abp.Web.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
try
{
return HttpContext.Current?.Request.Url.AbsoluteUri;
}
catch (HttpException ex)
{
/* Workaround:
* Accessing HttpContext.Request during Application_Start or Application_End will throw exception.
* This behavior is intentional from microsoft
* See https://stackoverflow.com/questions/2518057/request-is-not-available-in-this-context/23908099#comment2514887_2518066
*/
Logger.Warn("HttpContext.Request access when it is not suppose to", ex);
return null;
}
}
}
public HttpRequestEntityChangeSetReasonProvider(
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
}
}
}
|
Fix for gallio on non-windows systems | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;
namespace Bari.Plugins.Gallio.Tools
{
public class Gallio: DownloadablePackedExternalTool, IGallio
{
private readonly IFileSystemDirectory targetDir;
public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
: base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
@"bin\Gallio.Echo.exe", new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
{
this.targetDir = targetDir;
}
public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
{
List<string> ps = testAssemblies.Select(p => (string)p).ToList();
ps.Add("/report-type:Xml");
ps.Add("/report-directory:.");
ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
ps.Add("/report-name-format:test-report");
return Run(targetDir, ps.ToArray());
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;
namespace Bari.Plugins.Gallio.Tools
{
public class Gallio: DownloadablePackedExternalTool, IGallio
{
private readonly IFileSystemDirectory targetDir;
public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
: base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
Path.Combine("bin", "Gallio.Echo.exe"), new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
{
this.targetDir = targetDir;
}
public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
{
List<string> ps = testAssemblies.Select(p => (string)p).ToList();
ps.Add("/report-type:Xml");
ps.Add("/report-directory:.");
ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
ps.Add("/report-name-format:test-report");
return Run(targetDir, ps.ToArray());
}
}
} |
Add a couple of SharpDX Math related assertion helpers | using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
}
| using SharpDX;
using System;
using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
[Conditional("DEBUG")]
public static void AssertSamePosition(Vector3 v1, Vector3 v2) {
float distance = Vector3.Distance(v1, v2);
float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f;
float relativeDistance = distance / denominator;
Debug.Assert(relativeDistance < 1e-2, "not same position");
}
[Conditional("DEBUG")]
public static void AssertSameDirection(Vector3 v1, Vector3 v2) {
Vector3 u1 = Vector3.Normalize(v1);
Vector3 u2 = Vector3.Normalize(v2);
float dotProduct = Vector3.Dot(u1, u2);
Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction");
}
}
|
Convert .Text and .Primitive to interfaces | using System;
using System.Linq;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
internal static Random Rand { get; private set; }
public static PrimitiveRandomizer Primitive { get; private set; }
public static TextRandomizer Text { get; private set; }
static Incident()
{
Rand = new Random();
setupConcreteRandomizers();
}
public static int Seed
{
set
{
Rand = new Random(value);
}
}
}
}
| using System;
using System.Linq;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
internal static Random Rand { get; private set; }
public static IPrimitiveRandomizer Primitive { get; private set; }
public static ITextRandomizer Text { get; private set; }
static Incident()
{
Rand = new Random();
setupConcreteRandomizers();
}
public static int Seed
{
set
{
Rand = new Random(value);
}
}
}
}
|
Disable caching to force fetching of data when navigating backwards. Added api to clear db. | using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;
namespace topicr.Controllers.Api
{
[Produces("application/json")]
[Route("api/topics")]
public class TopicController : Controller
{
private readonly TopicContext _db;
public TopicController(TopicContext db)
{
_db = db;
}
[HttpGet]
public IActionResult GetTopics()
{
return Json(_db.Topics
.Select(p => new
{
p.Id,
p.Title,
p.Description
})
.ToList());
}
[HttpPost]
[Route("new")]
public IActionResult PostTopic(Topic topic)
{
_db.Topics.Add(topic);
_db.SaveChanges();
return Ok();
}
}
}
| using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;
namespace topicr.Controllers.Api
{
[Produces("application/json")]
[Route("api/topics")]
public class TopicController : Controller
{
private readonly TopicContext _db;
public TopicController(TopicContext db)
{
_db = db;
}
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult GetTopics()
{
return Json(_db.Topics
.Select(p => new
{
p.Id,
p.Title,
p.Description
})
.ToList());
}
[HttpPost]
[Route("new")]
public IActionResult PostTopic(Topic topic)
{
_db.Topics.Add(topic);
_db.SaveChanges();
return Ok();
}
[HttpGet]
[Route("clear")]
public IActionResult ClearTopics()
{
foreach (var topic in _db.Topics)
{
_db.Topics.Remove(topic);
}
_db.SaveChanges();
return Ok();
}
}
}
|
Update example implementation for Bob exercise | public static class Bob
{
public static string Response(string statement)
{
if (IsSilence(statement))
return "Fine. Be that way!";
if (IsYelling(statement))
return "Whoa, chill out!";
if (IsQuestion(statement))
return "Sure.";
return "Whatever.";
}
private static bool IsSilence (string statement)
{
return statement.Trim() == "";
}
private static bool IsYelling (string statement)
{
return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
}
private static bool IsQuestion (string statement)
{
return statement.Trim().EndsWith("?");
}
} | public static class Bob
{
public static string Response(string statement)
{
if (IsSilence(statement))
return "Fine. Be that way!";
if (IsYelling(statement) && IsQuestion(statement))
return "Calm down, I know what I'm doing!";
if (IsYelling(statement))
return "Whoa, chill out!";
if (IsQuestion(statement))
return "Sure.";
return "Whatever.";
}
private static bool IsSilence (string statement)
{
return statement.Trim() == "";
}
private static bool IsYelling (string statement)
{
return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
}
private static bool IsQuestion (string statement)
{
return statement.Trim().EndsWith("?");
}
} |
Make the guard class internal | using System;
namespace PalmDB
{
/// <summary>
/// Typical guard class that contains methods to validate method arguments.
/// </summary>
public static class Guard
{
/// <summary>
/// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
/// </summary>
/// <param name="argument">The argument to check for null.</param>
/// <param name="name">The name of the argument.</param>
public static void NotNull(object argument, string name)
{
if (argument == null)
throw new ArgumentNullException(name);
}
/// <summary>
/// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
/// </summary>
/// <param name="argument">The argument.</param>
/// <param name="name">The name.</param>
public static void NotNegative(int argument, string name)
{
if (argument < 0)
throw new ArgumentException($"{name} cannot be less than 0.", name);
}
}
} | using System;
namespace PalmDB
{
/// <summary>
/// Typical guard class that contains methods to validate method arguments.
/// </summary>
internal static class Guard
{
/// <summary>
/// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
/// </summary>
/// <param name="argument">The argument to check for null.</param>
/// <param name="name">The name of the argument.</param>
public static void NotNull(object argument, string name)
{
if (argument == null)
throw new ArgumentNullException(name);
}
/// <summary>
/// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
/// </summary>
/// <param name="argument">The argument.</param>
/// <param name="name">The name.</param>
public static void NotNegative(int argument, string name)
{
if (argument < 0)
throw new ArgumentException($"{name} cannot be less than 0.", name);
}
}
} |
Fix (again) syntax issue with using static | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;
using static NBi.Core.ResultSet.ResultSetBuilder;
namespace NBi.Xml.Items.ResultSet
{
public class ResultSetXml : BaseItem
{
[XmlElement("row")]
public List<RowXml> _rows { get; set; }
public IList<IRow> Rows
{
get { return _rows.Cast<IRow>().ToList(); }
}
public IList<string> Columns
{
get
{
if (_rows.Count == 0)
return new List<string>();
var names = new List<string>();
var row = _rows[0];
foreach (var cell in row.Cells)
{
if (!string.IsNullOrEmpty(cell.ColumnName))
names.Add(cell.ColumnName);
else
names.Add(string.Empty);
}
return names;
}
}
[XmlIgnore]
public Content Content
{
get { return new Content(Rows, Columns); }
}
[XmlAttribute("file")]
public string File { get; set; }
public string GetFile()
{
var file = string.Empty;
if (Path.IsPathRooted(File))
file = File;
else
file = Settings.BasePath + File;
return file;
}
public ResultSetXml()
{
_rows = new List<RowXml>();
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;
namespace NBi.Xml.Items.ResultSet
{
public class ResultSetXml : BaseItem
{
[XmlElement("row")]
public List<RowXml> _rows { get; set; }
public IList<IRow> Rows
{
get { return _rows.Cast<IRow>().ToList(); }
}
public IList<string> Columns
{
get
{
if (_rows.Count == 0)
return new List<string>();
var names = new List<string>();
var row = _rows[0];
foreach (var cell in row.Cells)
{
if (!string.IsNullOrEmpty(cell.ColumnName))
names.Add(cell.ColumnName);
else
names.Add(string.Empty);
}
return names;
}
}
[XmlIgnore]
public ResultSetBuilder.Content Content
{
get { return new ResultSetBuilder.Content(Rows, Columns); }
}
[XmlAttribute("file")]
public string File { get; set; }
public string GetFile()
{
var file = string.Empty;
if (Path.IsPathRooted(File))
file = File;
else
file = Settings.BasePath + File;
return file;
}
public ResultSetXml()
{
_rows = new List<RowXml>();
}
}
}
|
Add a 4th board cell status "Miss" to show that the user shoot to a blank spot. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FightFleet
{
public enum BoardCellStatus
{
Blank = 0,
Ship = 1,
Hit = 2
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FightFleet
{
public enum BoardCellStatus
{
Blank = 0,
Ship = 1,
Hit = 2,
Miss = 3
}
}
|
Fix bug in assembly file versioning ("*" was included in file version string) | using System.Reflection;
using JetBrains.ActionManagement;
using JetBrains.Application.PluginSupport;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Reformatting Utilities")]
[assembly:
AssemblyDescription(
"A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: AssemblyCompany("Øystein Krog")]
[assembly: AssemblyProduct("ReformatUtils")]
[assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.*")]
[assembly: AssemblyFileVersion("1.3.0.*")]
// The following information is displayed by ReSharper in the Plugins dialog
[assembly: PluginTitle("Reformatting Utilities")]
[assembly:
PluginDescription(
"A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: PluginVendor("Øystein Krog")] | using System.Reflection;
using JetBrains.ActionManagement;
using JetBrains.Application.PluginSupport;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Reformatting Utilities")]
[assembly:
AssemblyDescription(
"A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: AssemblyCompany("Øystein Krog")]
[assembly: AssemblyProduct("ReformatUtils")]
[assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.*")]
// The following information is displayed by ReSharper in the Plugins dialog
[assembly: PluginTitle("Reformatting Utilities")]
[assembly:
PluginDescription(
"A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: PluginVendor("Øystein Krog")] |
Reset protagonist balance to 0 | using System;
class Protagonist {
private static Protagonist INSTANCE;
private static int MAX_MONEY = 99;
private int balance;
public int Balance {
get { return balance; }
}
private Inventory inventory;
public Inventory Inventory {
get { return inventory; }
}
private Outfit outfit;
private Protagonist() {
balance = 99;
outfit = new Outfit();
inventory = new Inventory();
}
public static Protagonist GetInstance() {
if (INSTANCE == null) {
INSTANCE = new Protagonist();
}
return INSTANCE;
}
public bool modifyBalance(int difference) {
if (difference + balance < 0) {
return false;
}
balance = Math.Min(balance + difference, MAX_MONEY);
return true;
}
public bool CanPurchase(int price) {
return (price >= 0) && balance - price >= 0;
}
}
| using System;
class Protagonist {
private static Protagonist INSTANCE;
private static int MAX_MONEY = 99;
private int balance;
public int Balance {
get { return balance; }
}
private Inventory inventory;
public Inventory Inventory {
get { return inventory; }
}
private Outfit outfit;
private Protagonist() {
balance = 0;
outfit = new Outfit();
inventory = new Inventory();
}
public static Protagonist GetInstance() {
if (INSTANCE == null) {
INSTANCE = new Protagonist();
}
return INSTANCE;
}
public bool modifyBalance(int difference) {
if (difference + balance < 0) {
return false;
}
balance = Math.Min(balance + difference, MAX_MONEY);
return true;
}
public bool CanPurchase(int price) {
return (price >= 0) && balance - price >= 0;
}
}
|
Set window title for authentication | using System;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class AuthenticationWindow : BaseWindow
{
[SerializeField] private AuthenticationView authView;
[MenuItem("GitHub/Authenticate")]
public static void Launch()
{
Open();
}
public static IView Open(Action<bool> onClose = null)
{
AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
if (onClose != null)
authWindow.OnClose += onClose;
authWindow.minSize = new Vector2(290, 290);
authWindow.Show();
return authWindow;
}
public override void OnGUI()
{
authView.OnGUI();
}
public override void Refresh()
{
authView.Refresh();
}
public override void OnEnable()
{
Utility.UnregisterReadyCallback(CreateViews);
Utility.RegisterReadyCallback(CreateViews);
Utility.UnregisterReadyCallback(ShowActiveView);
Utility.RegisterReadyCallback(ShowActiveView);
}
private void CreateViews()
{
if (authView == null)
authView = new AuthenticationView();
authView.Initialize(this);
}
private void ShowActiveView()
{
authView.OnShow();
Refresh();
}
public override void Finish(bool result)
{
Close();
base.Finish(result);
}
}
}
| using System;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class AuthenticationWindow : BaseWindow
{
[SerializeField] private AuthenticationView authView;
[MenuItem("GitHub/Authenticate")]
public static void Launch()
{
Open();
}
public static IView Open(Action<bool> onClose = null)
{
AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
if (onClose != null)
authWindow.OnClose += onClose;
authWindow.minSize = new Vector2(290, 290);
authWindow.Show();
return authWindow;
}
public override void OnGUI()
{
authView.OnGUI();
}
public override void Refresh()
{
authView.Refresh();
}
public override void OnEnable()
{
// Set window title
titleContent = new GUIContent("Sign in", Styles.SmallLogo);
Utility.UnregisterReadyCallback(CreateViews);
Utility.RegisterReadyCallback(CreateViews);
Utility.UnregisterReadyCallback(ShowActiveView);
Utility.RegisterReadyCallback(ShowActiveView);
}
private void CreateViews()
{
if (authView == null)
authView = new AuthenticationView();
authView.Initialize(this);
}
private void ShowActiveView()
{
authView.OnShow();
Refresh();
}
public override void Finish(bool result)
{
Close();
base.Finish(result);
}
}
}
|
Remove unneeded methods from model | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace twitch_tv_viewer.Models
{
public class TwitchChannel : IComparable
{
public TwitchChannel()
{
}
public TwitchChannel(JToken data)
{
var channel = data["channel"];
Name = channel["display_name"]?.ToString() ?? "no name";
Game = channel["game"]?.ToString() ?? "no game";
Status = channel["status"]?.ToString().Trim() ?? "no status";
Viewers = data["viewers"]?.ToString() ?? "???";
}
public string Name { get; set; }
public string Game { get; set; }
public string Status { get; set; }
public string Viewers { get; set; }
public int CompareTo(object obj)
{
var that = obj as TwitchChannel;
if (that == null)
return 0;
return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal);
}
public async Task<string> StartStream()
{
var startInfo = new ProcessStartInfo
{
FileName = "livestreamer",
Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{Name} high",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
var process = new Process
{
StartInfo = startInfo
};
process.Start();
return await process.StandardOutput.ReadToEndAsync();
}
public void OpenChatroom() => Process.Start($"http://twitch.tv/{Name}/chat?popout=");
}
} | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace twitch_tv_viewer.Models
{
public class TwitchChannel : IComparable
{
public TwitchChannel()
{
}
public TwitchChannel(JToken data)
{
var channel = data["channel"];
Name = channel["display_name"]?.ToString() ?? "no name";
Game = channel["game"]?.ToString() ?? "no game";
Status = channel["status"]?.ToString().Trim() ?? "no status";
Viewers = data["viewers"]?.ToString() ?? "???";
}
public string Name { get; set; }
public string Game { get; set; }
public string Status { get; set; }
public string Viewers { get; set; }
public int CompareTo(object obj)
{
var that = obj as TwitchChannel;
if (that == null)
return 0;
return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal);
}
}
} |
Add endpoints for controlling game speed. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Game;
using GnomeServer.Extensions;
using GnomeServer.Routing;
namespace GnomeServer.Controllers
{
[Route("Game")]
public sealed class GameController : ConventionRoutingController
{
[HttpGet]
[Route("")]
public IResponseFormatter Get(int speed)
{
GnomanEmpire.Instance.World.GameSpeed.Value = speed;
String content = String.Format("Game Speed set to '{0}'", speed);
return JsonResponse(content);
}
public IResponseFormatter Test()
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
var fields = typeof(Character).GetFields(bindFlags);
var behaviorTypeFields = fields.Where(obj => obj.FieldType == typeof(BehaviorType)).ToList();
List<TestResponse> testResponses = new List<TestResponse>();
var members = GnomanEmpire.Instance.GetGnomes();
foreach (var characterKey in members)
{
var character = characterKey.Value;
var name = character.NameAndTitle();
foreach (var fieldInfo in behaviorTypeFields)
{
var val = (BehaviorType)(fieldInfo.GetValue(character));
testResponses.Add(new TestResponse
{
Name = name,
Value = val.ToString(),
});
}
}
return JsonResponse(testResponses);
}
private class TestResponse
{
public String Name { get; set; }
public String Value { get; set; }
}
}
}
| using System.Globalization;
using System.Net;
using Game;
using GnomeServer.Routing;
namespace GnomeServer.Controllers
{
[Route("Game")]
public sealed class GameController : ConventionRoutingController
{
[HttpGet]
[Route("Speed")]
public IResponseFormatter GetSpeed()
{
var world = GnomanEmpire.Instance.World;
var speed = new
{
Speed = world.GameSpeed.Value.ToString(CultureInfo.InvariantCulture),
IsPaused = world.Paused.Value.ToString(CultureInfo.InvariantCulture)
};
return JsonResponse(speed);
}
[HttpPost]
[Route("Speed")]
public IResponseFormatter PostSpeed(int speed)
{
GnomanEmpire.Instance.World.GameSpeed.Value = speed;
return BlankResponse(HttpStatusCode.NoContent);
}
[HttpPost]
[Route("Pause")]
public IResponseFormatter PostPause()
{
GnomanEmpire.Instance.World.Paused.Value = true;
return BlankResponse(HttpStatusCode.NoContent);
}
[HttpPost]
[Route("Play")]
public IResponseFormatter PostPlay()
{
GnomanEmpire.Instance.World.Paused.Value = false;
return BlankResponse(HttpStatusCode.NoContent);
}
}
}
|
Correct the Example Name in Comment | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Aspose.Cells.Examples.CSharp.Articles
{
public class LoadWorkbookWithSpecificCultureInfoNumberFormat
{
public static void Run()
{
// ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat
using (var inputStream = new MemoryStream())
{
using (var writer = new StreamWriter(inputStream))
{
writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>");
writer.Flush();
var culture = new CultureInfo("en-GB");
culture.NumberFormat.NumberDecimalSeparator = ",";
culture.DateTimeFormat.DateSeparator = "-";
culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
LoadOptions options = new LoadOptions(LoadFormat.Html);
options.CultureInfo = culture;
using (var workbook = new Workbook(inputStream, options))
{
var cell = workbook.Worksheets[0].Cells["A1"];
Assert.AreEqual(CellValueType.IsNumeric, cell.Type);
Assert.AreEqual(1234.56, cell.DoubleValue);
}
}
}
// ExEnd:LoadWorkbookWithSpecificCultureInfo
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Aspose.Cells.Examples.CSharp.Articles
{
public class LoadWorkbookWithSpecificCultureInfoNumberFormat
{
public static void Run()
{
// ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat
using (var inputStream = new MemoryStream())
{
using (var writer = new StreamWriter(inputStream))
{
writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>");
writer.Flush();
var culture = new CultureInfo("en-GB");
culture.NumberFormat.NumberDecimalSeparator = ",";
culture.DateTimeFormat.DateSeparator = "-";
culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
LoadOptions options = new LoadOptions(LoadFormat.Html);
options.CultureInfo = culture;
using (var workbook = new Workbook(inputStream, options))
{
var cell = workbook.Worksheets[0].Cells["A1"];
Assert.AreEqual(CellValueType.IsNumeric, cell.Type);
Assert.AreEqual(1234.56, cell.DoubleValue);
}
}
}
// ExEnd:LoadWorkbookWithSpecificCultureInfoNumberFormat
}
}
}
|
Fix background brightness being adjusted globally | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using OpenTK.Graphics;
namespace osu.Game.Graphics.Backgrounds
{
public class Background : BufferedContainer
{
public Sprite Sprite;
private readonly string textureName;
public Background(string textureName = @"")
{
CacheDrawnFrameBuffer = true;
this.textureName = textureName;
RelativeSizeAxes = Axes.Both;
Add(Sprite = new Sprite
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.DarkGray,
FillMode = FillMode.Fill,
});
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
if (!string.IsNullOrEmpty(textureName))
Sprite.Texture = textures.Get(textureName);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Graphics.Backgrounds
{
public class Background : BufferedContainer
{
public Sprite Sprite;
private readonly string textureName;
public Background(string textureName = @"")
{
CacheDrawnFrameBuffer = true;
this.textureName = textureName;
RelativeSizeAxes = Axes.Both;
Add(Sprite = new Sprite
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
FillMode = FillMode.Fill,
});
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
if (!string.IsNullOrEmpty(textureName))
Sprite.Texture = textures.Get(textureName);
}
}
}
|
Drop in other CRUD methods | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
public class ACFTController : Controller
{
private readonly Database db;
public ACFTController(Database db)
{
this.db = db;
}
public async Task<IActionResult> Index()
{
return Content("Coming soon!");
}
}
}
| using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
public class ACFTController : Controller
{
private readonly Database db;
public ACFTController(Database db)
{
this.db = db;
}
public async Task<IActionResult> Index()
{
return Content("Coming soon!");
}
public async Task<IActionResult> Details(int id)
{
return View(await Get(db, id));
}
public async Task<IActionResult> New(int soldier = 0)
{
ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);
return View(nameof(Edit), new APFT { SoldierId = soldier });
}
public async Task<IActionResult> Edit(int id)
{
ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);
return View(await Get(db, id));
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Save(ACFT model)
{
if (!ModelState.IsValid)
{
ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);
return View("Edit", model);
}
if (await db.ACFTs.AnyAsync(apft => apft.Id == model.Id) == false)
{
db.ACFTs.Add(model);
}
else
{
db.ACFTs.Update(model);
}
await db.SaveChangesAsync();
return RedirectToAction(nameof(Details), new { model.Id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var test = await Get(db, id);
db.ACFTs.Remove(test);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public static async Task<ACFT> Get(Database db, int id)
{
return
await db
.ACFTs
.Include(_ => _.Soldier)
.ThenInclude(_ => _.Unit)
.Where(_ => _.Id == id)
.SingleOrDefaultAsync();
}
}
}
|
Use 'o' format for date. Fixed splitting problem with backtrace. | using System;
using System.Linq;
using Newtonsoft.Json;
namespace Exceptional.Core
{
public class ExceptionSummary
{
[JsonProperty(PropertyName = "occurred_at")]
public DateTime OccurredAt { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "backtrace")]
public string[] Backtrace { get; set; }
[JsonProperty(PropertyName = "exception_class")]
public string ExceptionClass { get; set; }
public ExceptionSummary()
{
OccurredAt = DateTime.UtcNow;
}
public static ExceptionSummary CreateFromException(Exception ex)
{
var summary = new ExceptionSummary();
summary.Message = ex.Message;
summary.Backtrace = ex.StackTrace.Split('\r', '\n').Select(line => line.Trim()).ToArray();
summary.ExceptionClass = ex.GetType().Name;
return summary;
}
}
} | using System;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace Exceptional.Core
{
public class ExceptionSummary
{
[JsonProperty(PropertyName = "occurred_at")]
public string OccurredAt { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "backtrace")]
public string[] Backtrace { get; set; }
[JsonProperty(PropertyName = "exception_class")]
public string ExceptionClass { get; set; }
public ExceptionSummary()
{
OccurredAt = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
}
public static ExceptionSummary CreateFromException(Exception ex)
{
var summary = new ExceptionSummary();
summary.Message = ex.Message;
summary.Backtrace = ex.StackTrace.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries).Select(line => line.Trim()).ToArray();
summary.ExceptionClass = ex.GetType().Name;
return summary;
}
}
} |
Add key binding set to loop i/o params | using System.IO;
using NClap.ConsoleInput;
using NClap.Utilities;
namespace NClap.Repl
{
/// <summary>
/// Parameters for constructing a loop with advanced line input. The
/// parameters indicate how the loop's textual input and output should
/// be implemented.
/// </summary>
public class LoopInputOutputParameters
{
/// <summary>
/// Writer to use for error output.
/// </summary>
public TextWriter ErrorWriter { get; set; }
/// <summary>
/// Line input object to use.
/// </summary>
public IConsoleLineInput LineInput { get; set; }
/// <summary>
/// The console input interface to use.
/// </summary>
public IConsoleInput ConsoleInput { get; set; }
/// <summary>
/// The console output interface to use.
/// </summary>
public IConsoleOutput ConsoleOutput { get; set; }
/// <summary>
/// Input prompt.
/// </summary>
public ColoredString Prompt { get; set; }
}
}
| using System.IO;
using NClap.ConsoleInput;
using NClap.Utilities;
namespace NClap.Repl
{
/// <summary>
/// Parameters for constructing a loop with advanced line input. The
/// parameters indicate how the loop's textual input and output should
/// be implemented.
/// </summary>
public class LoopInputOutputParameters
{
/// <summary>
/// Optionally provides a writer to use for error output.
/// </summary>
public TextWriter ErrorWriter { get; set; }
/// <summary>
/// Line input object to use, or null for a default one to be
/// constructed.
/// </summary>
public IConsoleLineInput LineInput { get; set; }
/// <summary>
/// The console input interface to use, or null to use the default one.
/// </summary>
public IConsoleInput ConsoleInput { get; set; }
/// <summary>
/// The console output interface to use, or null to use the default one.
/// </summary>
public IConsoleOutput ConsoleOutput { get; set; }
/// <summary>
/// The console key binding set to use, or null to use the default one.
/// </summary>
public IReadOnlyConsoleKeyBindingSet KeyBindingSet { get; set; }
/// <summary>
/// Input prompt, or null to use the default one.
/// </summary>
public ColoredString Prompt { get; set; }
}
}
|
Fix build of test case | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)]
public partial class Bugzilla51642 : ContentPage
{
public Bugzilla51642 ()
{
InitializeComponent ();
LoadDelayedVM();
BoundPicker.SelectedIndexChanged += (s, e) =>
{
SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString();
};
}
public async void LoadDelayedVM()
{
await Task.Delay(1000);
Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM());
}
}
[Preserve(AllMembers=true)]
class Bz51642VM
{
public IList<string> Items {
get {
return new List<String> { "Foo", "Bar", "Baz" };
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)]
public partial class Bugzilla51642 : ContentPage
{
#if APP
public Bugzilla51642 ()
{
InitializeComponent ();
LoadDelayedVM();
BoundPicker.SelectedIndexChanged += (s, e) =>
{
SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString();
};
}
public async void LoadDelayedVM()
{
await Task.Delay(1000);
Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM());
}
#endif
}
[Preserve(AllMembers=true)]
class Bz51642VM
{
public IList<string> Items {
get {
return new List<String> { "Foo", "Bar", "Baz" };
}
}
}
}
|
Remove some unused using statements | // Copyright 2017 Daniel Plemmons
// 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.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicStageManagable : StageManagable{
private bool hasInitialized = false;
protected virtual void Awake()
{
Initialize();
}
protected virtual void Initialize()
{
if(hasInitialized)
{
return;
}
hasInitialized = true;
gameObject.SetActive(false);
}
public override void Enter()
{
Initialize();
StartEnter();
gameObject.SetActive(true);
CompleteEnter();
}
public override void Exit()
{
Initialize();
StartExit();
gameObject.SetActive(false);
CompleteExit();
}
}
| // Copyright 2017 Daniel Plemmons
// 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.
public class BasicStageManagable : StageManagable{
private bool hasInitialized = false;
protected virtual void Awake()
{
Initialize();
}
protected virtual void Initialize()
{
if(hasInitialized)
{
return;
}
hasInitialized = true;
gameObject.SetActive(false);
}
public override void Enter()
{
Initialize();
StartEnter();
gameObject.SetActive(true);
CompleteEnter();
}
public override void Exit()
{
Initialize();
StartExit();
gameObject.SetActive(false);
CompleteExit();
}
}
|
Add test for scalar queries with 1 row | using System;
using System.Linq;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
namespace SQLite.Tests
{
[TestFixture]
public class ScalarTest
{
class TestTable
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Two { get; set; }
}
const int Count = 100;
SQLiteConnection CreateDb ()
{
var db = new TestDb ();
db.CreateTable<TestTable> ();
var items = from i in Enumerable.Range (0, Count)
select new TestTable { Two = 2 };
db.InsertAll (items);
Assert.AreEqual (Count, db.Table<TestTable> ().Count ());
return db;
}
[Test]
public void Int32 ()
{
var db = CreateDb ();
var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable");
Assert.AreEqual (Count * 2, r);
}
}
}
| using System;
using System.Linq;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
namespace SQLite.Tests
{
[TestFixture]
public class ScalarTest
{
class TestTable
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Two { get; set; }
}
const int Count = 100;
SQLiteConnection CreateDb ()
{
var db = new TestDb ();
db.CreateTable<TestTable> ();
var items = from i in Enumerable.Range (0, Count)
select new TestTable { Two = 2 };
db.InsertAll (items);
Assert.AreEqual (Count, db.Table<TestTable> ().Count ());
return db;
}
[Test]
public void Int32 ()
{
var db = CreateDb ();
var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable");
Assert.AreEqual (Count * 2, r);
}
[Test]
public void SelectSingleRowValue ()
{
var db = CreateDb ();
var r = db.ExecuteScalar<int> ("SELECT Two FROM TestTable WHERE Id = 1 LIMIT 1");
Assert.AreEqual (2, r);
}
}
}
|
Adjust the values for the Punchline Place fishing spot. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Environment;
namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing
{
public class FishingSpotFlavor
{
public Coordinates Scan1 { get; }
public Coordinates Scan2 { get; }
public ScreenshotColor BubbleColor { get; }
public int Tolerance { get; }
public FishingSpotFlavor(Coordinates scan1, Coordinates scan2,
ScreenshotColor bubbleColor, int tolerance)
{
this.Scan1 = scan1;
this.Scan2 = scan2;
this.BubbleColor = bubbleColor;
this.Tolerance = tolerance;
}
// TODO: The Color value needs some adjustment!
public static readonly FishingSpotFlavor PunchlinePlace =
new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626),
new ScreenshotColor(24, 142, 118), 16);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Environment;
namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing
{
public class FishingSpotFlavor
{
public Coordinates Scan1 { get; }
public Coordinates Scan2 { get; }
public ScreenshotColor BubbleColor { get; }
public int Tolerance { get; }
public FishingSpotFlavor(Coordinates scan1, Coordinates scan2,
ScreenshotColor bubbleColor, int tolerance)
{
this.Scan1 = scan1;
this.Scan2 = scan2;
this.BubbleColor = bubbleColor;
this.Tolerance = tolerance;
}
// TODO: The Color value needs some adjustment!
public static readonly FishingSpotFlavor PunchlinePlace =
new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626),
new ScreenshotColor(22, 140, 116), 13);
}
}
|
Initialize new home controller instance for test class | namespace Foo.Tests.Web.Controllers
{
public class HomeControllerTest
{
}
}
| using Foo.Web.Controllers;
namespace Foo.Tests.Web.Controllers
{
public class HomeControllerTest
{
private readonly HomeController _controller;
public HomeControllerTest()
{
_controller = new HomeController();
}
}
}
|
Update find resource code post internal change | using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.IO;
using System.Reflection;
using System.Text;
using Glimpse.Server.Web;
namespace Glimpse.Agent.Browser.Resources
{
public class BrowserAgent : IMiddlewareResourceComposer
{
public void Register(IApplicationBuilder appBuilder)
{
appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context =>
{
var response = context.Response;
response.Headers.Set("Content-Type", "application/javascript");
var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly;
var jqueryStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/jquery.jquery-2.1.1.js");
var signalrStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/signalr/jquery.signalR-2.2.0.js");
var agentStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/BrowserAgent.js");
using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8))
using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8))
using (var agentReader = new StreamReader(agentStream, Encoding.UTF8))
{
// TODO: The worlds worst hack!!! Nik did this...
await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd());
}
}));
}
}
} | using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.IO;
using System.Reflection;
using System.Text;
using Glimpse.Server.Web;
namespace Glimpse.Agent.Browser.Resources
{
public class BrowserAgent : IMiddlewareResourceComposer
{
public void Register(IApplicationBuilder appBuilder)
{
appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context =>
{
var response = context.Response;
response.Headers.Set("Content-Type", "application/javascript");
var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly;
var jqueryStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.jquery.jquery-2.1.1.js");
var signalrStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.signalr.jquery.signalR-2.2.0.js");
var agentStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.BrowserAgent.js");
using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8))
using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8))
using (var agentReader = new StreamReader(agentStream, Encoding.UTF8))
{
// TODO: The worlds worst hack!!! Nik did this...
await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd());
}
}));
}
}
} |
Fix target in installer form | @{
Layout = "master.cshtml";
}
<div class="admin-container">
<div class="admin-form-view">
<form role="form" method="POST" target="/">
<div class="form-group well">
<label for="key">Key</label>
<input type="password" class="form-control" id="key" name="key" placeholder="key">
</div>
<div class="well">
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="password">
</div>
</div>
<button class="btn btn-danger btn-lg pull-right" type="submit">Install</button>
</form>
</div>
</div> | @{
Layout = "master.cshtml";
}
<div class="admin-container">
<div class="admin-form-view">
<form role="form" method="POST">
<div class="form-group well">
<label for="key">Key</label>
<input type="password" class="form-control" id="key" name="key" placeholder="key">
</div>
<div class="well">
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="password">
</div>
</div>
<button class="btn btn-danger btn-lg pull-right" type="submit">Install</button>
</form>
</div>
</div> |
FIX logger variable in PS scripts | using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;
namespace Aggregator.Core
{
/// <summary>
/// Invokes Powershell scripting engine
/// </summary>
public class PsScriptEngine : ScriptEngine
{
private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();
public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
: base(store, logger, debug)
{
}
public override bool Load(string scriptName, string script)
{
this.scripts.Add(scriptName, script);
return true;
}
public override bool LoadCompleted()
{
return true;
}
public override void Run(string scriptName, IWorkItem workItem)
{
string script = this.scripts[scriptName];
var config = RunspaceConfiguration.Create();
using (var runspace = RunspaceFactory.CreateRunspace(config))
{
runspace.Open();
runspace.SessionStateProxy.SetVariable("self", workItem);
runspace.SessionStateProxy.SetVariable("store", this.Store);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
// execute
var results = pipeline.Invoke();
this.Logger.ResultsFromScriptRun(scriptName, results);
}
}
}
}
| using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;
namespace Aggregator.Core
{
/// <summary>
/// Invokes Powershell scripting engine
/// </summary>
public class PsScriptEngine : ScriptEngine
{
private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();
public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
: base(store, logger, debug)
{
}
public override bool Load(string scriptName, string script)
{
this.scripts.Add(scriptName, script);
return true;
}
public override bool LoadCompleted()
{
return true;
}
public override void Run(string scriptName, IWorkItem workItem)
{
string script = this.scripts[scriptName];
var config = RunspaceConfiguration.Create();
using (var runspace = RunspaceFactory.CreateRunspace(config))
{
runspace.Open();
runspace.SessionStateProxy.SetVariable("self", workItem);
runspace.SessionStateProxy.SetVariable("store", this.Store);
runspace.SessionStateProxy.SetVariable("logger", this.Logger);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
// execute
var results = pipeline.Invoke();
this.Logger.ResultsFromScriptRun(scriptName, results);
}
}
}
}
|
Fix "Keep Window Centered" option | #region
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class SwitchWindow : Window
{
public SwitchWindow()
{
InitializeComponent();
ReloadAccountListBinding();
}
public void ReloadAccountListBinding()
{
AccountView.DataContext = null;
AccountView.DataContext = App.Accounts;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
if (App.IsShuttingDown)
return;
if (Settings.Default.AlwaysOn)
{
e.Cancel = true;
HideWindow();
return;
}
AppHelper.ShutdownApplication();
}
public void HideWindow()
{
var visible = Visibility == Visibility.Visible;
Hide();
if (visible && Settings.Default.AlwaysOn)
TrayIconHelper.ShowRunningInTrayBalloon();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
var mainWindowPtr = new WindowInteropHelper(this).Handle;
var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc);
}
}
} | #region
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class SwitchWindow : Window
{
public SwitchWindow()
{
InitializeComponent();
WindowStartupLocation = Settings.Default.SwitchWindowKeepCentered
? WindowStartupLocation.CenterScreen
: WindowStartupLocation.Manual;
ReloadAccountListBinding();
}
public void ReloadAccountListBinding()
{
AccountView.DataContext = null;
AccountView.DataContext = App.Accounts;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
if (App.IsShuttingDown)
return;
if (Settings.Default.AlwaysOn)
{
e.Cancel = true;
HideWindow();
return;
}
AppHelper.ShutdownApplication();
}
public void HideWindow()
{
var visible = Visibility == Visibility.Visible;
Hide();
if (visible && Settings.Default.AlwaysOn)
TrayIconHelper.ShowRunningInTrayBalloon();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
var mainWindowPtr = new WindowInteropHelper(this).Handle;
var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc);
}
}
} |
Allow selecting vpks in content search paths | using System;
using System.Windows.Forms;
using GUI.Utils;
namespace GUI.Forms
{
public partial class SettingsForm : Form
{
public SettingsForm()
{
InitializeComponent();
}
private void SettingsForm_Load(object sender, EventArgs e)
{
foreach (var path in Settings.GameSearchPaths)
{
gamePaths.Items.Add(path);
}
}
private void GamePathRemoveClick(object sender, EventArgs e)
{
if (gamePaths.SelectedIndex < 0)
{
return;
}
Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem);
Settings.Save();
gamePaths.Items.RemoveAt(gamePaths.SelectedIndex);
}
private void GamePathAdd(object sender, EventArgs e)
{
using (var dlg = new FolderBrowserDialog())
{
dlg.Description = "Select a folder";
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
if (Settings.GameSearchPaths.Contains(dlg.SelectedPath))
{
return;
}
Settings.GameSearchPaths.Add(dlg.SelectedPath);
Settings.Save();
gamePaths.Items.Add(dlg.SelectedPath);
}
}
private void button1_Click(object sender, EventArgs e)
{
var colorPicker = new ColorDialog();
colorPicker.Color = Settings.BackgroundColor;
// Update the text box color if the user clicks OK
if (colorPicker.ShowDialog() == DialogResult.OK)
{
Settings.BackgroundColor = colorPicker.Color;
}
}
}
}
| using System;
using System.Windows.Forms;
using GUI.Utils;
namespace GUI.Forms
{
public partial class SettingsForm : Form
{
public SettingsForm()
{
InitializeComponent();
}
private void SettingsForm_Load(object sender, EventArgs e)
{
foreach (var path in Settings.GameSearchPaths)
{
gamePaths.Items.Add(path);
}
}
private void GamePathRemoveClick(object sender, EventArgs e)
{
if (gamePaths.SelectedIndex < 0)
{
return;
}
Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem);
Settings.Save();
gamePaths.Items.RemoveAt(gamePaths.SelectedIndex);
}
private void GamePathAdd(object sender, EventArgs e)
{
using (var dlg = new OpenFileDialog())
{
dlg.Filter = "Valve Pak (*.vpk)|*.vpk|All files (*.*)|*.*";
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
if (Settings.GameSearchPaths.Contains(dlg.FileName))
{
return;
}
Settings.GameSearchPaths.Add(dlg.FileName);
Settings.Save();
gamePaths.Items.Add(dlg.FileName);
}
}
private void button1_Click(object sender, EventArgs e)
{
var colorPicker = new ColorDialog();
colorPicker.Color = Settings.BackgroundColor;
// Update the text box color if the user clicks OK
if (colorPicker.ShowDialog() == DialogResult.OK)
{
Settings.BackgroundColor = colorPicker.Color;
}
}
}
}
|
Add App_Code, App_Data and App_Plugins folders to be created during app startup | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Umbraco.Core.IO;
using umbraco.businesslogic;
using umbraco.interfaces;
namespace umbraco.presentation
{
public class EnsureSystemPathsApplicationStartupHandler : IApplicationStartupHandler
{
public EnsureSystemPathsApplicationStartupHandler()
{
EnsurePathExists(SystemDirectories.Css);
EnsurePathExists(SystemDirectories.Data);
EnsurePathExists(SystemDirectories.MacroScripts);
EnsurePathExists(SystemDirectories.Masterpages);
EnsurePathExists(SystemDirectories.Media);
EnsurePathExists(SystemDirectories.Scripts);
EnsurePathExists(SystemDirectories.UserControls);
EnsurePathExists(SystemDirectories.Xslt);
EnsurePathExists(SystemDirectories.MvcViews);
EnsurePathExists(SystemDirectories.MvcViews + "/Partials");
EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials");
}
public void EnsurePathExists(string path)
{
var absolutePath = IOHelper.MapPath(path);
if (!Directory.Exists(absolutePath))
Directory.CreateDirectory(absolutePath);
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Umbraco.Core.IO;
using umbraco.businesslogic;
using umbraco.interfaces;
namespace umbraco.presentation
{
public class EnsureSystemPathsApplicationStartupHandler : IApplicationStartupHandler
{
public EnsureSystemPathsApplicationStartupHandler()
{
EnsurePathExists("~/App_Code");
EnsurePathExists("~/App_Data");
EnsurePathExists(SystemDirectories.AppPlugins);
EnsurePathExists(SystemDirectories.Css);
EnsurePathExists(SystemDirectories.MacroScripts);
EnsurePathExists(SystemDirectories.Masterpages);
EnsurePathExists(SystemDirectories.Media);
EnsurePathExists(SystemDirectories.Scripts);
EnsurePathExists(SystemDirectories.UserControls);
EnsurePathExists(SystemDirectories.Xslt);
EnsurePathExists(SystemDirectories.MvcViews);
EnsurePathExists(SystemDirectories.MvcViews + "/Partials");
EnsurePathExists(SystemDirectories.MvcViews + "/MacroPartials");
}
public void EnsurePathExists(string path)
{
var absolutePath = IOHelper.MapPath(path);
if (!Directory.Exists(absolutePath))
Directory.CreateDirectory(absolutePath);
}
}
} |
Fix Canvas negative Height test | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ooui;
namespace Tests
{
[TestClass]
public class CanvasTests
{
[TestMethod]
public void Context2dState ()
{
var c = new Canvas ();
Assert.AreEqual (1, c.StateMessages.Count);
var c2d = c.GetContext2d ();
Assert.AreEqual (2, c.StateMessages.Count);
var c2d2 = c.GetContext2d ();
Assert.AreEqual (2, c.StateMessages.Count);
Assert.AreEqual (c2d, c2d2);
}
[TestMethod]
public void DefaultWidthAndHeight ()
{
var c = new Canvas ();
Assert.AreEqual (150, c.Width);
Assert.AreEqual (150, c.Height);
}
[TestMethod]
public void WidthAndHeight ()
{
var c = new Canvas {
Width = 640,
Height = 480,
};
Assert.AreEqual (640, c.Width);
Assert.AreEqual (480, c.Height);
}
[TestMethod]
public void CantBeNegativeOrZero ()
{
var c = new Canvas {
Width = 640,
Height = 480,
};
Assert.AreEqual (640, c.Width);
Assert.AreEqual (480, c.Height);
c.Width = 0;
c.Height = 0;
Assert.AreEqual (150, c.Width);
Assert.AreEqual (150, c.Height);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ooui;
namespace Tests
{
[TestClass]
public class CanvasTests
{
[TestMethod]
public void Context2dState ()
{
var c = new Canvas ();
Assert.AreEqual (1, c.StateMessages.Count);
var c2d = c.GetContext2d ();
Assert.AreEqual (2, c.StateMessages.Count);
var c2d2 = c.GetContext2d ();
Assert.AreEqual (2, c.StateMessages.Count);
Assert.AreEqual (c2d, c2d2);
}
[TestMethod]
public void DefaultWidthAndHeight ()
{
var c = new Canvas ();
Assert.AreEqual (150, c.Width);
Assert.AreEqual (150, c.Height);
}
[TestMethod]
public void WidthAndHeight ()
{
var c = new Canvas {
Width = 640,
Height = 480,
};
Assert.AreEqual (640, c.Width);
Assert.AreEqual (480, c.Height);
}
[TestMethod]
public void CantBeNegativeOrZero ()
{
var c = new Canvas {
Width = 640,
Height = 480,
};
Assert.AreEqual (640, c.Width);
Assert.AreEqual (480, c.Height);
c.Width = 0;
c.Height = -100;
Assert.AreEqual (150, c.Width);
Assert.AreEqual (150, c.Height);
}
}
}
|
Add exception handling in middleware | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) => {
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
trace.Record(Annotations.ServerRecv());
trace.Record(Annotations.ServiceName(serviceName));
trace.Record(Annotations.Rpc(context.Request.Method));
await next.Invoke();
trace.Record(Annotations.ServerSend());
});
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) => {
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
trace.Record(Annotations.ServerRecv());
trace.Record(Annotations.ServiceName(serviceName));
trace.Record(Annotations.Rpc(context.Request.Method));
try
{
await next.Invoke();
}
catch (System.Exception e)
{
trace.Record(Annotations.Tag("error", e.Message));
throw;
}
finally
{
trace.Record(Annotations.ServerSend());
}
});
}
}
} |
Refactor Subtract Doubles Operation to use GetValues and CloneWithValues | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
Tensor<double> result = new Tensor<double>();
result.SetValue(tensor1.GetValue() - tensor2.GetValue());
return result;
}
}
}
| namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
double[] values1 = tensor1.GetValues();
int l = values1.Length;
double[] values2 = tensor2.GetValues();
double[] newvalues = new double[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] - values2[k];
return tensor1.CloneWithNewValues(newvalues);
}
}
}
|
FIx issue looking up property aliases for built-in datatypes | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Interfaces;
namespace Census.UmbracoObject
{
public class Property : IUmbracoObject
{
public string Name { get { return "Document Type"; } }
public List<string> BackofficePages
{
get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; }
}
DataTable IUmbracoObject.ToDataTable(object usages)
{
return ToDataTable(usages);
}
public static DataTable ToDataTable(object usages, int propertyId = 0)
{
var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages;
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Alias");
dt.Columns.Add("Property");
foreach (var documentType in documentTypes)
{
var row = dt.NewRow();
row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif");
row["Alias"] = documentType.Alias;
if (propertyId > 0)
{
var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId);
if (prop != null)
row["Property"] = prop.Name;
}
dt.Rows.Add(row);
row.AcceptChanges();
}
return dt;
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Interfaces;
namespace Census.UmbracoObject
{
public class Property : IUmbracoObject
{
public string Name { get { return "Document Type"; } }
public List<string> BackofficePages
{
get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; }
}
DataTable IUmbracoObject.ToDataTable(object usages)
{
return ToDataTable(usages);
}
public static DataTable ToDataTable(object usages, int propertyId = 0)
{
var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages;
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Alias");
dt.Columns.Add("Property");
foreach (var documentType in documentTypes)
{
var row = dt.NewRow();
row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif");
row["Alias"] = documentType.Alias;
if (propertyId != 0)
{
var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId);
if (prop != null)
row["Property"] = prop.Name;
}
dt.Rows.Add(row);
row.AcceptChanges();
}
return dt;
}
}
} |
Add choices of hover sample sets | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with added default sound effects.
/// </summary>
public class OsuButton : Button
{
private SampleChannel sampleClick;
private SampleChannel sampleHover;
protected override bool OnClick(InputState state)
{
sampleClick?.Play();
return base.OnClick(state);
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, AudioManager audio)
{
sampleClick = audio.Sample.Get(@"UI/generic-select");
sampleHover = audio.Sample.Get(@"UI/generic-hover");
}
}
}
| // 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.UserInterface;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with added default sound effects.
/// </summary>
public class OsuButton : Button
{
private SampleChannel sampleClick;
private SampleChannel sampleHover;
protected HoverSampleSet SampleSet = HoverSampleSet.Normal;
protected override bool OnClick(InputState state)
{
sampleClick?.Play();
return base.OnClick(state);
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Sample.Get($@"UI/generic-select{SampleSet.GetDescription()}");
sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
public enum HoverSampleSet
{
[Description("")]
Normal,
[Description("-soft")]
Soft,
[Description("-softer")]
Softer
}
}
}
|
Read pages and break them down into streams If file stream was not owned by us, rewind it after reading | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mlabs.Ogg.Metadata;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IStreamInfo Read()
{
var p = new PageReader();
var pages = p.ReadPages(m_fileStream).ToList();
if (m_owns)
m_fileStream.Dispose();
return null;
}
}
} | using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
} |
Change path for def template generator | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimTrans.Builder;
using RimTrans.Builder.Crawler;
namespace RimTransLibTest {
public static class GenHelper {
public static void Gen_DefTypeNameOf() {
Console.Write(DefTypeCrawler.GenCode(true, false));
}
public static void Gen_DefsTemplate() {
DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs");
Capture capture = Capture.Parse(coreDefinitionData);
capture.ProcessFieldNames(coreDefinitionData);
coreDefinitionData.Save(@"D:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed");
string sourceCodePath = @"D:\git\rw\RimWorld-Decompile\Assembly-CSharp";
Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true);
templates.Save(@"D:\git\rw\RimWorld-Defs-Templates\Templates");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimTrans.Builder;
using RimTrans.Builder.Crawler;
namespace RimTransLibTest {
public static class GenHelper {
public static void Gen_DefTypeNameOf() {
Console.Write(DefTypeCrawler.GenCode(true, false));
}
public static void Gen_DefsTemplate() {
DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs");
Capture capture = Capture.Parse(coreDefinitionData);
capture.ProcessFieldNames(coreDefinitionData);
coreDefinitionData.Save(@"C:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed");
string sourceCodePath = @"C:\git\rw\RimWorld-Decompile\Assembly-CSharp";
Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true);
templates.Save(@"C:\git\rw\RimWorld-Defs-Templates\Templates");
}
}
}
|
Make virtual tracks reeeeeeeaaally long | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Timing;
namespace osu.Framework.Audio.Track
{
public class TrackVirtual : Track
{
private readonly StopwatchClock clock = new StopwatchClock();
private double seekOffset;
public override bool Seek(double seek)
{
double current = CurrentTime;
seekOffset = seek;
lock (clock) clock.Restart();
if (Length > 0 && seekOffset > Length)
seekOffset = Length;
return current != seekOffset;
}
public override void Start()
{
lock (clock) clock.Start();
}
public override void Reset()
{
lock (clock) clock.Reset();
seekOffset = 0;
base.Reset();
}
public override void Stop()
{
lock (clock) clock.Stop();
}
public override bool IsRunning
{
get
{
lock (clock) return clock.IsRunning;
}
}
public override bool HasCompleted
{
get
{
lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
}
}
public override double CurrentTime
{
get
{
lock (clock) return seekOffset + clock.CurrentTime;
}
}
public override void Update()
{
lock (clock)
{
if (CurrentTime >= Length)
Stop();
}
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Timing;
namespace osu.Framework.Audio.Track
{
public class TrackVirtual : Track
{
private readonly StopwatchClock clock = new StopwatchClock();
private double seekOffset;
public TrackVirtual()
{
Length = double.MaxValue;
}
public override bool Seek(double seek)
{
double current = CurrentTime;
seekOffset = seek;
lock (clock) clock.Restart();
if (Length > 0 && seekOffset > Length)
seekOffset = Length;
return current != seekOffset;
}
public override void Start()
{
lock (clock) clock.Start();
}
public override void Reset()
{
lock (clock) clock.Reset();
seekOffset = 0;
base.Reset();
}
public override void Stop()
{
lock (clock) clock.Stop();
}
public override bool IsRunning
{
get
{
lock (clock) return clock.IsRunning;
}
}
public override bool HasCompleted
{
get
{
lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
}
}
public override double CurrentTime
{
get
{
lock (clock) return seekOffset + clock.CurrentTime;
}
}
public override void Update()
{
lock (clock)
{
if (CurrentTime >= Length)
Stop();
}
}
}
}
|
Fix category of revision log RSS feeds. | <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Report</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
| <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Log</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
|
Remove these enum values that were copy-pasted by mistake. | namespace ZWave.CommandClasses
{
public enum ThermostatFanModeValue : byte
{
AutoLow = 0x00,
Low = 0x01,
AutoHigh = 0x02,
High = 0x03,
AutoMedium = 0x04,
Medium = 0x05,
Circulation = 0x06,
HumidityCirculation = 0x07,
LeftAndRight = 0x08,
UpAndDown = 0x09,
Quiet = 0x0A,
ExternalCirculation = 0x0B,
EnergyCool = 0x0C,
Away = 0x0D,
Reserved = 0x0E,
FullPower = 0x0F,
ManufacturerSpecific = 0x1F
};
}
| namespace ZWave.CommandClasses
{
public enum ThermostatFanModeValue : byte
{
AutoLow = 0x00,
Low = 0x01,
AutoHigh = 0x02,
High = 0x03,
AutoMedium = 0x04,
Medium = 0x05,
Circulation = 0x06,
HumidityCirculation = 0x07,
LeftAndRight = 0x08,
UpAndDown = 0x09,
Quiet = 0x0A,
ExternalCirculation = 0x0B
};
}
|
Fix expiry date on create new poll | using System;
using System.ComponentModel.DataAnnotations;
namespace VotingApplication.Web.Api.Models.DBViewModels
{
public class PollCreationRequestModel
{
[Required]
public string Name { get; set; }
[Required]
public string Creator { get; set; }
[Required]
public string VotingStrategy { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(1, int.MaxValue)]
public int MaxPoints { get; set; }
[Range(1, int.MaxValue)]
public int MaxPerVote { get; set; }
public long TemplateId { get; set; }
public bool InviteOnly { get; set; }
public bool NamedVoting { get; set; }
public bool RequireAuth { get; set; }
public bool Expires { get; set; }
public DateTimeOffset ExpiryDate { get; set; }
public bool OptionAdding { get; set; }
}
} | using System;
using System.ComponentModel.DataAnnotations;
namespace VotingApplication.Web.Api.Models.DBViewModels
{
public class PollCreationRequestModel
{
[Required]
public string Name { get; set; }
[Required]
public string Creator { get; set; }
[Required]
public string VotingStrategy { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(1, int.MaxValue)]
public int MaxPoints { get; set; }
[Range(1, int.MaxValue)]
public int MaxPerVote { get; set; }
public long TemplateId { get; set; }
public bool InviteOnly { get; set; }
public bool NamedVoting { get; set; }
public bool RequireAuth { get; set; }
public bool Expires { get; set; }
public DateTimeOffset? ExpiryDate { get; set; }
public bool OptionAdding { get; set; }
}
} |
Add Initialize() method to ITabsterPlugin | #region
using System;
using Tabster.Core.Plugins;
#endregion
namespace TextFile
{
public class TextFilePlugin : ITabsterPlugin
{
#region Implementation of ITabsterPlugin
public string Author
{
get { return "Nate Shoffner"; }
}
public string Copyright
{
get { return "Copyright © Nate Shoffner 2014"; }
}
public string Description
{
get { return "Supports importing and exporting to/from text (.txt) files. "; }
}
public string DisplayName
{
get { return "Textfile support"; }
}
public Version Version
{
get { return new Version("1.0"); }
}
public Uri Website
{
get { return new Uri("http://nateshoffner.com"); }
}
public void Activate()
{
// not implemented
}
public void Deactivate()
{
// not implemented
}
public Type[] Types
{
get { return new[] {typeof (TextFileExporter), typeof (TextFileImporter)}; }
}
#endregion
}
} | #region
using System;
using Tabster.Core.Plugins;
#endregion
namespace TextFile
{
public class TextFilePlugin : ITabsterPlugin
{
#region Implementation of ITabsterPlugin
public string Author
{
get { return "Nate Shoffner"; }
}
public string Copyright
{
get { return "Copyright © Nate Shoffner 2014"; }
}
public string Description
{
get { return "Supports importing and exporting to/from text (.txt) files. "; }
}
public string DisplayName
{
get { return "Textfile support"; }
}
public Version Version
{
get { return new Version("1.0"); }
}
public Uri Website
{
get { return new Uri("http://nateshoffner.com"); }
}
public void Activate()
{
// not implemented
}
public void Deactivate()
{
// not implemented
}
public void Initialize()
{
// not implemented
}
public Type[] Types
{
get { return new[] {typeof (TextFileExporter), typeof (TextFileImporter)}; }
}
#endregion
}
} |
Add AssertConfigurationIsValid test for missing ctor parameter | using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class ValidationTests
{
[Fact]
public void VerifyValidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
container.AssertConfigurationIsValid();
}
[Fact]
public void VerifyInvalidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<BrokenService>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
public class BrokenService : IService
{
public string Id { get; private set; }
[ValidationMethod]
public void BrokenMethod()
{
throw new ApplicationException();
}
}
}
}
| using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class ValidationTests
{
[Fact]
public void MissingRequiredConstructorArgument()
{
var container = new Container(x =>
{
x.For<IService>().Use<ServiceWithCtorArg>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
[Fact]
public void VerifyValidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
container.AssertConfigurationIsValid();
}
[Fact]
public void VerifyInvalidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<BrokenService>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
public class BrokenService : IService
{
public string Id { get; private set; }
[ValidationMethod]
public void BrokenMethod()
{
throw new ApplicationException();
}
}
}
}
|
Use anchor tag helper instead of hard coded href | @page
@model Disable2faModel
@{
ViewData["Title"] = "Disable two-factor authentication (2FA)";
ViewData["ActivePage"] = "TwoFactorAuthentication";
}
<h2>@ViewData["Title"]</h2>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>This action only disables 2FA.</strong>
</p>
<p>
Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a href="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Disable 2FA</button>
</form>
</div>
| @page
@model Disable2faModel
@{
ViewData["Title"] = "Disable two-factor authentication (2FA)";
ViewData["ActivePage"] = "TwoFactorAuthentication";
}
<h2>@ViewData["Title"]</h2>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>This action only disables 2FA.</strong>
</p>
<p>
Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a asp-page="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Disable 2FA</button>
</form>
</div>
|
Fix settings checkboxes not being searchable | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsCheckbox : SettingsItem<bool>
{
private OsuCheckbox checkbox;
protected override Drawable CreateControl() => checkbox = new OsuCheckbox();
public override string LabelText
{
set => checkbox.LabelText = value;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsCheckbox : SettingsItem<bool>
{
private OsuCheckbox checkbox;
private string labelText;
protected override Drawable CreateControl() => checkbox = new OsuCheckbox();
public override string LabelText
{
get => labelText;
set => checkbox.LabelText = labelText = value;
}
}
}
|
Allow deletion and reading of saved package information. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using YaTools.Yaml;
using Raven;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Storage;
using Raven.Database;
namespace Craftitude
{
public class RepositoryCache : IDisposable
{
internal EmbeddableDocumentStore _db;
internal Cache _cache;
internal RepositoryCache(Cache cache, string cacheId)
{
_cache = cache;
_db = new EmbeddableDocumentStore()
{
DataDirectory = Path.Combine(_cache._path, cacheId)
};
if (!Directory.Exists(_db.DataDirectory))
Directory.CreateDirectory(_db.DataDirectory);
_db.Initialize();
}
public void Dispose()
{
if (!_db.WasDisposed)
_db.Dispose();
}
public void SavePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Store(package, id);
}
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using YaTools.Yaml;
using Raven;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Storage;
using Raven.Database;
namespace Craftitude
{
public class RepositoryCache : IDisposable
{
internal EmbeddableDocumentStore _db;
internal Cache _cache;
internal RepositoryCache(Cache cache, string cacheId)
{
_cache = cache;
_db = new EmbeddableDocumentStore()
{
DataDirectory = Path.Combine(_cache._path, cacheId)
};
if (!Directory.Exists(_db.DataDirectory))
Directory.CreateDirectory(_db.DataDirectory);
_db.Initialize();
}
public void Dispose()
{
if (!_db.WasDisposed)
_db.Dispose();
}
public void DeletePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Delete(package);
session.SaveChanges();
}
}
public void SavePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Store(package, id);
session.SaveChanges();
}
}
public Package[] GetPackages(params string[] IDs)
{
using (var session = _db.OpenSession())
{
return session.Load<Package>(IDs);
}
}
public Package GetPackage(string ID)
{
using (var session = _db.OpenSession())
{
return session.Load<Package>(ID);
}
}
}
}
|
Split apart and made generic the interfaces for maps following interface segregation and CQRS | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Mappings
{
public interface IMapping<T>
{
void print();
T get_pos(ICoordinate coord);
bool pos_exists(ICoordinate coord);
bool add_to_pos(T addition, ICoordinate coord);
bool remove_from_pos(ICoordinate coord);
}
public interface IMapUpdatable
{
bool can_move(ICoordinate startCoord, ICoordinate endCoord);
bool move(ICoordinate startCoord, ICoordinate endCoord);
}
public interface IMapUpdateReadable<T>
{
void print();
T get_pos(ICoordinate coord);
bool pos_exists(ICoordinate coord);
}
}
| using Engine.Mappings.Coordinates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Mappings
{
public interface IMapWriteable<T>
{
bool can_move(ICoordinate<T> startCoord, ICoordinate<T> endCoord);
bool move(ICoordinate<T> startCoord, ICoordinate<T> endCoord);
}
public interface IMapReadable<T, S>
{
void print();
S get_pos(ICoordinate<T> coord);
bool pos_exists(ICoordinate<T> coord);
}
}
|
Add command in the comment. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WinSerHost
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private ServiceHost host;
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
host = new ServiceHost(typeof(BankAService.BankAService));
host.Open();
}
protected override void OnStop()
{
if (host != null)
{
host.Close();
}
host = null;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WinSerHost
{
// For this service to work correctly,
// we must run the following command in Admin mode,
// netsh http add urlacl url=http://+:9889/BankA user="NT AUTHORITY\NETWORKSERVICE"
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private ServiceHost host;
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
host = new ServiceHost(typeof(BankAService.BankAService));
host.Open();
}
protected override void OnStop()
{
if (host != null)
{
host.Close();
}
host = null;
}
}
}
|
Use SkipLocalsInit on .NET 5 | using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("ZeroLog.Tests")]
[assembly: InternalsVisibleTo("ZeroLog.Benchmarks")]
| using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("ZeroLog.Tests")]
[assembly: InternalsVisibleTo("ZeroLog.Benchmarks")]
#if NETCOREAPP && !NETCOREAPP2_1
[module: SkipLocalsInit]
#endif
|
Add timeout waiting for MainWindow. | namespace Gu.Wpf.Geometry.UiTests
{
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that we do not explode.
using (var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe"))
{
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
_ = tabItem.Select();
}
}
}
}
}
| namespace Gu.Wpf.Geometry.UiTests
{
using System;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that we do not explode.
using (var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe"))
{
app.WaitForMainWindow(TimeSpan.FromSeconds(10));
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
_ = tabItem.Select();
}
}
}
}
}
|
Add - Aggiunta proprietà lista sedi alla result degli utenti nella gestione utenti | //-----------------------------------------------------------------------
// <copyright file="ListaOperatoriResult.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Condivise;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaOperatori
{
public class ListaOperatoriResult
{
public Paginazione Pagination { get; set; }
public List<Utente> DataArray { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="ListaOperatoriResult.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Condivise;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaOperatori
{
public class ListaOperatoriResult
{
public Paginazione Pagination { get; set; }
public List<Utente> DataArray { get; set; }
public List<string> ListaSediPresenti { get; set; }
}
}
|
Fix manual smoke test for Google.Cloud.Firestore.Admin.V1 | // Copyright 2019 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 System;
namespace Google.Cloud.Firestore.Admin.V1.SmokeTests
{
public sealed class FirestoreAdminSmokeTest
{
private const string ProjectEnvironmentVariable = "FIRESTORE_TEST_PROJECT";
public static int Main(string[] args)
{
string projectId = Environment.GetEnvironmentVariable(ProjectEnvironmentVariable);
if (string.IsNullOrEmpty(projectId))
{
Console.WriteLine($"Environment variable {ProjectEnvironmentVariable} must be set.");
return 1;
}
// Create client
FirestoreAdminClient client = FirestoreAdminClient.Create();
// Initialize request argument
ParentName parentName = new ParentName(projectId, "(default)", "collection");
// Call API method
var indexes = client.ListIndexes(parentName);
// Show the result
foreach (var index in indexes)
{
Console.WriteLine(index);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
| // Copyright 2019 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 System;
namespace Google.Cloud.Firestore.Admin.V1.SmokeTests
{
public sealed class FirestoreAdminSmokeTest
{
private const string ProjectEnvironmentVariable = "FIRESTORE_TEST_PROJECT";
public static int Main(string[] args)
{
string projectId = Environment.GetEnvironmentVariable(ProjectEnvironmentVariable);
if (string.IsNullOrEmpty(projectId))
{
Console.WriteLine($"Environment variable {ProjectEnvironmentVariable} must be set.");
return 1;
}
// Create client
FirestoreAdminClient client = FirestoreAdminClient.Create();
// Initialize request argument
CollectionGroupName collectionGroupName = CollectionGroupName.FromProjectDatabaseCollection(projectId, "(default)", "collection");
// Call API method
var indexes = client.ListIndexes(collectionGroupName);
// Show the result
foreach (var index in indexes)
{
Console.WriteLine(index);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
|
Add non-complete boss controller script | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouthOfEvilController : MonoBehaviour {
public List<EvilEyeScript> evilEyes;
public int mouthOfEvilHealth = 12;
private int hitsLeftInPhase;
public int maxHitsPerPhase = 4;
public bool isInPhase = false;
void Awake () {
foreach(EvilEyeScript eye in evilEyes){
eye.isActive = false;
}
hitsLeftInPhase = 4;
isInPhase = false;
}
// Update is called once per frame
void Update () {
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouthOfEvilController : MonoBehaviour {
public List<EvilEyeScript> evilEyes;
public int mouthOfEvilHealth = 12;
private int hitsLeftInPhase;
public int maxHitsPerPhase = 4;
public bool isInPhase = false;
public int totalPhases;
public int currentPhase;
public bool isBossFightActive = false;
void Awake () {
foreach(EvilEyeScript eye in evilEyes){
eye.isActive = false;
}
hitsLeftInPhase = 4;
isInPhase = false;
}
// Update is called once per frame
void Update () {
if(isBossFightActive){
if(hitsLeftInPhase <= 0){
IteratePhase();
}
}
}
private void IteratePhase(){
currentPhase++;
return;
}
//stolen from: https://forum.unity.com/threads/make-a-sprite-flash.224086/
IEnumerator FlashSprites(SpriteRenderer[] sprites, int numTimes, float delay, bool disable = false) {
// number of times to loop
for (int loop = 0; loop < numTimes; loop++) {
// cycle through all sprites
for (int i = 0; i < sprites.Length; i++) {
if (disable) {
// for disabling
sprites[i].enabled = false;
} else {
// for changing the alpha
sprites[i].color = new Color(sprites[i].color.r, sprites[i].color.g, sprites[i].color.b, 0.5f);
}
}
// delay specified amount
yield return new WaitForSeconds(delay);
// cycle through all sprites
for (int i = 0; i < sprites.Length; i++) {
if (disable) {
// for disabling
sprites[i].enabled = true;
} else {
// for changing the alpha
sprites[i].color = new Color(sprites[i].color.r, sprites[i].color.g, sprites[i].color.b, 1);
}
}
// delay specified amount
yield return new WaitForSeconds(delay);
}
}
}
|
Improve the interface documentation for the attribute | using System;
namespace PropertyChanged
{
/// <summary>
/// Include a <see cref="Type"/> for notification.
/// The INotifyPropertyChanged interface is added to the type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ImplementPropertyChangedAttribute : Attribute
{
}
} | using System;
namespace PropertyChanged
{
/// <summary>
/// Specifies that PropertyChanged Notification will be added to a class.
/// PropertyChanged.Fody will weave the <c>INotifyPropertyChanged</c> interface and implementation into the class.
/// When the value of a property changes, the PropertyChanged notification will be raised automatically
/// See https://github.com/Fody/PropertyChanged for more information.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ImplementPropertyChangedAttribute : Attribute
{
}
}
|
Return object from Dump/Inspect extension methods. | using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Dump<T>(this T value) {
value.Inspect(title: "Dump");
}
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
| using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value)
=> value.Inspect(title: "Dump");
public static T Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
return value;
}
}
|
Initialize AppConfigCommand with an IApplicationConfiguration | using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
public AddConfigCommand()
{
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
public AddConfigCommand(IApplicationConfiguration applicationConfiguration)
{
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
|
Change automapper to whitelist classes rather than blacklist enums. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Mapping;
namespace FluentNHibernate.AutoMap
{
public class AutoMapper
{
private readonly List<IAutoMapper> _mappingRules;
public AutoMapper(Conventions conventions)
{
_mappingRules = new List<IAutoMapper>
{
new AutoMapIdentity(conventions),
new AutoMapVersion(conventions),
new AutoMapColumn(conventions),
new AutoMapManyToOne(conventions),
new AutoMapOneToMany(conventions),
};
}
public AutoMap<T> MergeMap<T>(AutoMap<T> map)
{
foreach (var property in typeof(T).GetProperties())
{
if (!property.PropertyType.IsEnum)
{
foreach (var rule in _mappingRules)
{
if (rule.MapsProperty(property))
{
if (map.PropertiesMapped.Count(p => p.Name == property.Name) == 0)
{
rule.Map(map, property);
break;
}
}
}
}
}
return map;
}
public AutoMap<T> Map<T>()
{
var classMap = (AutoMap<T>)Activator.CreateInstance(typeof(AutoMap<T>));
return MergeMap(classMap);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Mapping;
namespace FluentNHibernate.AutoMap
{
public class AutoMapper
{
private readonly List<IAutoMapper> _mappingRules;
public AutoMapper(Conventions conventions)
{
_mappingRules = new List<IAutoMapper>
{
new AutoMapIdentity(conventions),
new AutoMapVersion(conventions),
new AutoMapColumn(conventions),
new AutoMapManyToOne(conventions),
new AutoMapOneToMany(conventions),
};
}
public AutoMap<T> MergeMap<T>(AutoMap<T> map)
{
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType.IsClass)
{
foreach (var rule in _mappingRules)
{
if (rule.MapsProperty(property))
{
if (map.PropertiesMapped.Count(p => p.Name == property.Name) == 0)
{
rule.Map(map, property);
break;
}
}
}
}
}
return map;
}
public AutoMap<T> Map<T>()
{
var classMap = (AutoMap<T>)Activator.CreateInstance(typeof(AutoMap<T>));
return MergeMap(classMap);
}
}
} |
Restructure to start implementing category based pool. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _prefab;
private Stack<GameObject> _pool;
public GameObject prefab
{
set {
_prefab = value;
}
}
//TODO: Add possibility to differentiate between prefabs
public GameObject GetGameObject()
{
if (_pool != null)
{
if (_pool.Count > 0)
return _pool.Pop();
else
return GameObject.Instantiate<GameObject>(_prefab);
}
else
{
_pool = new Stack<GameObject>();
return GameObject.Instantiate<GameObject>(_prefab);
}
}
public void Put(GameObject obj)
{
if (_pool == null)
_pool = new Stack<GameObject>();
_pool.Push(obj);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _defaultPrefab;
#region Public methods and properties
public GameObject defaultPrefab
{
set
{
_defaultPrefab = value;
}
}
//TODO: Add possibility to differentiate between prefabs
public AudioObject GetFreeAudioObject(GameObject prefab = null)
{
return null;
}
#endregion
}
[System.Serializable]
public class PrefabBasedPool
{
public GameObject prefab;
public List<AudioObject> audioObjects;
}
|
Change default configuration file name. | using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Mono.Options;
namespace Menora
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
var config = "TempConfig.json";
var help = false;
var minimize = false;
var optionSet = new OptionSet();
optionSet
.Add("c=|config=", "Change configuration file path", (v) => config = v)
.Add("m|minimize", "Start minimized", (v) => minimize = true)
.Add("h|help", "Display help and exit", (v) => help = true)
.Parse(args);
if (help)
{
using (var writer = new StringWriter())
{
writer.WriteLine(Application.ProductName);
writer.WriteLine();
optionSet.WriteOptionDescriptions(writer);
MessageBox.Show(writer.ToString(), Application.ProductName);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(config, minimize));
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Mono.Options;
namespace Menora
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
var config = "Menora.json";
var help = false;
var minimize = false;
var optionSet = new OptionSet();
optionSet
.Add("c=|config=", "Change configuration file path", (v) => config = v)
.Add("m|minimize", "Start minimized", (v) => minimize = true)
.Add("h|help", "Display help and exit", (v) => help = true)
.Parse(args);
if (help)
{
using (var writer = new StringWriter())
{
writer.WriteLine(Application.ProductName);
writer.WriteLine();
optionSet.WriteOptionDescriptions(writer);
MessageBox.Show(writer.ToString(), Application.ProductName);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(config, minimize));
}
}
}
|
Remove unnecessary using and comment. | namespace Playground.Leetcode
{
using System;
using System.Collections.Generic;
public static class CombinationSum
{
// Problem number 377. https://leetcode.com/problems/combination-sum-iv/
public static int CombinationSum4(int[] nums, int target)
{
//Array.Sort(nums);
var count = 0;
var countOfInterimSums = new Dictionary<int, int>();
count = Helper(nums, target, countOfInterimSums);
return count;
}
private static int Helper(
int[] nums,
int target,
Dictionary<int, int> cache)
{
if (target == 0)
{
return 1;
}
if (cache.ContainsKey(target))
{
return cache[target];
}
var count = 0;
foreach (var n in nums)
{
if (n > target)
{
}
else
{
var innerCount = Helper(nums, target - n, cache);
if (innerCount != 0)
{
count += innerCount;
}
}
}
cache[target] = count;
return count;
}
}
} | namespace Playground.Leetcode
{
using System.Collections.Generic;
public static class CombinationSum
{
// Problem number 377. https://leetcode.com/problems/combination-sum-iv/
public static int CombinationSum4(int[] nums, int target)
{
var count = 0;
var countOfInterimSums = new Dictionary<int, int>();
count = Helper(nums, target, countOfInterimSums);
return count;
}
private static int Helper(
int[] nums,
int target,
Dictionary<int, int> cache)
{
if (target == 0)
{
return 1;
}
if (cache.ContainsKey(target))
{
return cache[target];
}
var count = 0;
foreach (var n in nums)
{
if (n > target)
{
}
else
{
var innerCount = Helper(nums, target - n, cache);
if (innerCount != 0)
{
count += innerCount;
}
}
}
cache[target] = count;
return count;
}
}
} |
Make new exception inherit from known type. Tests ok. | using System;
namespace RepositoryExceptions.Persistence
{
/// <summary>
/// New exception introduced
/// </summary>
public class UserNotFoundException : Exception
{
public UserNotFoundException() : base()
{
}
public UserNotFoundException(string message) : base(message)
{
}
}
}
| using System;
namespace RepositoryExceptions.Persistence
{
/// <summary>
/// New exception introduced
/// </summary>
public class UserNotFoundException : EntityNotFoundException
{
public UserNotFoundException() : base()
{
}
public UserNotFoundException(string message) : base(message)
{
}
}
}
|
Update stripe connect objects based on changes to the API | namespace Paydock_dotnet_sdk.Models
{
public class ChargeRequestStripeConnect : ChargeRequestBase
{
public MetaData meta;
}
public class MetaData
{
public string stripe_direct_account_id;
public string stripe_destination_account_id;
public string stripe_transfer_group;
public Transfer[] stripe_transfer;
}
public class Transfer
{
public decimal amount;
public string currency;
public string destination;
}
} | namespace Paydock_dotnet_sdk.Models
{
public class ChargeRequestStripeConnect : ChargeRequestBase
{
public MetaData meta;
public Transfer[] transfer;
}
public class MetaData
{
public string stripe_direct_account_id;
public decimal stripe_application_fee;
public string stripe_destination_account_id;
public decimal stripe_destination_amount;
}
public class Transfer
{
public string stripe_transfer_group;
public TransferItems[] items;
public class TransferItems
{
public decimal amount;
public string currency;
public string destination;
}
}
} |
Add AppendEncoded to the builder | // 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.
namespace Microsoft.AspNet.Html.Abstractions
{
/// <summary>
/// A builder for HTML content.
/// </summary>
public interface IHtmlContentBuilder : IHtmlContent
{
/// <summary>
/// Appends an <see cref="IHtmlContent"/> instance.
/// </summary>
/// <param name="content">The <see cref="IHtmlContent"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(IHtmlContent content);
/// <summary>
/// Appends a <see cref="string"/> value. The value is treated as unencoded as-provided, and will be HTML
/// encoded before writing to output.
/// </summary>
/// <param name="content">The <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(string unencoded);
/// <summary>
/// Clears the content.
/// </summary>
void Clear();
}
}
| // 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.
namespace Microsoft.AspNet.Html.Abstractions
{
/// <summary>
/// A builder for HTML content.
/// </summary>
public interface IHtmlContentBuilder : IHtmlContent
{
/// <summary>
/// Appends an <see cref="IHtmlContent"/> instance.
/// </summary>
/// <param name="content">The <see cref="IHtmlContent"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(IHtmlContent content);
/// <summary>
/// Appends a <see cref="string"/> value. The value is treated as unencoded as-provided, and will be HTML
/// encoded before writing to output.
/// </summary>
/// <param name="content">The <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(string unencoded);
/// <summary>
/// Appends an HTML encoded <see cref="string"/> value. The value is treated as HTML encoded as-provided, and
/// no further encoding will be performed.
/// </summary>
/// <param name="content">The HTML encoded <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder AppendEncoded(string encoded);
/// <summary>
/// Clears the content.
/// </summary>
void Clear();
}
}
|
Return name of channel so we can subscribe to it | using SOVND.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SOVND.Client.Views
{
/// <summary>
/// Interaction logic for NewChannel.xaml
/// </summary>
public partial class NewChannel : Window
{
public NewChannel()
{
InitializeComponent();
DataContext = new NewChannelViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(((NewChannelViewModel) DataContext).Register())
this.Close();
}
}
}
| using SOVND.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SOVND.Client.Views
{
/// <summary>
/// Interaction logic for NewChannel.xaml
/// </summary>
public partial class NewChannel : Window
{
public string ChannelName { get; private set; }
public NewChannel()
{
InitializeComponent();
DataContext = new NewChannelViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (((NewChannelViewModel) DataContext).Register())
{
ChannelName = ((NewChannelViewModel) DataContext).Name;
this.Close();
}
}
}
}
|
Fix bug in GitHub backend | namespace Downlink.GitHub
{
public class GitHubCredentials
{
public GitHubCredentials(string apiToken, string repoId)
{
Token = apiToken;
var segs = repoId.Split('/');
if (segs.Length != 2) throw new System.InvalidOperationException("Could not parse repository name");
Owner = segs[0];
Repo = segs[1];
}
public string Owner { get; }
public string Repo { get; }
public string Token { get; }
}
}
| namespace Downlink.GitHub
{
public class GitHubCredentials
{
public GitHubCredentials(string apiToken, string repoId)
{
Token = apiToken;
var segs = repoId.Split('/');
if (segs.Length != 0) return;
if (segs.Length != 2) throw new System.InvalidOperationException("Could not parse repository name");
Owner = segs[0];
Repo = segs[1];
}
public string Owner { get; }
public string Repo { get; }
public string Token { get; }
}
}
|
Add author to assembly properties | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Obvs.RabbitMQ")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Obvs.RabbitMQ")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1712ac7-e84e-400d-9cbb-c3b8945377c6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Obvs.RabbitMQ")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Christopher Read")]
[assembly: AssemblyProduct("Obvs.RabbitMQ")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1712ac7-e84e-400d-9cbb-c3b8945377c6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Use command line args when configuring the server | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace AspNetCoreMvc
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace AspNetCoreMvc
{
public class Program
{
public static void Main (string[] args)
{
BuildWebHost (args).Run ();
}
public static IWebHost BuildWebHost (string[] args) =>
WebHost.CreateDefaultBuilder (args)
.UseConfiguration (new ConfigurationBuilder ().AddCommandLine (args).Build ())
.UseStartup<Startup> ()
.Build ();
}
}
|
Add methods for opening and closing PSX handle | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSXFinder
{
public static Process FindPSX()
{
Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSXFinder
{
public static Process FindPSX()
{
Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
return psx;
}
public static IntPtr OpenPSX(Process psx)
{
int PID = psx.Id;
IntPtr psxHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);
}
public static void ClosePSX(IntPtr processHandle)
{
int result = Memory.CloseHandle(processHandle);
if (result == 0)
{
Console.WriteLine("ERROR: Could not close psx handle");
}
}
}
}
|
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.Moq 3.0.1")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.Moq 3.0.1")]
|
Resolve a problem with Obsolete controller | using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;
namespace Blogifier.Core.Services
{
public class MailKitService : IEmailService
{
private readonly IDataService _db;
public MailKitService(IDataService db)
{
_db = db;
}
public async Task<string> SendEmail(string fromName, string fromEmail, string toEmail, string subject, string content)
{
try
{
var mailKit = await _db.CustomFields.GetMailKitModel();
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromEmail));
message.To.Add(new MailboxAddress(toEmail));
message.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = content;
message.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(mailKit.EmailServer, mailKit.Port, mailKit.Options);
client.Authenticate(mailKit.EmailAddress, mailKit.EmailPassword);
client.Send(message);
client.Disconnect(true);
return await Task.FromResult("");
}
catch (Exception ex)
{
return await Task.FromResult(ex.Message);
}
}
}
}
| using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;
namespace Blogifier.Core.Services
{
public class MailKitService : IEmailService
{
private readonly IDataService _db;
public MailKitService(IDataService db)
{
_db = db;
}
public async Task<string> SendEmail(string fromName, string fromEmail, string toEmail, string subject, string content)
{
try
{
var mailKit = await _db.CustomFields.GetMailKitModel();
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromEmail));
message.To.Add(new MailboxAddress(fromName, toEmail));
message.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = content;
message.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(mailKit.EmailServer, mailKit.Port, mailKit.Options);
client.Authenticate(mailKit.EmailAddress, mailKit.EmailPassword);
client.Send(message);
client.Disconnect(true);
return await Task.FromResult("");
}
catch (Exception ex)
{
return await Task.FromResult(ex.Message);
}
}
}
}
|
Rework models for global domains | using System;
using Bit.Core.Domains;
using System.Collections.Generic;
using Newtonsoft.Json;
using Bit.Core.Enums;
namespace Bit.Api.Models
{
public class DomainsResponseModel : ResponseModel
{
public DomainsResponseModel(User user)
: base("domains")
{
if(user == null)
{
throw new ArgumentNullException(nameof(user));
}
EquivalentDomains = user.EquivalentDomains != null ?
JsonConvert.DeserializeObject<List<List<string>>>(user.EquivalentDomains) : null;
GlobalEquivalentDomains = Core.Utilities.EquivalentDomains.Global;
ExcludedGlobalEquivalentDomains = user.ExcludedGlobalEquivalentDomains != null ?
JsonConvert.DeserializeObject<List<GlobalEquivalentDomainsType>>(user.ExcludedGlobalEquivalentDomains) : null;
}
public IEnumerable<IEnumerable<string>> EquivalentDomains { get; set; }
public IDictionary<GlobalEquivalentDomainsType, IEnumerable<string>> GlobalEquivalentDomains { get; set; }
public IEnumerable<GlobalEquivalentDomainsType> ExcludedGlobalEquivalentDomains { get; set; }
}
}
| using System;
using Bit.Core.Domains;
using System.Collections.Generic;
using Newtonsoft.Json;
using Bit.Core.Enums;
using System.Linq;
namespace Bit.Api.Models
{
public class DomainsResponseModel : ResponseModel
{
public DomainsResponseModel(User user)
: base("domains")
{
if(user == null)
{
throw new ArgumentNullException(nameof(user));
}
EquivalentDomains = user.EquivalentDomains != null ?
JsonConvert.DeserializeObject<List<List<string>>>(user.EquivalentDomains) : null;
var excludedGlobalEquivalentDomains = user.ExcludedGlobalEquivalentDomains != null ?
JsonConvert.DeserializeObject<List<GlobalEquivalentDomainsType>>(user.ExcludedGlobalEquivalentDomains) : null;
var globalDomains = new List<GlobalDomains>();
foreach(var domain in Core.Utilities.EquivalentDomains.Global)
{
globalDomains.Add(new GlobalDomains(domain.Key, domain.Value, excludedGlobalEquivalentDomains));
}
GlobalEquivalentDomains = !globalDomains.Any() ? null : globalDomains;
}
public IEnumerable<IEnumerable<string>> EquivalentDomains { get; set; }
public IEnumerable<GlobalDomains> GlobalEquivalentDomains { get; set; }
public class GlobalDomains
{
public GlobalDomains(
GlobalEquivalentDomainsType globalDomain,
IEnumerable<string> domains,
IEnumerable<GlobalEquivalentDomainsType> excludedDomains)
{
Type = globalDomain;
Domains = domains;
Excluded = excludedDomains?.Contains(globalDomain) ?? false;
}
public GlobalEquivalentDomainsType Type { get; set; }
public IEnumerable<string> Domains { get; set; }
public bool Excluded { get; set; }
}
}
}
|
Update comments on test extensions | namespace CertiPay.Common.Testing
{
using ApprovalTests;
using Newtonsoft.Json;
using Ploeh.AutoFixture;
public static class TestExtensions
{
private static readonly Fixture _fixture = new Fixture { };
/// <summary>
/// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
/// </summary>
public static void VerifyMe(this object obj)
{
var json = JsonConvert.SerializeObject(obj);
Approvals.VerifyJson(json);
}
public static T AutoGenerate<T>()
{
return _fixture.Create<T>();
}
}
} | namespace CertiPay.Common.Testing
{
using ApprovalTests;
using Newtonsoft.Json;
using Ploeh.AutoFixture;
public static class TestExtensions
{
private static readonly Fixture _fixture = new Fixture { };
/// <summary>
/// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
/// </summary>
public static void VerifyMe(this object obj)
{
var json = JsonConvert.SerializeObject(obj);
Approvals.VerifyJson(json);
}
/// <summary>
/// Returns an auto-initialized instance of the type T, filled via mock
/// data via AutoFixture.
///
/// This will not work for interfaces, only concrete types.
/// </summary>
public static T AutoGenerate<T>()
{
return _fixture.Create<T>();
}
}
} |
Use interfaces instead of concrete types in file definition | using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDocs.Common.Contract.Service
{
public interface IPageExtractor
{
IEnumerable<string> SupportedExtensions { get; }
Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
}
public class PageExtractorList : IPageExtractor
{
private readonly List<IPageExtractor> extractors;
public PageExtractorList(IEnumerable<IPageExtractor> extractors)
{
this.extractors = extractors.ToList();
}
public IEnumerable<string> SupportedExtensions
{
get { return extractors.SelectMany(e => e.SupportedExtensions); }
}
public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
{
var extension = Path.GetExtension(file.Name);
return await extractors
.Single(e => e.SupportedExtensions.Contains(extension))
.ExtractPages(file, document);
}
}
}
| using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDocs.Common.Contract.Service
{
public interface IPageExtractor
{
IEnumerable<string> SupportedExtensions { get; }
Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
}
public class PageExtractorList : IPageExtractor
{
private readonly IList<IPageExtractor> extractors;
public PageExtractorList(IEnumerable<IPageExtractor> extractors)
{
this.extractors = extractors.ToList();
}
public IEnumerable<string> SupportedExtensions
{
get { return extractors.SelectMany(e => e.SupportedExtensions); }
}
public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
{
var extension = Path.GetExtension(file.Name);
return await extractors
.Single(e => e.SupportedExtensions.Contains(extension))
.ExtractPages(file, document);
}
}
}
|
Adjust rule for Age Calc. | using System;
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
public static DateTime Yesterday(this DateTime date)
{
return date.AddDays(-1);
}
public static int Age(this DateTime date)
{
var now = DateTime.Now;
var age = now.Year - date.Year;
if (now.Month > date.Month || (now.Month == date.Month && now.Day < date.Month))
age -= 1;
return age;
}
public static int AgeInDays(this DateTime date)
{
TimeSpan ts = DateTime.Now - date;
return ts.Duration().Days;
}
}
}
| using System;
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
public static DateTime Yesterday(this DateTime date)
{
return date.AddDays(-1);
}
public static int Age(this DateTime date)
{
var now = DateTime.Now;
var age = now.Year - date.Year;
if (now.Month > date.Month || (now.Month == date.Month && now.Day <= date.Day))
age -= 1;
return age;
}
public static int AgeInDays(this DateTime date)
{
TimeSpan ts = DateTime.Now - date;
return ts.Duration().Days;
}
}
}
|
Fix safety measures. Destroy missing. | using UnityEngine;
using System.Collections;
public class TriggerDestroy : MonoBehaviour
{
public Transform owner;
public float ensureDestroyAfter = 5f;
void Update()
{
ensureDestroyAfter -= Time.deltaTime;
}
void OnTriggerEnter(Collider other)
{
if (other.transform.name != owner.name)
{
return;
}
Destroy(gameObject);
}
}
| using UnityEngine;
using System.Collections;
public class TriggerDestroy : MonoBehaviour
{
public Transform owner;
public float ensureDestroyAfter = 2f;
void Update()
{
ensureDestroyAfter -= Time.deltaTime;
if (ensureDestroyAfter <= 0) {
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.name != owner.name)
{
return;
}
Destroy(gameObject);
}
}
|
Improve accuracy of IsBackingField extension method. | #region Apache License 2.0
// Copyright 2015 Thaddeus Ryker
//
// 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.
#endregion
using System;
using System.Reflection;
using Fasterflect;
namespace Org.Edgerunner.DotSerialize.Utilities
{
public static class FieldInfoExtensions
{
#region Static Methods
public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (!string.IsNullOrEmpty(propertyName))
return info.DeclaringType.Property(propertyName);
return null;
}
public static bool IsBackingField(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
return !string.IsNullOrEmpty(propertyName);
}
#endregion
}
} | #region Apache License 2.0
// Copyright 2015 Thaddeus Ryker
//
// 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.
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Fasterflect;
namespace Org.Edgerunner.DotSerialize.Utilities
{
public static class FieldInfoExtensions
{
#region Static Methods
public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (!string.IsNullOrEmpty(propertyName))
return info.DeclaringType.Property(propertyName);
return null;
}
public static bool IsBackingField(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (string.IsNullOrEmpty(propertyName))
return false;
return info.HasAttribute<CompilerGeneratedAttribute>();
}
#endregion
}
} |
Use StringBuilderResultStore in the console application | using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;
namespace TheTesst
{
class Program
{
static void Main(string[] args)
{
var formatter = new DefaultPrinterFormatter(() => new FileResultStore(), new NumberToWord(), new FizzBuzz());
var printer = new ConsolePrinter();
var cruncher = new Cruncher(formatter, printer);
var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };
cruncher.Execute(data);
Console.ReadLine();
}
}
} | using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;
namespace TheTesst
{
class Program
{
static void Main(string[] args)
{
var formatter = new DefaultPrinterFormatter(() => new StringBuilderResultStore(), new NumberToWord(), new FizzBuzz());
var printer = new ConsolePrinter();
var cruncher = new Cruncher(formatter, printer);
var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };
cruncher.Execute(data);
Console.ReadLine();
}
}
}
|
Add xml documentation to moya exceptions | namespace Moya.Exceptions
{
using System;
public class MoyaException : Exception
{
public MoyaException(String message) : base(message)
{
}
}
} | namespace Moya.Exceptions
{
using System;
/// <summary>
/// Represents errors that occur during execution of Moya.
/// </summary>
public class MoyaException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MoyaException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">A message describing the error.</param>
public MoyaException(String message) : base(message)
{
}
}
} |
Work around faulty StatusStrip implementations | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace ExtendedControls
{
public class StatusStripCustom : StatusStrip
{
public const int WM_NCHITTEST = 0x84;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int HT_CLIENT = 0x1;
public const int HT_BOTTOMRIGHT = 0x11;
public const int HT_TRANSPARENT = -1;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace ExtendedControls
{
public class StatusStripCustom : StatusStrip
{
public const int WM_NCHITTEST = 0x84;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int HT_CLIENT = 0x1;
public const int HT_BOTTOMRIGHT = 0x11;
public const int HT_TRANSPARENT = -1;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
{
if ((int)m.Result == HT_BOTTOMRIGHT)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
else if ((int)m.Result == HT_CLIENT)
{
// Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT
int x = unchecked((short)((uint)m.LParam & 0xFFFF));
int y = unchecked((short)((uint)m.LParam >> 16));
Point p = PointToClient(new Point(x, y));
if (p.X >= this.ClientSize.Width - this.ClientSize.Height)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
}
}
}
}
}
|
Add find first or default | namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
public interface IRepository<T> : IEnumerable<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
}
}
| namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
public interface IRepository<T> : IEnumerable<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
T FindFirstOrDefault(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
}
}
|
Set tabs on Android to be on the bottom | using MobileKidsIdApp.ViewModels;
using Xamarin.Forms;
namespace MobileKidsIdApp.Views
{
public class MainPage : TabbedPage
{
private ApplicationBase CurrentApp => Application.Current as ApplicationBase;
public MainPage()
{
Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;
if (childListPage is NavigationPage childNavPage)
{
childNavPage.Title = "My Kids";
// TODO: set icon
}
if (instructionsPage is NavigationPage instructionNavPage)
{
instructionNavPage.Title = "Content";
// TODO: set icon
}
Children.Add(childListPage);
Children.Add(instructionsPage);
// TODO: Add "logout" ability
}
}
}
| using MobileKidsIdApp.ViewModels;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
namespace MobileKidsIdApp.Views
{
public class MainPage : Xamarin.Forms.TabbedPage
{
private ApplicationBase CurrentApp => Xamarin.Forms.Application.Current as ApplicationBase;
public MainPage()
{
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
Xamarin.Forms.Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
Xamarin.Forms.Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;
if (childListPage is Xamarin.Forms.NavigationPage childNavPage)
{
childNavPage.Title = "My Kids";
// TODO: set icon
}
if (instructionsPage is Xamarin.Forms.NavigationPage instructionNavPage)
{
instructionNavPage.Title = "Content";
// TODO: set icon
}
Children.Add(childListPage);
Children.Add(instructionsPage);
// TODO: Add "logout" ability
}
}
}
|
Add Request Authorizer to master request runtime | using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
// TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
} | using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
private readonly IDiscoverableCollection<IRequestAuthorizer> _requestAuthorizers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
// TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
_requestAuthorizers = serviceProvider.GetService<IDiscoverableCollection<IRequestAuthorizer>>();
_requestAuthorizers.Discover();
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public bool Authorized(IHttpContext context)
{
foreach (var requestAuthorizer in _requestAuthorizers)
{
var allowed = requestAuthorizer.AllowUser(context);
if (!allowed)
{
return false;
}
}
return true;
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
} |
Use Unix line feed for score exportation. | using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;
namespace DereTore.Applications.StarlightDirector.Entities {
public sealed class CompiledScore {
public CompiledScore() {
Notes = new InternalList<CompiledNote>();
}
public InternalList<CompiledNote> Notes { get; }
public string GetCsvString() {
var tempFileName = Path.GetTempFileName();
using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
var config = new CsvConfiguration();
config.RegisterClassMap<ScoreCsvMap>();
config.HasHeaderRecord = true;
config.TrimFields = false;
using (var csv = new CsvWriter(writer, config)) {
var newList = new List<CompiledNote>(Notes);
newList.Sort(CompiledNote.IDComparison);
csv.WriteRecords(newList);
}
}
}
// BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
var text = File.ReadAllText(tempFileName, Encoding.UTF8);
File.Delete(tempFileName);
return text;
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;
namespace DereTore.Applications.StarlightDirector.Entities {
public sealed class CompiledScore {
public CompiledScore() {
Notes = new InternalList<CompiledNote>();
}
public InternalList<CompiledNote> Notes { get; }
public string GetCsvString() {
var tempFileName = Path.GetTempFileName();
using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
var config = new CsvConfiguration();
config.RegisterClassMap<ScoreCsvMap>();
config.HasHeaderRecord = true;
config.TrimFields = false;
using (var csv = new CsvWriter(writer, config)) {
var newList = new List<CompiledNote>(Notes);
newList.Sort(CompiledNote.IDComparison);
csv.WriteRecords(newList);
}
}
}
// BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
var text = File.ReadAllText(tempFileName, Encoding.UTF8);
text = text.Replace("\r\n", "\n");
File.Delete(tempFileName);
return text;
}
}
}
|
Stop errors if invalid plugboard settings and inputted into the constructor The constructor would throw errors if the length of a string in the string array of settings was of length 1 or 0. Now it only adds plug settings with a length of 2 or above | // Plugboard.cs
// <copyright file="Plugboard.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;
namespace EnigmaUtilities.Components
{
/// <summary>
/// An implementation of the plug board component for the enigma machine.
/// </summary>
public class Plugboard : Component
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugboard" /> class.
/// </summary>
/// <param name="plugs"> The plugs to be used. </param>
public Plugboard(string[] plugs)
{
// Turn each plug connection into an encryption element in the dictionary
this.EncryptionKeys = new Dictionary<char, char>();
foreach (string plug in plugs)
{
// Add both ways round so its not required to look backwards across the plugboard during the encryption
this.EncryptionKeys.Add(plug[0], plug[1]);
this.EncryptionKeys.Add(plug[1], plug[0]);
}
}
/// <summary>
/// Encrypts a letter with the current plug board settings.
/// </summary>
/// <param name="c"> The character to encrypt. </param>
/// <returns> The encrypted character. </returns>
public override char Encrypt(char c)
{
return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
}
}
}
| // Plugboard.cs
// <copyright file="Plugboard.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;
namespace EnigmaUtilities.Components
{
/// <summary>
/// An implementation of the plug board component for the enigma machine.
/// </summary>
public class Plugboard : Component
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugboard" /> class.
/// </summary>
/// <param name="plugs"> The plugs to be used. </param>
public Plugboard(string[] plugs)
{
// Turn each plug connection into an encryption element in the dictionary
this.EncryptionKeys = new Dictionary<char, char>();
foreach (string plug in plugs)
{
// Only add to plugboard if its and length that won't create errors (2 or above)
if (plug.Length >= 2)
{
// Add both ways round so its not required to look backwards across the plugboard during the encryption
this.EncryptionKeys.Add(plug[0], plug[1]);
this.EncryptionKeys.Add(plug[1], plug[0]);
}
}
}
/// <summary>
/// Encrypts a letter with the current plug board settings.
/// </summary>
/// <param name="c"> The character to encrypt. </param>
/// <returns> The encrypted character. </returns>
public override char Encrypt(char c)
{
return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
}
}
}
|
Improve exception report to also get inner exceptions if possible | using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace Daisy.SaveAsDAISY.Addins.Word2007 {
public partial class ExceptionReport : Form {
private Exception ExceptionRaised { get; }
public ExceptionReport(Exception raised) {
InitializeComponent();
this.ExceptionRaised = raised;
this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
}
private void SendReport_Click(object sender, EventArgs e) {
StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
message.AppendLine(this.ExceptionRaised.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
string mailto = string.Format(
"mailto:{0}?Subject={1}&Body={2}",
"daisy-pipeline@mail.daisy.org",
"Unhandled exception report in the SaveAsDAISY addin",
message.ToString()
);
mailto = Uri.EscapeUriString(mailto);
//MessageBox.Show(message.ToString());
Process.Start(mailto);
}
}
}
| using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace Daisy.SaveAsDAISY.Addins.Word2007 {
public partial class ExceptionReport : Form {
private Exception ExceptionRaised { get; }
public ExceptionReport(Exception raised) {
InitializeComponent();
this.ExceptionRaised = raised;
this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
}
private void SendReport_Click(object sender, EventArgs evt) {
StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
message.AppendLine(this.ExceptionRaised.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
Exception e = ExceptionRaised;
while (e.InnerException != null) {
e = e.InnerException;
message.AppendLine(" - Inner exception : " + e.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
}
string mailto = string.Format(
"mailto:{0}?Subject={1}&Body={2}",
"daisy-pipeline@mail.daisy.org",
"Unhandled exception report in the SaveAsDAISY addin",
message.ToString()
);
mailto = Uri.EscapeUriString(mailto);
//MessageBox.Show(message.ToString());
Process.Start(mailto);
}
}
}
|
Fix comparer. Seed node all have NodeId=-99, so need to compare their fields. | using System.Collections.Generic;
namespace kafka4net.Metadata
{
class BrokerMeta
{
public int NodeId;
public string Host;
public int Port;
// Not serialized, just a link to connection associated with this broker
internal Connection Conn;
public override string ToString()
{
return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
}
#region comparer
public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
class ComparerImpl : IEqualityComparer<BrokerMeta>
{
public bool Equals(BrokerMeta x, BrokerMeta y)
{
return x.NodeId == y.NodeId;
}
public int GetHashCode(BrokerMeta obj)
{
return obj.NodeId;
}
}
#endregion
}
}
| using System;
using System.Collections.Generic;
namespace kafka4net.Metadata
{
class BrokerMeta
{
public int NodeId;
public string Host;
public int Port;
// Not serialized, just a link to connection associated with this broker
internal Connection Conn;
public override string ToString()
{
return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
}
#region comparer
public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
class ComparerImpl : IEqualityComparer<BrokerMeta>
{
public bool Equals(BrokerMeta x, BrokerMeta y)
{
if(x.NodeId != -99 || y.NodeId != -99)
return x.NodeId == y.NodeId;
// If those are non-resolved seed brokers, do property comparison, because they all have NodeId==-99
return string.Equals(x.Host, y.Host, StringComparison.OrdinalIgnoreCase) && x.Port == y.Port;
}
public int GetHashCode(BrokerMeta obj)
{
return obj.NodeId;
}
}
#endregion
}
}
|
Fix the access level on the size and rating structs | using System.Drawing;
public struct FBAdSize {
SizeF size;
}
public struct FBAdStarRating {
float value;
int scale;
}
| using System.Drawing;
public struct FBAdSize {
public SizeF size;
}
public struct FBAdStarRating {
public float value;
public int scale;
}
|
Add Bigsby Jobs was here | using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
Console.WriteLine("Bigsby Gates was here!");
Console.WriteLine("Bigsby Trovalds was here!");
}
}
}
| using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
Console.WriteLine("Bigsby Gates was here!");
Console.WriteLine("Bigsby Trovalds was here!");
Console.WriteLine("Bigsby Jobs was here!");
}
}
}
|
Change IntervalReached event to contain duration position. | using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public class IntervalReachedEventArgs : EventArgs
{
public String Message { get; set; }
public IntervalReachedEventArgs(String message)
{
Message = message;
}
}
}
| using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public class IntervalReachedEventArgs : EventArgs
{
public int DurationNumber { get; set; }
public IntervalReachedEventArgs(int durationNumber)
{
DurationNumber = durationNumber;
}
}
}
|
Scale the playfield to avoid off-screen objects | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield
{
[SettingSource("Roll speed", "Speed at which things rotate")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
{
MinValue = 0.1,
MaxValue = 20,
Precision = 0.1,
};
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override double ScoreMultiplier => 1;
public void Update(Playfield playfield)
{
playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
[SettingSource("Roll speed", "Speed at which things rotate")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
{
MinValue = 0.1,
MaxValue = 20,
Precision = 0.1,
};
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override double ScoreMultiplier => 1;
public void Update(Playfield playfield)
{
playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// scale the playfield to allow all hitobjects to stay within the visible region.
drawableRuleset.Playfield.Scale = new Vector2(OsuPlayfield.BASE_SIZE.Y / OsuPlayfield.BASE_SIZE.X);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.