Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove unused ClickMacro controller method | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EndlessClient.HUD
{
public interface IHudButtonController
{
void ClickInventory();
void ClickViewMapToggle();
void ClickActiveSpells();
void ClickPassiveSpells();
void ClickChat();
void ClickStats();
void ClickOnlineList();
void ClickParty();
//void ClickMacro();
void ClickSettings();
void ClickHelp();
//friend/ignore
//E/Q
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EndlessClient.HUD
{
public interface IHudButtonController
{
void ClickInventory();
void ClickViewMapToggle();
void ClickActiveSpells();
void ClickPassiveSpells();
void ClickChat();
void ClickStats();
void ClickOnlineList();
void ClickParty();
void ClickSettings();
void ClickHelp();
//friend/ignore
//E/Q
}
}
|
Fix misnamed LOWFONT enumeration to LOWERFONT | namespace Grobid.NET
{
public enum FontSizeStatus
{
HIGHERFONT,
SAMEFONTSIZE,
LOWFONT,
}
} | namespace Grobid.NET
{
public enum FontSizeStatus
{
HIGHERFONT,
SAMEFONTSIZE,
LOWERFONT,
}
} |
Make the default BrstmTrackType Standard | using DspAdpcm.Adpcm.Formats.Internal;
using DspAdpcm.Adpcm.Formats.Structures;
namespace DspAdpcm.Adpcm.Formats.Configuration
{
/// <summary>
/// Contains the options used to build the BRSTM file.
/// </summary>
public class BrstmConfiguration : B_stmConfiguration
{
/// <summary>
/// The type of track description to be used when building the
/// BRSTM header.
/// Default is <see cref="BrstmTrackType.Short"/>
/// </summary>
public BrstmTrackType TrackType { get; set; } = BrstmTrackType.Short;
/// <summary>
/// The type of seek table to use when building the BRSTM
/// ADPC chunk.
/// Default is <see cref="BrstmSeekTableType.Standard"/>
/// </summary>
public BrstmSeekTableType SeekTableType { get; set; } = BrstmSeekTableType.Standard;
}
}
| using DspAdpcm.Adpcm.Formats.Internal;
using DspAdpcm.Adpcm.Formats.Structures;
namespace DspAdpcm.Adpcm.Formats.Configuration
{
/// <summary>
/// Contains the options used to build the BRSTM file.
/// </summary>
public class BrstmConfiguration : B_stmConfiguration
{
/// <summary>
/// The type of track description to be used when building the
/// BRSTM header.
/// Default is <see cref="BrstmTrackType.Standard"/>
/// </summary>
public BrstmTrackType TrackType { get; set; } = BrstmTrackType.Standard;
/// <summary>
/// The type of seek table to use when building the BRSTM
/// ADPC chunk.
/// Default is <see cref="BrstmSeekTableType.Standard"/>
/// </summary>
public BrstmSeekTableType SeekTableType { get; set; } = BrstmSeekTableType.Standard;
}
}
|
Support server messages in the Image widget | using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerImage : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var resName = (string)args[0];
var widget = new Image(parent.Widget);
widget.Drawable = App.Resources.GetImage(resName);
widget.Resize(widget.Drawable.Size);
return new ServerImage(id, parent, widget);
}
public ServerImage(ushort id, ServerWidget parent, Image widget)
: base(id, parent, widget)
{
}
}
}
| using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerImage : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var resName = (string)args[0];
var widget = new Image(parent.Widget);
widget.Drawable = App.Resources.GetImage(resName);
widget.Resize(widget.Drawable.Size);
return new ServerImage(id, parent, widget);
}
private readonly Image widget;
public ServerImage(ushort id, ServerWidget parent, Image widget)
: base(id, parent, widget)
{
this.widget = widget;
}
public override void ReceiveMessage(string message, object[] args)
{
if (message == "ch")
widget.Drawable = App.Resources.GetImage((string)args[0]);
else
base.ReceiveMessage(message, args);
}
}
}
|
Reduce allocations while maintaining read-only-ness | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Extensions.ListExtensions;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A basic implementation of <see cref="ITextPart"/>,
/// which automatically handles returning correct <see cref="Drawables"/>
/// and raising <see cref="DrawablePartsRecreated"/>.
/// </summary>
public abstract class TextPart : ITextPart
{
public IEnumerable<Drawable> Drawables => drawables.AsSlimReadOnly();
private readonly List<Drawable> drawables = new List<Drawable>();
public event Action<IEnumerable<Drawable>> DrawablePartsRecreated;
public void RecreateDrawablesFor(TextFlowContainer textFlowContainer)
{
drawables.Clear();
drawables.AddRange(CreateDrawablesFor(textFlowContainer));
DrawablePartsRecreated?.Invoke(drawables);
}
/// <summary>
/// Creates drawables representing the contents of this <see cref="TextPart"/>,
/// to be appended to the <paramref name="textFlowContainer"/>.
/// </summary>
protected abstract IEnumerable<Drawable> CreateDrawablesFor(TextFlowContainer textFlowContainer);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A basic implementation of <see cref="ITextPart"/>,
/// which automatically handles returning correct <see cref="Drawables"/>
/// and raising <see cref="DrawablePartsRecreated"/>.
/// </summary>
public abstract class TextPart : ITextPart
{
public IEnumerable<Drawable> Drawables { get; }
public event Action<IEnumerable<Drawable>> DrawablePartsRecreated;
private readonly List<Drawable> drawables = new List<Drawable>();
protected TextPart()
{
Drawables = drawables.AsReadOnly();
}
public void RecreateDrawablesFor(TextFlowContainer textFlowContainer)
{
drawables.Clear();
drawables.AddRange(CreateDrawablesFor(textFlowContainer));
DrawablePartsRecreated?.Invoke(drawables);
}
/// <summary>
/// Creates drawables representing the contents of this <see cref="TextPart"/>,
/// to be appended to the <paramref name="textFlowContainer"/>.
/// </summary>
protected abstract IEnumerable<Drawable> CreateDrawablesFor(TextFlowContainer textFlowContainer);
}
}
|
Fix sync context Run always returns true when it ran something. | using System;
using System.Collections.Generic;
using System.Threading;
namespace Toggl.Phoebe.Tests
{
public class MainThreadSynchronizationContext : SynchronizationContext
{
private readonly Thread thread;
private readonly object syncRoot = new Object ();
private readonly Queue<Job> jobs = new Queue<Job> ();
public MainThreadSynchronizationContext ()
{
thread = Thread.CurrentThread;
}
public bool Run ()
{
int count;
Job job;
lock (syncRoot) {
count = jobs.Count;
if (count < 1)
return false;
job = jobs.Dequeue ();
}
try {
job.Callback (job.State);
} finally {
if (job.OnProcessed != null) {
job.OnProcessed ();
}
}
return count > 1;
}
public override void Post (SendOrPostCallback d, object state)
{
Post (d, state, null);
}
public override void Send (SendOrPostCallback d, object state)
{
if (thread == Thread.CurrentThread) {
d (state);
} else {
// Schedule task and wait for it to complete
var reset = new ManualResetEventSlim ();
Post (d, state, reset.Set);
reset.Wait ();
}
}
private void Post (SendOrPostCallback d, object state, Action completionHandler)
{
lock (syncRoot) {
jobs.Enqueue (new Job () {
Callback = d,
State = state,
OnProcessed = completionHandler,
});
}
}
struct Job
{
public SendOrPostCallback Callback;
public object State;
public Action OnProcessed;
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
namespace Toggl.Phoebe.Tests
{
public class MainThreadSynchronizationContext : SynchronizationContext
{
private readonly Thread thread;
private readonly object syncRoot = new Object ();
private readonly Queue<Job> jobs = new Queue<Job> ();
public MainThreadSynchronizationContext ()
{
thread = Thread.CurrentThread;
}
public bool Run ()
{
Job job;
lock (syncRoot) {
if (jobs.Count < 1)
return false;
job = jobs.Dequeue ();
}
try {
job.Callback (job.State);
} finally {
if (job.OnProcessed != null) {
job.OnProcessed ();
}
}
return true;
}
public override void Post (SendOrPostCallback d, object state)
{
Post (d, state, null);
}
public override void Send (SendOrPostCallback d, object state)
{
if (thread == Thread.CurrentThread) {
d (state);
} else {
// Schedule task and wait for it to complete
var reset = new ManualResetEventSlim ();
Post (d, state, reset.Set);
reset.Wait ();
}
}
private void Post (SendOrPostCallback d, object state, Action completionHandler)
{
lock (syncRoot) {
jobs.Enqueue (new Job () {
Callback = d,
State = state,
OnProcessed = completionHandler,
});
}
}
struct Job
{
public SendOrPostCallback Callback;
public object State;
public Action OnProcessed;
}
}
}
|
Make GameObject.SetEnabled extension method more generic | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
public static class GameObjectUtilities
{
public static void SetEnabled(this GameObject obj, bool enabled)
{
// Disable rendering of this component
obj.GetComponent<MeshRenderer>().enabled = enabled;
// And of its children
var subComponents = obj.GetComponentsInChildren<MeshRenderer>();
foreach (var renderer in subComponents)
{
renderer.enabled = enabled;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
public static class GameObjectUtilities
{
public static void SetEnabled(this GameObject obj, bool enabled)
{
// Disable rendering of this component
obj.GetComponent<Renderer>().enabled = enabled;
// And of its children
var subComponents = obj.GetComponentsInChildren<Renderer>();
foreach (var renderer in subComponents)
{
renderer.enabled = enabled;
}
}
}
}
|
Fix for help blowing up if a module or command lacks a summary | using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace Modix.Modules
{
[Name("Info"), Summary("General helper module")]
public sealed class InfoModule : ModuleBase
{
private CommandService commandService;
public InfoModule(CommandService cs)
{
commandService = cs;
}
[Command("help"), Summary("Prints a neat list of all commands.")]
public async Task HelpAsync()
{
var eb = new EmbedBuilder();
var userDm = await Context.User.GetOrCreateDMChannelAsync();
foreach (var module in commandService.Modules)
{
eb = eb.WithTitle($"Module: {module.Name ?? ""}")
.WithDescription(module.Summary ?? "");
foreach(var command in module.Commands)
{
eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? ""));
}
await userDm.SendMessageAsync(string.Empty, embed: eb.Build());
eb = new EmbedBuilder();
}
await ReplyAsync($"Check your private messages, {Context.User.Mention}");
}
private string GetParams(CommandInfo info)
{
var sb = new StringBuilder();
info.Parameters.ToList().ForEach(x =>
{
if (x.IsOptional)
sb.Append("[Optional(" + x.Name + ")]");
else
sb.Append("[" + x.Name + "]");
});
return sb.ToString();
}
}
}
| using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace Modix.Modules
{
[Name("Info"), Summary("General helper module")]
public sealed class InfoModule : ModuleBase
{
private CommandService commandService;
public InfoModule(CommandService cs)
{
commandService = cs;
}
[Command("help"), Summary("Prints a neat list of all commands.")]
public async Task HelpAsync()
{
var eb = new EmbedBuilder();
var userDm = await Context.User.GetOrCreateDMChannelAsync();
foreach (var module in commandService.Modules)
{
eb = eb.WithTitle($"Module: {module.Name ?? "Unknown"}")
.WithDescription(module.Summary ?? "Unknown");
foreach(var command in module.Commands)
{
eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? "Unknown"));
}
await userDm.SendMessageAsync(string.Empty, embed: eb.Build());
eb = new EmbedBuilder();
}
await ReplyAsync($"Check your private messages, {Context.User.Mention}");
}
private string GetParams(CommandInfo info)
{
var sb = new StringBuilder();
info.Parameters.ToList().ForEach(x =>
{
if (x.IsOptional)
sb.Append("[Optional(" + x.Name + ")]");
else
sb.Append("[" + x.Name + "]");
});
return sb.ToString();
}
}
}
|
Allow properties to be nullable to support V12 databases | using System;
using System.Xml.Linq;
namespace Linq2Azure.SqlDatabases
{
public class Database
{
internal Database(XElement xml, DatabaseServer databaseServer)
{
xml.HydrateObject(XmlNamespaces.WindowsAzure, this);
DatabaseServer = databaseServer;
}
public DatabaseServer DatabaseServer { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string State { get; private set; }
public Uri SelfLink { get; private set; }
public Uri ParentLink { get; private set; }
public int Id { get; private set; }
public string Edition { get; private set; }
public string CollationName { get; private set; }
public DateTimeOffset CreationDate { get; private set; }
public bool IsFederationRoot { get; private set; }
public bool IsSystemObject { get; private set; }
public decimal? SizeMB { get; private set; }
public long MaxSizeBytes { get; private set; }
public Guid ServiceObjectiveId { get; private set; }
public Guid AssignedServiceObjectiveId { get; private set; }
public int ServiceObjectiveAssignmentState { get; private set; }
public string ServiceObjectiveAssignmentStateDescription { get; private set; }
public int ServiceObjectiveAssignmentErrorCode { get; private set; }
public string ServiceObjectiveAssignmentErrorDescription { get; private set; }
public DateTimeOffset ServiceObjectiveAssignmentSuccessDate { get; private set; }
public DateTimeOffset? RecoveryPeriodStartDate { get; private set; }
public bool IsSuspended { get; private set; }
}
} | using System;
using System.Xml.Linq;
namespace Linq2Azure.SqlDatabases
{
public class Database
{
internal Database(XElement xml, DatabaseServer databaseServer)
{
xml.HydrateObject(XmlNamespaces.WindowsAzure, this);
DatabaseServer = databaseServer;
}
public DatabaseServer DatabaseServer { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string State { get; private set; }
public Uri SelfLink { get; private set; }
public Uri ParentLink { get; private set; }
public int Id { get; private set; }
public string Edition { get; private set; }
public string CollationName { get; private set; }
public DateTimeOffset CreationDate { get; private set; }
public bool IsFederationRoot { get; private set; }
public bool IsSystemObject { get; private set; }
public decimal? SizeMB { get; private set; }
public long MaxSizeBytes { get; private set; }
public Guid ServiceObjectiveId { get; private set; }
public Guid AssignedServiceObjectiveId { get; private set; }
public int? ServiceObjectiveAssignmentState { get; private set; }
public string ServiceObjectiveAssignmentStateDescription { get; private set; }
public int ServiceObjectiveAssignmentErrorCode { get; private set; }
public string ServiceObjectiveAssignmentErrorDescription { get; private set; }
public DateTimeOffset? ServiceObjectiveAssignmentSuccessDate { get; private set; }
public DateTimeOffset? RecoveryPeriodStartDate { get; private set; }
public bool IsSuspended { get; private set; }
}
} |
Fix the issue with settings name | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace BoardGamesApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class TempController : Controller
{
private readonly IConfiguration _configuration;
public TempController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[Route("/get-token")]
public IActionResult GenerateToken(string name = "mscommunity")
{
var jwt = JwtTokenGenerator
.Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]);
return Ok(jwt);
}
}
}
| using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace BoardGamesApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class TempController : Controller
{
private readonly IConfiguration _configuration;
public TempController(IConfiguration configuration)
{
_configuration = configuration;
}
[AllowAnonymous]
[Route("/get-token")]
public IActionResult GenerateToken(string name = "mscommunity")
{
var jwt = JwtTokenGenerator
.Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]);
return Ok(jwt);
}
}
}
|
Add textarea, keyboard listener and timer. | @{
ViewBag.Title = "Typing Classifier";
}
<div class="jumbotron">
This will be our awesome typing classifier
</div>
<div class="row">
Typing classifier goes here.
@Html.ActionLink("Go to results", "Results", "Home");
</div> | @{
ViewBag.Title = "Typing Classifier";
}
@section scripts
{
<script type="text/javascript">
'use strict'
var timer = getTimer();
$(function() {
var capturing = false;
document.addEventListener('keydown', function(event) {
if(!capturing) {
capturing = true;
}
});
});
function getTimer() {
if(window.performance.now) {
return function() { return window.performance.now(); };
} else if(window.performance.webkitNow) {
return function() { return window.performance.webkitNot(); }
} else {
return function() { return new Date().getTime(); }
}
}
</script>
}
<div class="jumbotron">
This will be our awesome typing classifier
</div>
<div class="row">
Typing classifier goes here.
<textarea></textarea>
@Html.ActionLink("Go to results", "Results", "Home");
</div> |
Sort snippets in descending order | using System;
using System.Linq;
using System.Web.Mvc;
using Hangfire.Highlighter.Jobs;
using Hangfire.Highlighter.Models;
namespace Hangfire.Highlighter.Controllers
{
public class HomeController : Controller
{
private readonly HighlighterDbContext _db = new HighlighterDbContext();
public ActionResult Index()
{
return View(_db.CodeSnippets.ToList());
}
public ActionResult Details(int id)
{
var snippet = _db.CodeSnippets.Find(id);
return View(snippet);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
{
if (ModelState.IsValid)
{
snippet.CreatedAt = DateTime.UtcNow;
_db.CodeSnippets.Add(snippet);
_db.SaveChanges();
using (StackExchange.Profiling.MiniProfiler.StepStatic("Job enqueue"))
{
// Enqueue a job
BackgroundJob.Enqueue<SnippetHighlighter>(x => x.HighlightAsync(snippet.Id));
}
return RedirectToAction("Details", new { id = snippet.Id });
}
return View(snippet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
} | using System;
using System.Linq;
using System.Web.Mvc;
using Hangfire.Highlighter.Jobs;
using Hangfire.Highlighter.Models;
namespace Hangfire.Highlighter.Controllers
{
public class HomeController : Controller
{
private readonly HighlighterDbContext _db = new HighlighterDbContext();
public ActionResult Index()
{
return View(_db.CodeSnippets.OrderByDescending(x => x.Id).ToList());
}
public ActionResult Details(int id)
{
var snippet = _db.CodeSnippets.Find(id);
return View(snippet);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
{
if (ModelState.IsValid)
{
snippet.CreatedAt = DateTime.UtcNow;
_db.CodeSnippets.Add(snippet);
_db.SaveChanges();
using (StackExchange.Profiling.MiniProfiler.StepStatic("Job enqueue"))
{
// Enqueue a job
BackgroundJob.Enqueue<SnippetHighlighter>(x => x.HighlightAsync(snippet.Id));
}
return RedirectToAction("Details", new { id = snippet.Id });
}
return View(snippet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
} |
Move generating mock data to separate function. | using ProjectCDA.Model;
using ProjectCDA.Model.Constants;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace ProjectCDA.DAL
{
public class DataService : IDataService
{
public IEnumerable<FacingPages> GetData()
{
ObservableCollection<FacingPages> gridData = new ObservableCollection<FacingPages>();
FacingPages pages = new FacingPages();
pages.ID = 0;
pages.Type = FacingPagesTypes.DEFAULT;
gridData.Add(pages);
pages = new FacingPages();
pages.ID = 1;
pages.Type = FacingPagesTypes.NO_HEADER;
gridData.Add(pages);
pages = new FacingPages();
pages.ID = 2;
pages.Type = FacingPagesTypes.SINGLE_PAGE;
gridData.Add(pages);
for (int i = 3; i < 65; i++)
{
pages = new FacingPages();
pages.ID = i;
pages.Type = FacingPagesTypes.DEFAULT;
gridData.Add(pages);
}
return gridData;
}
}
}
| using ProjectCDA.Model;
using ProjectCDA.Model.Constants;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace ProjectCDA.DAL
{
public class DataService : IDataService
{
public IEnumerable<FacingPages> GetData()
{
return GetMockData();
}
public IEnumerable<FacingPages> GetMockData()
{
ObservableCollection<FacingPages> gridData = new ObservableCollection<FacingPages>();
FacingPages pages = new FacingPages();
pages.ID = 0;
pages.Type = FacingPagesTypes.DEFAULT;
gridData.Add(pages);
pages = new FacingPages();
pages.ID = 1;
pages.Type = FacingPagesTypes.NO_HEADER;
gridData.Add(pages);
pages = new FacingPages();
pages.ID = 2;
pages.Type = FacingPagesTypes.SINGLE_PAGE;
gridData.Add(pages);
for (int i = 3; i < 65; i++)
{
pages = new FacingPages();
pages.ID = i;
pages.Type = FacingPagesTypes.DEFAULT;
gridData.Add(pages);
}
return gridData;
}
}
}
|
Make key entry case insensitive | using System;
using System.IO;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var game = new Game("HANG THE MAN");
while (true) {
string titleText = File.ReadAllText("title.txt");
Cell[] title = {
new Cell(titleText, Cell.CentreAlign)
};
string shownWord = game.ShownWord();
Cell[] word = {
new Cell(shownWord, Cell.CentreAlign)
};
Cell[] stats = {
new Cell("Incorrect letters:\n A B I U"),
new Cell("Lives remaining:\n 11/15", Cell.RightAlign)
};
Cell[] status = {
new Cell("Press any letter to guess!", Cell.CentreAlign)
};
Row[] rows = {
new Row(title),
new Row(word),
new Row(stats),
new Row(status)
};
var table = new Table(
Math.Min(81, Console.WindowWidth),
2,
rows
);
var tableOutput = table.Draw();
Console.WriteLine(tableOutput);
char key = Console.ReadKey(true).KeyChar;
bool wasCorrect = game.GuessLetter(key);
Console.Clear();
}
}
}
}
| using System;
using System.IO;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var game = new Game("HANG THE MAN");
while (true) {
string titleText = File.ReadAllText("title.txt");
Cell[] title = {
new Cell(titleText, Cell.CentreAlign)
};
string shownWord = game.ShownWord();
Cell[] word = {
new Cell(shownWord, Cell.CentreAlign)
};
Cell[] stats = {
new Cell("Incorrect letters:\n A B I U"),
new Cell("Lives remaining:\n 11/15", Cell.RightAlign)
};
Cell[] status = {
new Cell("Press any letter to guess!", Cell.CentreAlign)
};
Row[] rows = {
new Row(title),
new Row(word),
new Row(stats),
new Row(status)
};
var table = new Table(
Math.Min(81, Console.WindowWidth),
2,
rows
);
var tableOutput = table.Draw();
Console.WriteLine(tableOutput);
char key = Console.ReadKey(true).KeyChar;
bool wasCorrect = game.GuessLetter(Char.ToUpper(key));
Console.Clear();
}
}
}
}
|
Fix the temp enum change | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InheritanceMargin
{
internal static class InheritanceMarginHelpers
{
/// <summary>
/// Decide which moniker should be shown.
/// </summary>
public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
{
// If there are multiple targets and we have the corresponding compound image, use it
if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverriding))
{
return KnownMonikers.Implementing;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverridden))
{
return KnownMonikers.Implementing;
}
// Otherwise, show the image based on this preference
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implemented))
{
return KnownMonikers.Implemented;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implementing))
{
return KnownMonikers.Implementing;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overridden))
{
return KnownMonikers.Overridden;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overriding))
{
return KnownMonikers.Overriding;
}
// The relationship is None. Don't know what image should be shown, throws
throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InheritanceMargin
{
internal static class InheritanceMarginHelpers
{
/// <summary>
/// Decide which moniker should be shown.
/// </summary>
public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
{
// If there are multiple targets and we have the corresponding compound image, use it
if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverriding))
{
return KnownMonikers.ImplementingOverriding;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverridden))
{
return KnownMonikers.ImplementingOverridden;
}
// Otherwise, show the image based on this preference
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implemented))
{
return KnownMonikers.Implemented;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implementing))
{
return KnownMonikers.Implementing;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overridden))
{
return KnownMonikers.Overridden;
}
if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overriding))
{
return KnownMonikers.Overriding;
}
// The relationship is None. Don't know what image should be shown, throws
throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
}
}
}
|
Use readonly properties instead of public fields | using System;
namespace Avalonia.Media.Fonts
{
public readonly struct FontKey : IEquatable<FontKey>
{
public readonly string FamilyName;
public readonly FontStyle Style;
public readonly FontWeight Weight;
public FontKey(string familyName, FontWeight weight, FontStyle style)
{
FamilyName = familyName;
Style = style;
Weight = weight;
}
public override int GetHashCode()
{
var hash = FamilyName.GetHashCode();
hash = hash * 31 + (int)Style;
hash = hash * 31 + (int)Weight;
return hash;
}
public override bool Equals(object other)
{
return other is FontKey key && Equals(key);
}
public bool Equals(FontKey other)
{
return FamilyName == other.FamilyName &&
Style == other.Style &&
Weight == other.Weight;
}
}
}
| using System;
namespace Avalonia.Media.Fonts
{
public readonly struct FontKey : IEquatable<FontKey>
{
public FontKey(string familyName, FontWeight weight, FontStyle style)
{
FamilyName = familyName;
Style = style;
Weight = weight;
}
public string FamilyName { get; }
public FontStyle Style { get; }
public FontWeight Weight { get; }
public override int GetHashCode()
{
var hash = FamilyName.GetHashCode();
hash = hash * 31 + (int)Style;
hash = hash * 31 + (int)Weight;
return hash;
}
public override bool Equals(object other)
{
return other is FontKey key && Equals(key);
}
public bool Equals(FontKey other)
{
return FamilyName == other.FamilyName &&
Style == other.Style &&
Weight == other.Weight;
}
}
}
|
Fix null reference exception when creating a project. | using System;
namespace ZBuildLights.Core.Models
{
public class EditProject
{
public Guid? ProjectId { get; set; }
public string Name { get; set; }
public EditProjectCruiseProject[] CruiseProjects { get; set; }
}
public class EditProjectCruiseProject
{
public string Project { get; set; }
public Guid Server { get; set; }
}
} | using System;
namespace ZBuildLights.Core.Models
{
public class EditProject
{
public Guid? ProjectId { get; set; }
public string Name { get; set; }
public EditProjectCruiseProject[] CruiseProjects { get; set; }
public EditProjectCruiseProject[] SafeProjects
{
get { return CruiseProjects ?? new EditProjectCruiseProject[0]; }
}
}
public class EditProjectCruiseProject
{
public string Project { get; set; }
public Guid Server { get; set; }
}
} |
Clarify xmldoc regarding return 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.
namespace osu.Framework.Bindables
{
/// <summary>
/// An interface that represents a leased bindable.
/// </summary>
public interface ILeasedBindable : IBindable
{
/// <summary>
/// End the lease on the source <see cref="Bindable{T}"/>.
/// </summary>
/// <returns>
/// Whether the lease was returned. Will be <c>false</c> if already returned.
/// </returns>
bool Return();
}
/// <summary>
/// An interface that representes a leased bindable.
/// </summary>
/// <typeparam name="T">The value type of the bindable.</typeparam>
public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T>
{
}
}
| // 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.Bindables
{
/// <summary>
/// An interface that represents a leased bindable.
/// </summary>
public interface ILeasedBindable : IBindable
{
/// <summary>
/// End the lease on the source <see cref="Bindable{T}"/>.
/// </summary>
/// <returns>
/// Whether the lease was returned by this call. Will be <c>false</c> if already returned.
/// </returns>
bool Return();
}
/// <summary>
/// An interface that representes a leased bindable.
/// </summary>
/// <typeparam name="T">The value type of the bindable.</typeparam>
public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T>
{
}
}
|
Add tests for user name | using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class PropertyTests
{
[TestCase("street")]
[TestCase("highway")]
[TestCase("boulevard")]
public void TestAddressProperty_ShouldWorkCorrectly(string address)
{
var user = new User();
user.Address = address;
Assert.AreEqual(address, user.Address);
}
}
}
| using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class PropertyTests
{
[TestCase("street")]
[TestCase("highway")]
[TestCase("boulevard")]
public void TestAddressProperty_ShouldWorkCorrectly(string address)
{
var user = new User();
user.Address = address;
Assert.AreEqual(address, user.Address);
}
[TestCase("Pesho")]
[TestCase("Gosho")]
[TestCase("Stamat")]
public void TestNameProperty_ShouldWorkCorrectly(string name)
{
var user = new User();
user.Name = name;
Assert.AreEqual(name, user.Name);
}
}
}
|
Add nv optimus enabler for core tester | using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CoreTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
RenderForm form = new RenderForm();
CoreTestApp app = new CoreTestApp(form);
Application.Run(form);
}
}
}
| using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CoreTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
NVOptimusEnabler nvEnabler = new NVOptimusEnabler();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
RenderForm form = new RenderForm();
CoreTestApp app = new CoreTestApp(form);
Application.Run(form);
}
}
public sealed class NVOptimusEnabler
{
static NVOptimusEnabler()
{
try
{
if (Environment.Is64BitProcess)
NativeMethods.LoadNvApi64();
else
NativeMethods.LoadNvApi32();
}
catch { } // will always fail since 'fake' entry point doesn't exists
}
};
internal static class NativeMethods
{
[System.Runtime.InteropServices.DllImport("nvapi64.dll", EntryPoint = "fake")]
internal static extern int LoadNvApi64();
[System.Runtime.InteropServices.DllImport("nvapi.dll", EntryPoint = "fake")]
internal static extern int LoadNvApi32();
}
}
|
Fix serialization failure due to missing set | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.RealtimeMultiplayer
{
public class MultiplayerClientState
{
public MultiplayerClientState(in long roomId)
{
CurrentRoomID = roomId;
}
public long CurrentRoomID { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.RealtimeMultiplayer
{
public class MultiplayerClientState
{
public long CurrentRoomID { get; set; }
public MultiplayerClientState(in long roomId)
{
CurrentRoomID = roomId;
}
}
}
|
Fix so that dotnet test command can be used | using System.IO;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace MyNatsClient.IntegrationTests
{
public static class TestSettings
{
public static IConfigurationRoot Config { get; set; }
static TestSettings()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("testsettings.json");
Config = builder.Build();
}
public static Host[] GetHosts()
{
return Config.GetSection("clientIntegrationTests:hosts").GetChildren().Select(i =>
{
var u = i["credentials:usr"];
var p = i["credentials:pwd"];
return new Host(i["address"], int.Parse(i["port"]))
{
Credentials = !string.IsNullOrWhiteSpace(u) ? new Credentials(u, p) : Credentials.Empty
};
}).ToArray();
}
}
} | using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace MyNatsClient.IntegrationTests
{
public static class TestSettings
{
public static IConfigurationRoot Config { get; set; }
static TestSettings()
{
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory);
builder.AddJsonFile("testsettings.json");
Config = builder.Build();
}
public static Host[] GetHosts()
{
return Config.GetSection("clientIntegrationTests:hosts").GetChildren().Select(i =>
{
var u = i["credentials:usr"];
var p = i["credentials:pwd"];
return new Host(i["address"], int.Parse(i["port"]))
{
Credentials = !string.IsNullOrWhiteSpace(u) ? new Credentials(u, p) : Credentials.Empty
};
}).ToArray();
}
}
} |
Create server side API for single multiple answer question | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
|
Correct casing of file names | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.WebJobs.Script.Description
{
public static class CSharpConstants
{
public const string PrivateAssembliesFolderName = "bin";
public const string ProjectFileName = "Project.json";
public const string ProjectLockFileName = "Project.lock.json";
public const string MissingFunctionEntryPointCompilationCode = "AF001";
public const string AmbiguousFunctionEntryPointsCompilationCode = "AF002";
public const string MissingTriggerArgumentCompilationCode = "AF003";
public const string MissingBindingArgumentCompilationCode = "AF004";
public const string RedundantPackageAssemblyReference = "AF005";
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.WebJobs.Script.Description
{
public static class CSharpConstants
{
public const string PrivateAssembliesFolderName = "bin";
public const string ProjectFileName = "project.json";
public const string ProjectLockFileName = "project.lock.json";
public const string MissingFunctionEntryPointCompilationCode = "AF001";
public const string AmbiguousFunctionEntryPointsCompilationCode = "AF002";
public const string MissingTriggerArgumentCompilationCode = "AF003";
public const string MissingBindingArgumentCompilationCode = "AF004";
public const string RedundantPackageAssemblyReference = "AF005";
}
}
|
Remove cyclical Dispose method causing error. | using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;
namespace ServiceFabric.Mocks
{
/// <summary>
/// A sequence of operations performed as a single logical unit of work.
/// </summary>
public class MockTransaction : ITransaction
{
public long CommitSequenceNumber => 0L;
public bool IsCommitted { get; private set; }
public bool IsAborted { get; private set; }
public bool IsCompleted => IsCommitted || IsAborted;
public long TransactionId => 0L;
public void Abort()
{
IsAborted = true;
}
public Task CommitAsync()
{
IsCommitted = true;
return Task.FromResult(true);
}
public void Dispose()
{
Dispose();
IsAborted = true;
}
public Task<long> GetVisibilitySequenceNumberAsync()
{
return Task.FromResult(0L);
}
}
} | using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;
namespace ServiceFabric.Mocks
{
/// <summary>
/// A sequence of operations performed as a single logical unit of work.
/// </summary>
public class MockTransaction : ITransaction
{
public long CommitSequenceNumber => 0L;
public bool IsCommitted { get; private set; }
public bool IsAborted { get; private set; }
public bool IsCompleted => IsCommitted || IsAborted;
public long TransactionId => 0L;
public void Abort()
{
IsAborted = true;
}
public Task CommitAsync()
{
IsCommitted = true;
return Task.FromResult(true);
}
public void Dispose()
{
IsAborted = true;
}
public Task<long> GetVisibilitySequenceNumberAsync()
{
return Task.FromResult(0L);
}
}
} |
Add some seed data for quals | namespace BatteryCommander.Common.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(BatteryCommander.Common.DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
} | namespace BatteryCommander.Common.Migrations
{
using BatteryCommander.Common.Models;
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(BatteryCommander.Common.DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Qualifications.AddOrUpdate(
q => new { q.Name, q.Description },
// Field Artillery Qual Events
new Qualification { Name = "FA Safety" },
new Qualification { Name = "ASPT", Description = "Artillery Skills Proficiency Test" },
new Qualification { Name = "GQT", Description = "Gunner's Qualification Test" },
new Qualification { Name = "LDR VAL", Description = "Leader's Validation" },
// Weapon Qual Events
new Qualification { Name = "M-4 IWQ", Description = "M-4 Individual Weapons Qual" },
new Qualification { Name = "M-240B", Description = "M-240B Crew Serve Weapons Qual" },
new Qualification { Name = "M-2", Description = "M-2 Crew Serve Weapons Qual" },
// Driver Quals
// Otther individual warrior task quals
new Qualification { Name = "CLS", Description = "Combat Life Saver" },
new Qualification { Name = "DSCA", Description = "Defense Support of Civil authorities" }
);
context.Users.AddOrUpdate(
u => u.UserName,
new AppUser
{
UserName = "mattgwagner@gmail.com",
EmailAddressConfirmed = true,
PhoneNumber = "8134136839",
PhoneNumberConfirmed = true
});
}
}
} |
Update S.Diag.Contracts tests to verify behavior for DEBUG and !DEBUG | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.Contracts;
using Xunit;
namespace System.Diagnostics.Contracts.Tests
{
public class BasicContractsTest
{
[Fact]
public static void AssertTrueDoesNotRaiseEvent()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetHandled();
};
Contract.Assert(true);
Assert.False(eventRaised, "ContractFailed event was raised");
}
[Fact]
public static void AssertFalseRaisesEvent()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetHandled();
};
Contract.Assert(false);
Assert.True(eventRaised, "ContractFailed event not raised");
}
[Fact]
public static void AssertFalseThrows()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetUnwind();
};
Assert.ThrowsAny<Exception>(() =>
{
Contract.Assert(false, "Some kind of user message");
});
Assert.True(eventRaised, "Event was not raised");
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.Contracts;
using Xunit;
namespace System.Diagnostics.Contracts.Tests
{
public class BasicContractsTest
{
[Fact]
public static void AssertTrueDoesNotRaiseEvent()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetHandled();
};
Contract.Assert(true);
Assert.False(eventRaised, "ContractFailed event was raised");
}
[Fact]
public static void AssertFalseRaisesEvent()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetHandled();
};
Contract.Assert(false);
#if DEBUG
Assert.True(eventRaised, "ContractFailed event not raised");
#else
Assert.False(eventRaised, "ContractFailed event was raised");
#endif
}
[Fact]
public static void AssertFalseThrows()
{
bool eventRaised = false;
Contract.ContractFailed += (s, e) =>
{
eventRaised = true;
e.SetUnwind();
};
#if DEBUG
Assert.ThrowsAny<Exception>(() =>
{
Contract.Assert(false, "Some kind of user message");
});
Assert.True(eventRaised, "Event was not raised");
#else
Contract.Assert(false, "Some kind of user message");
Assert.False(eventRaised, "ContractFailed event was raised");
#endif
}
}
}
|
Fix removal of installation directory from PATH on uninstall | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyncTool.Cli.Installation
{
public class PathVariableInstallerStep : IInstallerStep
{
public void OnInitialInstall(Version version)
{
var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);
if (!currentValues.Contains(ApplicationInfo.RootDirectory))
{
Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
}
}
public void OnAppUpdate(Version version)
{
}
public void OnAppUninstall(Version version)
{
var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);
var valuesToRemove = currentValues.Where(v => StringComparer.InvariantCultureIgnoreCase.Equals(v, ApplicationInfo.RootDirectory));
foreach (var path in valuesToRemove)
{
value = value.Replace(path, "");
}
while (value.Contains(";;"))
{
value = value.Replace(";;", ";");
}
Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyncTool.Cli.Installation
{
public class PathVariableInstallerStep : IInstallerStep
{
public void OnInitialInstall(Version version)
{
var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);
if (!currentValues.Contains(ApplicationInfo.RootDirectory))
{
Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
}
}
public void OnAppUpdate(Version version)
{
}
public void OnAppUninstall(Version version)
{
var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);
var valuesToRemove = currentValues.Where(v => StringComparer.InvariantCultureIgnoreCase.Equals(v, ApplicationInfo.RootDirectory));
foreach (var path in valuesToRemove)
{
value = value.Replace(path, "");
}
while (value.Contains(";;"))
{
value = value.Replace(";;", ";");
}
Environment.SetEnvironmentVariable("PATH", value, EnvironmentVariableTarget.User);
}
}
} |
Add overlay layer to enumeration type | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Beatmaps.Legacy
{
internal enum LegacyStoryLayer
{
Background = 0,
Fail = 1,
Pass = 2,
Foreground = 3,
Video = 4
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Beatmaps.Legacy
{
internal enum LegacyStoryLayer
{
Background = 0,
Fail = 1,
Pass = 2,
Foreground = 3,
Overlay = 4,
Video = 5
}
}
|
Switch service registration over to using new RequestProfile provider | using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
services.AddSingleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
services.AddSingleton<IIgnoredStatusCodeProvider, DefaultIgnoredStatusCodeProvider>();
services.AddSingleton<IIgnoredContentTypeProvider, DefaultIgnoredContentTypeProvider>();
services.AddSingleton<IIgnoredRequestProvider, DefaultIgnoredRequestProvider>();
return services;
}
}
} | using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
services.AddSingleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
services.AddSingleton<IIgnoredStatusCodeProvider, DefaultIgnoredStatusCodeProvider>();
services.AddSingleton<IIgnoredContentTypeProvider, DefaultIgnoredContentTypeProvider>();
services.AddSingleton<IIgnoredRequestProvider, DefaultIgnoredRequestProvider>();
services.AddSingleton<IRequestProfilerProvider, DefaultRequestProfilerProvider>();
return services;
}
}
} |
Fix the build some more | using System.Reflection;
namespace Loyc.Compatibility
{
#if NetStandard20 || DotNet45
/// <summary>Defines ITuple in .NET Standard 2.0. System.Runtime.CompilerServices.ITuple
/// was added to .NET Core 2.0 and .NET Framework 4.7.1, but it wasn't added to .NET
/// Standard 2.0. ITuple was added to .NET Standard 2.1, but this requires .NET Core 3.</summary>
public interface ITuple
{
object this[int index] { get; }
int Length { get; }
}
#endif
}
| using System.Reflection;
namespace Loyc.Compatibility
{
#if NetStandard20 || DotNet45
/// <summary>Defines ITuple in .NET Standard 2.0. System.Runtime.CompilerServices.ITuple
/// was added to .NET Core 2.0 and .NET Framework 4.7.1, but it wasn't added to .NET
/// Standard 2.0. ITuple was added to .NET Standard 2.1, but this requires .NET Core 3.</summary>
public interface ITuple
{
object this[int index] { get; }
int Length { get; }
}
#else
/// <summary>Ensure `using Loyc.Compatibility` is not an error</summary>
public interface __ThisEnsuresTheNamespaceIsNotEmpty { }
#endif
}
|
FIX Logger object on Powershell engine | 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);
}
}
}
}
| 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.ScriptLogger);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
// execute
var results = pipeline.Invoke();
this.Logger.ResultsFromScriptRun(scriptName, results);
}
}
}
}
|
Clarify comment in sample app | using System;
using System.IO;
using System.Text;
using DelimitedDataParser;
namespace WindowsEncoding
{
internal class Program
{
private static void Main()
{
// When using DelimitedDataParser in a .NET Core app,
// be sure to include the NuGet package System.Text.Encoding.CodePages.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// Attempting to obtain the Windows-1252 encoding will fail on .NET Core
// if the required // code page is not correctly registered.
var windows1252 = Encoding.GetEncoding(1252);
// Try and ensure the console's encoding matches the character encoding
// of the file input data.
Console.OutputEncoding = windows1252;
var parser = new Parser
{
UseFirstRowAsColumnHeaders = false
};
using (var stream = new StreamReader("Windows1252.txt", windows1252))
using (var reader = parser.ParseReader(stream))
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
}
}
} | using System;
using System.IO;
using System.Text;
using DelimitedDataParser;
namespace WindowsEncoding
{
internal class Program
{
private static void Main()
{
// If code page based character encodings are required when using
// DelimitedDataParser in a .NET Core app, be sure to include the
// NuGet package System.Text.Encoding.CodePages.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// Attempting to obtain the Windows-1252 encoding will fail on .NET Core
// if the required code page based encoding is not correctly registered.
var windows1252 = Encoding.GetEncoding(1252);
// Try and ensure the console's encoding matches the character encoding
// of the file input data.
Console.OutputEncoding = windows1252;
var parser = new Parser
{
UseFirstRowAsColumnHeaders = false
};
using (var stream = new StreamReader("Windows1252.txt", windows1252))
using (var reader = parser.ParseReader(stream))
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
}
}
}
|
Test 'long'-based 'enum' types, too | using System;
public enum Colors
{
Red = 1,
Alpha,
Green = 13,
Blue
}
public static class Program
{
public static void Main(string[] Args)
{
Console.WriteLine((int)Colors.Red);
Console.WriteLine((int)Colors.Alpha);
Console.WriteLine((int)Colors.Green);
Console.WriteLine((int)Colors.Blue);
Console.WriteLine((long)Colors.Blue);
Console.WriteLine((double)Colors.Blue);
}
}
| using System;
public enum Colors
{
Red = 1,
Alpha,
Green = 13,
Blue
}
public enum LongColors : long
{
Red = 1,
Alpha,
Green = 13,
Blue
}
public static class Program
{
public static void Main(string[] Args)
{
Console.WriteLine((int)Colors.Red);
Console.WriteLine((int)Colors.Alpha);
Console.WriteLine((int)Colors.Green);
Console.WriteLine((int)Colors.Blue);
Console.WriteLine((long)Colors.Blue);
Console.WriteLine((double)Colors.Blue);
Console.WriteLine((int)LongColors.Red);
Console.WriteLine((int)LongColors.Alpha);
Console.WriteLine((int)LongColors.Green);
Console.WriteLine((int)LongColors.Blue);
Console.WriteLine((long)LongColors.Blue);
Console.WriteLine((double)LongColors.Blue);
}
}
|
Fix du mauvais nom de classe | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nutritia
{
public class MySqlPlatService : IPlatService
{
// TODO : Fonctionne pas
private MySqlConnexion connexion;
public Plat Retrieve(RetrievePlatArgs args)
{
Plat plat;
try
{
connexion = new MySqlConnexion();
string requete = string.Format("SELECT * FROM Plats WHERE idPlat = {0}", args.IdPlat);
DataSet dataSetPlats = connexion.Query(requete);
DataTable tablePlats = dataSetPlats.Tables[0];
plat = ConstruirePlat(tablePlats.Rows[0]);
}
catch (Exception)
{
throw;
}
return plat;
}
private Plat ConstruirePlat(DataRow plat)
{
return new Plat()
{
// TODO : Améliorer
IdPlat = (int)plat["idPlat"],
// TODO : Améliorer
Createur = new Membre(),
Nom = (string)plat["nom"],
Note = (int)plat["note"],
// TODO : À voir pour le 'EstType'
ListeIngredients = new List<Aliments>()
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nutritia
{
public class MySqlPlatService : IPlatService
{
// TODO : Fonctionne pas
private MySqlConnexion connexion;
public Plat Retrieve(RetrievePlatArgs args)
{
Plat plat;
try
{
connexion = new MySqlConnexion();
string requete = string.Format("SELECT * FROM Plats WHERE idPlat = {0}", args.IdPlat);
DataSet dataSetPlats = connexion.Query(requete);
DataTable tablePlats = dataSetPlats.Tables[0];
plat = ConstruirePlat(tablePlats.Rows[0]);
}
catch (Exception)
{
throw;
}
return plat;
}
private Plat ConstruirePlat(DataRow plat)
{
return new Plat()
{
// TODO : Améliorer
IdPlat = (int)plat["idPlat"],
// TODO : Améliorer
Createur = new Membre(),
Nom = (string)plat["nom"],
Note = (int)plat["note"],
// TODO : À voir pour le 'EstType'
ListeIngredients = new List<Aliment>()
};
}
}
}
|
Refactor BlockChain to have an internal list | namespace BlockchainSharp.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BlockChain
{
public long number;
public BlockChain(Block block)
{
if (!block.IsGenesis)
throw new ArgumentException("Initial block should be genesis");
this.number = block.Number;
}
public long BestBlockNumber { get { return this.number; } }
}
}
| namespace BlockchainSharp.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BlockChain
{
private IList<Block> blocks = new List<Block>();
public BlockChain(Block block)
{
if (!block.IsGenesis)
throw new ArgumentException("Initial block should be genesis");
this.blocks.Add(block);
}
public long BestBlockNumber { get { return this.blocks.Last().Number; } }
}
}
|
Load FMK credentials from serialized file. | using Assets.Scripts.Data.Interfaces;
using System.Collections.Generic;
using Assets.Scripts.Data.Model.Objects;
using Assets.Scripts.Data.Model.Telemetrics;
using Assets.Scripts.Data.Providers.Fmk;
using UnityEngine;
namespace Assets.Scripts.Data.Providers
{
/// <summary>
/// The author is working in First Monitoring Company. http://firstmk.ru
/// Current provider let to load navigation data from company's servers.
/// This data is confidential, therefore the data transfer protocol is not present in this repository.
/// </summary>
public sealed class FmkDataProvider : IDataProvider
{
private FmkApiClient _client;
public FmkDataProvider()
{
_client = new FmkApiClient(credentials.Key, credentials.Login, credentials.Password);
}
public List<Building> LoadBuildings()
{
return new List<Building>(0); // Buildings are not supported.
}
public List<MoveableObject> LoadMoveableObjects()
{
return _client.GetDevices();
}
public List<TrackPoint> UpdateMoveableObjectLocations()
{
return _client.GetLocations();
}
}
}
| using Assets.Scripts.Data.Interfaces;
using System.Collections.Generic;
using Assets.Scripts.Data.Model.Objects;
using Assets.Scripts.Data.Model.Telemetrics;
using Assets.Scripts.Data.Providers.Fmk;
using UnityEngine;
namespace Assets.Scripts.Data.Providers
{
/// <summary>
/// The author is working in First Monitoring Company. http://firstmk.ru
/// Current provider let to load navigation data from company's servers.
/// This data is confidential, therefore the data transfer protocol is not present in this repository.
/// </summary>
public sealed class FmkDataProvider : IDataProvider
{
private FmkApiClient _client;
public FmkDataProvider()
{
var credentials = Resources.Load<FmkCredentials>("Storages/FMK");
_client = new FmkApiClient(credentials.Key, credentials.Login, credentials.Password);
}
public List<Building> LoadBuildings()
{
return new List<Building>(0); // Buildings are not supported.
}
public List<MoveableObject> LoadMoveableObjects()
{
return _client.GetDevices();
}
public List<TrackPoint> UpdateMoveableObjectLocations()
{
return _client.GetLocations();
}
}
}
|
Remove unnecessary `public` prefix in interface specification | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
namespace osu.Game.Screens.Play
{
[Cached]
public interface ILocalUserPlayInfo
{
/// <summary>
/// Whether the local user is currently playing.
/// </summary>
public IBindable<bool> IsPlaying { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
namespace osu.Game.Screens.Play
{
[Cached]
public interface ILocalUserPlayInfo
{
/// <summary>
/// Whether the local user is currently playing.
/// </summary>
IBindable<bool> IsPlaying { get; }
}
}
|
Revert "YoumuSlash: Better camera looping algorithm" | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YoumuSlash3DEnvironmentController : MonoBehaviour
{
[SerializeField]
private GameObject stairObject;
[SerializeField]
private Vector2 stairOffset;
[SerializeField]
private Transform cameraParent;
[SerializeField]
private float cameraDollySpeed;
Vector3 StairOffset3D => new Vector3(0f, stairOffset.y, stairOffset.x);
//void Start ()
// {
// for (int i = 0; i < stairParent.childCount; i++)
// {
// stairParent.GetChild(i).localPosition = StairOffset3D * i;
// }
//}
void Update ()
{
cameraParent.position += StairOffset3D.resize(cameraDollySpeed * Time.deltaTime);
if (cameraParent.localPosition.y > stairOffset.y)
{
cameraParent.localPosition -= StairOffset3D;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YoumuSlash3DEnvironmentController : MonoBehaviour
{
[SerializeField]
private Transform stairParent;
[SerializeField]
private GameObject stairObject;
[SerializeField]
private Vector2 stairOffset;
[SerializeField]
private Transform cameraParent;
[SerializeField]
private float cameraDollySpeed;
private int unitsTravelled;
Vector3 StairOffset3D => new Vector3(0f, stairOffset.y, stairOffset.x);
void Start ()
{
for (int i = 0; i < stairParent.childCount; i++)
{
stairParent.GetChild(i).localPosition = StairOffset3D * i;
}
unitsTravelled = 1;
}
void Update ()
{
cameraParent.position += StairOffset3D.resize(cameraDollySpeed * Time.deltaTime);
if (cameraParent.localPosition.y > stairOffset.y * unitsTravelled)
{
Transform lowestStair = stairParent.GetChild(0);
lowestStair.SetSiblingIndex(stairParent.childCount - 1);
lowestStair.localPosition += StairOffset3D * stairParent.childCount;
unitsTravelled++;
}
}
}
|
Improve performance of keycode translations | using SierraLib.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Articulate
{
public sealed class FileBasedTranslation : SierraLib.Translation.FileBasedTranslation
{
public FileBasedTranslation(CultureInfo culture, Stream file)
: base(culture, file)
{
}
public override string this[string key]
{
get
{
return this[key, "!!!" + key];
}
}
public override string this[string key, string defaultValue]
{
get
{
if (FileData.ContainsKey(key)) return FileData[key];
else if (key.StartsWith("keyboard_"))
{
var keyCode = Convert.ToInt32(key.Substring("keyboard_".Length));
return ((System.Windows.Forms.Keys)keyCode).ToString();
}
else if (key.StartsWith("mouse_"))
{
var keyCode = Convert.ToInt32(key.Substring("mouse_".Length));
return ((System.Windows.Forms.MouseButtons)keyCode).ToString();
}
else return defaultValue;
}
}
}
}
| using SierraLib.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Articulate
{
public sealed class FileBasedTranslation : SierraLib.Translation.FileBasedTranslation
{
public FileBasedTranslation(CultureInfo culture, Stream file)
: base(culture, file)
{
}
public override string this[string key]
{
get
{
if (key.StartsWith("keyboard_"))
{
var keyCode = Convert.ToInt32(key.Substring("keyboard_".Length));
return this[key, ((System.Windows.Forms.Keys)keyCode).ToString()];
}
else if (key.StartsWith("mouse_"))
{
var keyCode = Convert.ToInt32(key.Substring("mouse_".Length));
return this[key, ((System.Windows.Forms.MouseButtons)keyCode).ToString()];
}
return this[key, "!!!" + key];
}
}
public override string this[string key, string defaultValue]
{
get
{
return FileData.ContainsKey(key) ? FileData[key] : defaultValue;
}
}
}
}
|
Make NetID use 1000+ range | namespace Content.Shared.GameObjects
{
public static class ContentNetIDs
{
public const uint HANDS = 0;
}
}
| namespace Content.Shared.GameObjects
{
public static class ContentNetIDs
{
public const uint HANDS = 1000;
}
}
|
Revert "LOG ALL THE ERRORS" | using RollbarSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LandmineWeb.App_Start
{
public class RollbarExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
//if (filterContext.ExceptionHandled)
// return;
(new RollbarClient()).SendException(filterContext.Exception);
}
}
} | using RollbarSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LandmineWeb.App_Start
{
public class RollbarExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
(new RollbarClient()).SendException(filterContext.Exception);
}
}
} |
Add extra test to ensure Account deserialization | using Machine.Specifications;
namespace Stripe.Tests
{
public class when_creating_a_charge_with_a_stripe_account
{
private static StripeAccount _stripeAccount;
private static StripeCharge _stripeCharge;
Establish context = () =>
{
// create a new custom account
_stripeAccount = new StripeAccountService().Create(new StripeAccountCreateOptions()
{
Country = "US",
Type = StripeAccountType.Custom
});
};
Because of = () =>
{
// charge the customer something
_stripeCharge = new StripeChargeService().Create(new StripeChargeCreateOptions()
{
Amount = 100,
Currency = "usd",
SourceTokenOrExistingSourceId = _stripeAccount.Id
});
};
It should_have_the_right_source = () =>
_stripeCharge.Source.Account.ShouldNotBeNull();
It should_not_have_the_wrong_source = () =>
_stripeCharge.Source.Card.ShouldBeNull();
It should_have_the_right_source_type = () =>
_stripeCharge.Source.Type.ShouldEqual(SourceType.Account);
It should_have_the_right_id = () =>
_stripeCharge.Source.Id.ShouldEqual(_stripeAccount.Id);
}
} | using Machine.Specifications;
namespace Stripe.Tests
{
public class when_creating_a_charge_with_a_stripe_account
{
private static StripeAccount _stripeAccount;
private static StripeCharge _stripeCharge;
Establish context = () =>
{
// create a new custom account
_stripeAccount = new StripeAccountService().Create(new StripeAccountCreateOptions()
{
Country = "US",
Type = StripeAccountType.Custom
});
};
Because of = () =>
{
// charge the customer something
_stripeCharge = new StripeChargeService().Create(new StripeChargeCreateOptions()
{
Amount = 100,
Currency = "usd",
SourceTokenOrExistingSourceId = _stripeAccount.Id
});
};
It should_have_the_right_source = () =>
_stripeCharge.Source.Account.ShouldNotBeNull();
It should_not_have_the_wrong_source = () =>
_stripeCharge.Source.Card.ShouldBeNull();
It should_have_the_right_source_type = () =>
_stripeCharge.Source.Type.ShouldEqual(SourceType.Account);
It should_have_the_right_id = () =>
_stripeCharge.Source.Id.ShouldEqual(_stripeAccount.Id);
It should_deserialize_the_account_properly = () =>
_stripeCharge.Source.Account.Id.ShouldEqual(_stripeAccount.Id);
}
} |
Fix sorting of search bags | using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Constants;
using TheCollection.Web.Extensions;
using TheCollection.Web.Models;
using TheCollection.Web.Services;
namespace TheCollection.Web.Commands
{
public class SearchBagsCommand : IAsyncCommand<Search>
{
private readonly IDocumentClient documentDbClient;
public SearchBagsCommand(IDocumentClient documentDbClient)
{
this.documentDbClient = documentDbClient;
}
public async Task<IActionResult> ExecuteAsync(Search search)
{
if (search.searchterm.IsNullOrWhiteSpace())
{
return new BadRequestResult();
}
var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId);
var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize);
var result = new SearchResult<Bag>
{
count = await bagsRepository.SearchRowCountAsync(search.searchterm),
data = bags.OrderBy(bag => bag.Brand.Name)
.ThenBy(bag => bag.Hallmark)
.ThenBy(bag => bag.Serie)
.ThenBy(bag => bag.BagType?.Name)
.ThenBy(bag => bag.Flavour)
};
return new OkObjectResult(result);
}
}
} | using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Constants;
using TheCollection.Web.Extensions;
using TheCollection.Web.Models;
using TheCollection.Web.Services;
namespace TheCollection.Web.Commands
{
public class SearchBagsCommand : IAsyncCommand<Search>
{
private readonly IDocumentClient documentDbClient;
public SearchBagsCommand(IDocumentClient documentDbClient)
{
this.documentDbClient = documentDbClient;
}
public async Task<IActionResult> ExecuteAsync(Search search)
{
if (search.searchterm.IsNullOrWhiteSpace())
{
return new BadRequestResult();
}
var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId);
var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize);
var result = new SearchResult<Bag>
{
count = await bagsRepository.SearchRowCountAsync(search.searchterm),
data = bags.OrderBy(bag => bag.Brand.Name)
.ThenBy(bag => bag.Serie)
.ThenBy(bag => bag.Hallmark)
.ThenBy(bag => bag.BagType?.Name)
.ThenBy(bag => bag.Flavour)
};
return new OkObjectResult(result);
}
}
} |
Add link to explanatory comment | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
internal static class EditorConfigStorageLocationExtensions
{
public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
{
// This is a workaround until we have an API for enumeratings AnalyzerConfigOptions.
var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var backing = backingField?.GetValue(analyzerConfigOptions);
if (backing is IReadOnlyDictionary<string, string> backingDictionary)
{
return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
}
value = null;
return false;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
internal static class EditorConfigStorageLocationExtensions
{
public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
{
// This is a workaround until we have an API for enumeratings AnalyzerConfigOptions. See https://github.com/dotnet/roslyn/issues/41840
var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var backing = backingField?.GetValue(analyzerConfigOptions);
if (backing is IReadOnlyDictionary<string, string> backingDictionary)
{
return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
}
value = null;
return false;
}
}
}
|
Add exception handler to main() | using CommandLineParser;
using Saucy.Actions;
using Saucy.Providers.GitHub;
namespace Saucy
{
public class Program
{
public static int Main(string[] args)
{
var settings = new SaucySettings();
ILogger logger = new VerboseLogger();
var restoreVerb = new SaucyCommandLine(
new PackagesRestorer(
new JsonLoader(),
new ProviderMatcher(new GitHubProvider(new FolderSync(logger))),
new ConsoleWriter(),
settings),
settings);
var runner = new Runner();
runner.Register(restoreVerb);
var exitCode = runner.Run(args);
return exitCode;
}
}
}
| using CommandLineParser;
using Saucy.Actions;
using Saucy.Providers.GitHub;
namespace Saucy
{
using System;
public class Program
{
public static int Main(string[] args)
{
var consoleWriter = new ConsoleWriter();
try
{
var settings = new SaucySettings();
ILogger logger = new VerboseLogger();
var restoreVerb = new SaucyCommandLine(
new PackagesRestorer(
new JsonLoader(),
new ProviderMatcher(new GitHubProvider(new FolderSync(logger))),
consoleWriter,
settings),
settings);
var runner = new Runner();
runner.Register(restoreVerb);
var exitCode = runner.Run(args);
return exitCode;
}
catch (Exception e)
{
consoleWriter.Write(e.Message);
consoleWriter.Write(e.StackTrace);
return -1;
}
}
}
}
|
Add option to use current dir. | using System;
namespace Watts
{
internal class Program
{
private static int Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: Watts.exe <\"Path/To/Config.json\">");
return 1;
}
var watts = new WebApiToTypeScript.WebApiToTypeScript
{
ConfigFilePath = args[0]
};
watts.Execute();
#if DEBUG
Console.ReadLine();
#endif
return 0;
}
}
} | using System;
using System.Diagnostics;
using System.IO;
namespace Watts
{
internal class Program
{
private static int Main(string[] args)
{
var watts = new WebApiToTypeScript.WebApiToTypeScript();
if (args.Length == 0)
{
var path = Path.Combine(Environment.CurrentDirectory, "watts.config.json");
if (File.Exists(path))
watts.ConfigFilePath = path;
}
else if (args.Length > 0 && File.Exists(args[0]))
{
watts.ConfigFilePath = args[1];
}
int status = 0;
if (watts.ConfigFilePath == null)
{
Console.WriteLine("Usage: Watts.exe <\"Path/To/Config.json\">");
status = -1;
}
else
{
status = watts.Execute() ? 0 : -1;
}
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . .");
Console.ReadLine();
}
return 0;
}
}
} |
Use intermediate variables to improve readability. | namespace Bakery.Security
{
using System;
using System.Text;
using Text;
public class BasicAuthenticationPrinter
: IBasicAuthenticationPrinter
{
private readonly IBase64Printer base64Printer;
private readonly Encoding encoding;
public BasicAuthenticationPrinter(IBase64Printer base64Printer, Encoding encoding)
{
if (base64Printer == null)
throw new ArgumentNullException(nameof(base64Printer));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
this.base64Printer = base64Printer;
this.encoding = encoding;
}
public String Print(IBasicAuthentication basicAuthentication)
{
if (basicAuthentication == null)
throw new ArgumentNullException(nameof(basicAuthentication));
return $"Basic {base64Printer.Print(encoding.GetBytes($"{basicAuthentication.Username}:{basicAuthentication.Password}"))}";
}
}
}
| namespace Bakery.Security
{
using System;
using System.Text;
using Text;
public class BasicAuthenticationPrinter
: IBasicAuthenticationPrinter
{
private readonly IBase64Printer base64Printer;
private readonly Encoding encoding;
public BasicAuthenticationPrinter(IBase64Printer base64Printer, Encoding encoding)
{
if (base64Printer == null)
throw new ArgumentNullException(nameof(base64Printer));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
this.base64Printer = base64Printer;
this.encoding = encoding;
}
public String Print(IBasicAuthentication basicAuthentication)
{
if (basicAuthentication == null)
throw new ArgumentNullException(nameof(basicAuthentication));
var credentials =
String.Format("{0}:{1}",
basicAuthentication.Username,
basicAuthentication.Password);
var credentialsBase64 = base64Printer.Print(encoding.GetBytes(credentials));
return $"Basic {credentialsBase64}";
}
}
}
|
Enable automatic versioning and Nuget packaging of shippable Vipr binaries | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using Vipr.Core;
namespace Vipr
{
internal class Program
{
private static void Main(string[] args)
{
var bootstrapper = new Bootstrapper();
bootstrapper.Start(args);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
namespace Vipr
{
internal class Program
{
private static void Main(string[] args)
{
var bootstrapper = new Bootstrapper();
bootstrapper.Start(args);
}
}
}
|
Revert "Enabling startup error logging" | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace MabWeb
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseSetting("detailedErrors", "true")
.CaptureStartupErrors(true)
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace MabWeb
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
|
Use string interpolation in key error | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
if (!textures.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException("Texture '" + name + "' was not found.");
return textures[name.ToLowerInvariant()];
}
}
}
| /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
if (!textures.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException($"Texture '{name}' was not found.");
return textures[name.ToLowerInvariant()];
}
}
}
|
Update main window text to include nomod/modded star rating | using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
using osu_StreamCompanion.Code.Windows;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window
{
public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater
{
private MainWindowUpdater _mainwindowHandle;
public bool Started { get; set; }
public void Start(ILogger logger)
{
Started = true;
}
public void SetNewMap(MapSearchResult map)
{
if (map.FoundBeatmaps)
{
var nowPlaying = string.Format("{0} - {1}", map.BeatmapsFound[0].ArtistRoman,map.BeatmapsFound[0].TitleRoman);
if (map.Action == OsuStatus.Playing || map.Action == OsuStatus.Watching)
{
nowPlaying += string.Format(" [{0}] {1}", map.BeatmapsFound[0].DiffName, map.Mods?.Item2 ?? "");
nowPlaying += string.Format("{0:##.###}", map.BeatmapsFound[0].StarsNomod);
}
_mainwindowHandle.NowPlaying = nowPlaying;
}
else
{
_mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString;
}
}
public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle)
{
_mainwindowHandle = mainWindowHandle;
}
}
} | using System;
using CollectionManager.DataTypes;
using CollectionManager.Enums;
using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
using osu_StreamCompanion.Code.Windows;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.Window
{
public class WindowDataGetter :IModule,IMapDataGetter,IMainWindowUpdater
{
private MainWindowUpdater _mainwindowHandle;
public bool Started { get; set; }
public void Start(ILogger logger)
{
Started = true;
}
public void SetNewMap(MapSearchResult map)
{
if (map.FoundBeatmaps)
{
var foundMap = map.BeatmapsFound[0];
var nowPlaying = string.Format("{0} - {1}", foundMap.ArtistRoman, foundMap.TitleRoman);
if (map.Action == OsuStatus.Playing || map.Action == OsuStatus.Watching)
{
nowPlaying += string.Format(" [{0}] {1}", foundMap.DiffName, map.Mods?.Item2 ?? "");
nowPlaying += string.Format(Environment.NewLine+"NoMod:{0:##.###}", foundMap.StarsNomod);
var mods = map.Mods?.Item1 ?? Mods.Omod;
nowPlaying += string.Format(" Modded: {0:##.###}", foundMap.Stars(PlayMode.Osu, mods));
}
_mainwindowHandle.NowPlaying = nowPlaying;
}
else
{
_mainwindowHandle.NowPlaying = "notFound:( " + map.MapSearchString;
}
}
public void GetMainWindowHandle(MainWindowUpdater mainWindowHandle)
{
_mainwindowHandle = mainWindowHandle;
}
}
} |
Fix D rank displaying as F | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"F")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"SPlus")]
SH,
[Description(@"SS")]
X,
[Description(@"SSPlus")]
XH,
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"D")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"SPlus")]
SH,
[Description(@"SS")]
X,
[Description(@"SSPlus")]
XH,
}
}
|
Add "are" to the command pattern | using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|will|is)", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"Only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure, ok."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|can|is";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
| using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|will|is)", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"Only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure, ok."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|are|can|is";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
|
Remove template contents from the home/index view | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
|
Add custom representation of unrenderable unicode characters. | // 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.Graphics.Sprites;
namespace osu.Game.Graphics.Sprites
{
class OsuSpriteText : SpriteText
{
public const float FONT_SIZE = 16;
public OsuSpriteText()
{
Shadow = true;
TextSize = FONT_SIZE;
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.MathUtils;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Game.Graphics.Sprites
{
class OsuSpriteText : SpriteText
{
public const float FONT_SIZE = 16;
public OsuSpriteText()
{
Shadow = true;
TextSize = FONT_SIZE;
}
protected override Drawable GetUndrawableCharacter()
{
var tex = GetTextureForCharacter('?');
if (tex != null)
{
float adjust = (RNG.NextSingle() - 0.5f) * 2;
return new Sprite
{
Texture = tex,
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Scale = new Vector2(1 + adjust * 0.2f),
Rotation = adjust * 15,
Colour = Color4.White,
};
}
return base.GetUndrawableCharacter();
}
}
}
|
Add the nullable DateTime type | using System;
using Newtonsoft.Json.Linq;
namespace Chronological
{
public class DataType
{
public string TimeSeriesInsightsType { get; }
internal DataType(string dataType)
{
TimeSeriesInsightsType = dataType;
}
internal JProperty ToJProperty()
{
return new JProperty("type", TimeSeriesInsightsType);
}
internal static DataType FromType(Type type)
{
switch (type)
{
case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
return Double;
case Type stringType when stringType == typeof(string):
return String;
case Type dateTimeType when dateTimeType == typeof(DateTime):
return DateTime;
case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
return Boolean;
default:
//Todo: Better exceptions
throw new Exception("Unexpected Type");
}
}
public static DataType Double => new DataType("Double");
public static DataType String => new DataType("String");
public static DataType DateTime => new DataType("DateTime");
public static DataType Boolean => new DataType("Boolean");
}
}
| using System;
using Newtonsoft.Json.Linq;
namespace Chronological
{
public class DataType
{
public string TimeSeriesInsightsType { get; }
internal DataType(string dataType)
{
TimeSeriesInsightsType = dataType;
}
internal JProperty ToJProperty()
{
return new JProperty("type", TimeSeriesInsightsType);
}
internal static DataType FromType(Type type)
{
switch (type)
{
case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
return Double;
case Type stringType when stringType == typeof(string):
return String;
case Type dateTimeType when dateTimeType == typeof(DateTime) || dateTimeType == typeof(DateTime?):
return DateTime;
case Type boolType when boolType == typeof(bool) || boolType == typeof(bool?):
return Boolean;
default:
//Todo: Better exceptions
throw new Exception("Unexpected Type");
}
}
public static DataType Double => new DataType("Double");
public static DataType String => new DataType("String");
public static DataType DateTime => new DataType("DateTime");
public static DataType Boolean => new DataType("Boolean");
}
}
|
Simplify uri -> filename conversion | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Mono.Debugging.Client
{
[Serializable]
public class SourceLink
{
// Keep the / character to use as a path separator to help group related symbols
static readonly HashSet<char> invalids = new HashSet<char>(Path.GetInvalidFileNameChars ().Except (new char[] { '/' }));
public string Uri { get; }
public string RelativeFilePath { get; }
public SourceLink (string uri, string relativeFilePath)
{
RelativeFilePath = relativeFilePath;
Uri = uri;
}
public string GetDownloadLocation (string cachePath)
{
var uri = new Uri (Uri);
return Path.Combine (cachePath, MakeValidFileName (uri));
}
static string MakeValidFileName (Uri uri)
{
// Remove scheme from uri
var text = uri.Host + uri.PathAndQuery;
var sb = new StringBuilder (text.Length);
for (int i = 0; i < text.Length; i++) {
char c = text[i];
if (invalids.Contains (c)) {
sb.Append ('_');
} else
sb.Append (c);
}
if (sb.Length == 0)
return "_";
return sb.ToString ();
}
}
}
| using System;
using System.IO;
namespace Mono.Debugging.Client
{
[Serializable]
public class SourceLink
{
public string Uri { get; }
public string RelativeFilePath { get; }
public SourceLink (string uri, string relativeFilePath)
{
RelativeFilePath = relativeFilePath;
Uri = uri;
}
public string GetDownloadLocation (string cachePath)
{
var uri = new Uri (Uri);
return Path.Combine (cachePath, uri.Host + uri.PathAndQuery);
}
}
}
|
Add support for new column name in fortis export | using CsvHelper.Configuration;
using MyAccounts.Business.AccountOperations.Contracts;
namespace MyAccounts.Business.AccountOperations.Fortis
{
public sealed class FortisOperationExportCsvMap : ClassMap<FortisOperation>
{
public FortisOperationExportCsvMap()
{
Map(m => m.Reference).Name("Numro de squence");
Map(m => m.ExecutionDate).Name("Date d'excution").TypeConverterOption.Format("dd/MM/yyyy");
Map(m => m.ValueDate).Name("Date valeur").TypeConverterOption.Format("dd/MM/yyyy");
Map(m => m.Amount).Name("Montant");
Map(m => m.Currency).Name("Devise du compte");
Map(m => m.CounterpartyOfTheTransaction).Name("CONTREPARTIE DE LA TRANSACTION");
Map(m => m.Detail).Name("Dtails");
Map(m => m.Account).Name("Numro de compte");
Map(m => m.SourceKind).Default(SourceKind.Unknwon);
}
}
} | using CsvHelper.Configuration;
using MyAccounts.Business.AccountOperations.Contracts;
namespace MyAccounts.Business.AccountOperations.Fortis
{
public sealed class FortisOperationExportCsvMap : ClassMap<FortisOperation>
{
public FortisOperationExportCsvMap()
{
Map(m => m.Reference).Name("Numro de squence", "N de squence");
Map(m => m.ExecutionDate).Name("Date d'excution").TypeConverterOption.Format("dd/MM/yyyy");
Map(m => m.ValueDate).Name("Date valeur").TypeConverterOption.Format("dd/MM/yyyy");
Map(m => m.Amount).Name("Montant");
Map(m => m.Currency).Name("Devise du compte");
Map(m => m.CounterpartyOfTheTransaction).Name("CONTREPARTIE DE LA TRANSACTION");
Map(m => m.Detail).Name("Dtails");
Map(m => m.Account).Name("Numro de compte");
Map(m => m.SourceKind).Default(SourceKind.Unknwon);
}
}
} |
Change Foreground Match Data "Title Match Mode" default value | using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Classes
{
[ExpandableObject]
public class ForegroundMatchData
{
[DisplayName("Title")]
public string Title { get; set; }
[DisplayName("Title Match Mode")]
public StringMatchMode TitleMatchMode { get; set; } = StringMatchMode.Any;
[DisplayName("Fullscreen")]
public YesNoAny Fullscreen { get; set; } = YesNoAny.Any;
}
} | using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Classes
{
[ExpandableObject]
public class ForegroundMatchData
{
[DisplayName("Title")]
public string Title { get; set; }
[DisplayName("Title Match Mode")]
public StringMatchMode TitleMatchMode { get; set; } = StringMatchMode.Equals;
[DisplayName("Fullscreen")]
public YesNoAny Fullscreen { get; set; } = YesNoAny.Any;
}
} |
Add serialize loop handling to prevent crashing for circular loops | // MvxJsonConverter.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using System.Collections.Generic;
using Cirrious.CrossCore.Platform;
using Newtonsoft.Json;
namespace Cirrious.MvvmCross.Plugins.Json
{
public class MvxJsonConverter : IMvxJsonConverter
{
private static readonly JsonSerializerSettings Settings;
static MvxJsonConverter()
{
Settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new MvxEnumJsonConverter(),
},
DateFormatHandling = DateFormatHandling.IsoDateFormat,
};
}
public T DeserializeObject<T>(string inputText)
{
return JsonConvert.DeserializeObject<T>(inputText, Settings);
}
public string SerializeObject(object toSerialise)
{
return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings);
}
public object DeserializeObject(Type type, string inputText)
{
return JsonConvert.DeserializeObject(inputText, type, Settings);
}
}
} | // MvxJsonConverter.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using System.Collections.Generic;
using Cirrious.CrossCore.Platform;
using Newtonsoft.Json;
namespace Cirrious.MvvmCross.Plugins.Json
{
public class MvxJsonConverter : IMvxJsonConverter
{
private static readonly JsonSerializerSettings Settings;
static MvxJsonConverter()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
Converters = new List<JsonConverter>
{
new MvxEnumJsonConverter(),
},
DateFormatHandling = DateFormatHandling.IsoDateFormat,
};
}
public T DeserializeObject<T>(string inputText)
{
return JsonConvert.DeserializeObject<T>(inputText, Settings);
}
public string SerializeObject(object toSerialise)
{
return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings);
}
public object DeserializeObject(Type type, string inputText)
{
return JsonConvert.DeserializeObject(inputText, type, Settings);
}
}
} |
Create an instance of Game | using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
| using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
Game game = new Game();
Console.WriteLine("Made a new Game object");
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
|
Move the backgroundtask runner into Initialize method to follow same practise as SchedulerComponent | using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;
namespace Umbraco.Web.Telemetry
{
public class TelemetryComponent : IComponent
{
private IProfilingLogger _logger;
private IRuntimeState _runtime;
private BackgroundTaskRunner<IBackgroundTask> _telemetryReporterRunner;
public TelemetryComponent(IProfilingLogger logger, IRuntimeState runtime)
{
_logger = logger;
_runtime = runtime;
_telemetryReporterRunner = new BackgroundTaskRunner<IBackgroundTask>("TelemetryReporter", _logger);
}
public void Initialize()
{
int delayBeforeWeStart = 60 * 1000; // 60 * 1000ms = 1min (60,000)
int howOftenWeRepeat = 60 * 1000 * 60 * 24; // 60 * 1000 * 60 * 24 = 24hrs (86400000)
// As soon as we add our task to the runner it will start to run (after its delay period)
var task = new ReportSiteTask(_telemetryReporterRunner, delayBeforeWeStart, howOftenWeRepeat, _runtime, _logger);
_telemetryReporterRunner.TryAdd(task);
}
public void Terminate()
{
}
}
}
| using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;
namespace Umbraco.Web.Telemetry
{
public class TelemetryComponent : IComponent
{
private IProfilingLogger _logger;
private IRuntimeState _runtime;
private BackgroundTaskRunner<IBackgroundTask> _telemetryReporterRunner;
public TelemetryComponent(IProfilingLogger logger, IRuntimeState runtime)
{
_logger = logger;
_runtime = runtime;
}
public void Initialize()
{
// backgrounds runners are web aware, if the app domain dies, these tasks will wind down correctly
_telemetryReporterRunner = new BackgroundTaskRunner<IBackgroundTask>("TelemetryReporter", _logger);
int delayBeforeWeStart = 60 * 1000; // 60 * 1000ms = 1min (60,000)
int howOftenWeRepeat = 60 * 1000 * 60 * 24; // 60 * 1000 * 60 * 24 = 24hrs (86400000)
// As soon as we add our task to the runner it will start to run (after its delay period)
var task = new ReportSiteTask(_telemetryReporterRunner, delayBeforeWeStart, howOftenWeRepeat, _runtime, _logger);
_telemetryReporterRunner.TryAdd(task);
}
public void Terminate()
{
}
}
}
|
Fix .NET 3.5 build error | using System;
using System.Reflection;
using Newtonsoft.Json;
namespace TrackableData.Json
{
public class TrackableContainerTrackerJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IContainerTracker).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.StartObject)
return null;
var tracker = (ITracker)Activator.CreateInstance(objectType);
reader.Read();
while (true)
{
if (reader.TokenType != JsonToken.PropertyName)
break;
var pi = objectType.GetProperty((string)reader.Value + "Tracker");
reader.Read();
var subTracker = serializer.Deserialize(reader, pi.PropertyType);
reader.Read();
pi.SetValue(tracker, subTracker);
}
return tracker;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var tracker = (ITracker)value;
writer.WriteStartObject();
foreach (var pi in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (typeof(ITracker).IsAssignableFrom(pi.PropertyType) == false)
continue;
var subTracker = (ITracker)pi.GetValue(value);
if (subTracker != null && subTracker.HasChange)
{
writer.WritePropertyName(pi.Name.Substring(0, pi.Name.Length - 7));
serializer.Serialize(writer, subTracker);
}
}
writer.WriteEndObject();
}
}
}
| using System;
using System.Reflection;
using Newtonsoft.Json;
namespace TrackableData.Json
{
public class TrackableContainerTrackerJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IContainerTracker).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.StartObject)
return null;
var tracker = (ITracker)Activator.CreateInstance(objectType);
reader.Read();
while (true)
{
if (reader.TokenType != JsonToken.PropertyName)
break;
var pi = objectType.GetProperty((string)reader.Value + "Tracker");
reader.Read();
var subTracker = serializer.Deserialize(reader, pi.PropertyType);
reader.Read();
pi.SetValue(tracker, subTracker, null);
}
return tracker;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var tracker = (ITracker)value;
writer.WriteStartObject();
foreach (var pi in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (typeof(ITracker).IsAssignableFrom(pi.PropertyType) == false)
continue;
var subTracker = (ITracker)pi.GetValue(value, null);
if (subTracker != null && subTracker.HasChange)
{
writer.WritePropertyName(pi.Name.Substring(0, pi.Name.Length - 7));
serializer.Serialize(writer, subTracker);
}
}
writer.WriteEndObject();
}
}
}
|
Fix api response success detection (sometimes body contains response, no +OK | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiResponse.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
using System;
using NEventSocket.Util;
/// <summary>
/// A message representing the response to an Api call.
/// </summary>
[Serializable]
public class ApiResponse : BasicMessage
{
internal ApiResponse(BasicMessage basicMessage)
{
if (basicMessage.ContentType != ContentTypes.ApiResponse)
{
throw new ArgumentException("Expected content type api/response, got {0} instead.".Fmt(basicMessage.ContentType));
}
this.Headers = basicMessage.Headers;
this.BodyText = basicMessage.BodyText;
}
/// <summary>
/// Gets a boolean indicating whether the operation succeeded or not.
/// </summary>
public bool Success
{
get
{
return this.BodyText != null && this.BodyText[0] == '+';
}
}
/// <summary>
/// Gets the error message for a failed api call.
/// </summary>
public string ErrorMessage
{
get
{
return this.BodyText != null && this.BodyText.StartsWith("-ERR")
? this.BodyText.Substring(5, this.BodyText.Length - 5)
: string.Empty;
}
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiResponse.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
using System;
using NEventSocket.Util;
/// <summary>
/// A message representing the response to an Api call.
/// </summary>
[Serializable]
public class ApiResponse : BasicMessage
{
internal ApiResponse(BasicMessage basicMessage)
{
if (basicMessage.ContentType != ContentTypes.ApiResponse)
{
throw new ArgumentException("Expected content type api/response, got {0} instead.".Fmt(basicMessage.ContentType));
}
this.Headers = basicMessage.Headers;
this.BodyText = basicMessage.BodyText;
}
/// <summary>
/// Gets a boolean indicating whether the operation succeeded or not.
/// </summary>
public bool Success
{
get
{
return this.BodyText != null && this.BodyText[0] != '-';
}
}
/// <summary>
/// Gets the error message for a failed api call.
/// </summary>
public string ErrorMessage
{
get
{
return this.BodyText != null && this.BodyText.StartsWith("-ERR")
? this.BodyText.Substring(5, this.BodyText.Length - 5)
: string.Empty;
}
}
}
} |
Use new style embed for vimeo links and made it https. | using System.Collections.Generic;
using System.Text.RegularExpressions;
using JabbR.ContentProviders.Core;
namespace JabbR.ContentProviders
{
public class VimeoContentProvider : EmbedContentProvider
{
private static readonly Regex _vimeoIdRegex = new Regex(@"(\d+)");
protected override Regex ParameterExtractionRegex
{
get
{
return _vimeoIdRegex;
}
}
public override IEnumerable<string> Domains
{
get
{
yield return "http://vimeo.com";
yield return "http://www.vimeo.com";
}
}
public override string MediaFormatString
{
get
{
return "<object width=\"500\" height=\"282 \">" +
"<param name=\"allowfullscreen\" value=\"true\" />" +
"<param name=\"allowscriptaccess\" value=\"always\" />" +
"<param name=\"movie\" value=\"http://vimeo.com/moogaloop.swf?clip_id={0}&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0\" />" +
"<embed src=\"http://vimeo.com/moogaloop.swf?clip_id={0}&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0\" " +
"type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowscriptaccess=\"always\" width=\"500\" height=\"282\">" +
"</embed></object>";
}
}
}
} | using System.Collections.Generic;
using System.Text.RegularExpressions;
using JabbR.ContentProviders.Core;
namespace JabbR.ContentProviders
{
public class VimeoContentProvider : EmbedContentProvider
{
private static readonly Regex _vimeoIdRegex = new Regex(@"(\d+)");
protected override Regex ParameterExtractionRegex
{
get
{
return _vimeoIdRegex;
}
}
public override IEnumerable<string> Domains
{
get
{
yield return "http://vimeo.com";
yield return "http://www.vimeo.com";
}
}
public override string MediaFormatString
{
get
{
return @"<iframe src=""https://player.vimeo.com/video/{0}?title=0&byline=0&portrait=0&color=c9ff23"" width=""500"" height=""271"" frameborder=""0"" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>";
}
}
}
} |
Hide in-game cursor manually in the testbrowser | // 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.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
namespace osu.Game.Tournament.Tests
{
public class TournamentTestBrowser : TournamentGameBase
{
protected override void LoadComplete()
{
base.LoadComplete();
LoadComponentAsync(new Background("Menu/menu-background-0")
{
Colour = OsuColour.Gray(0.5f),
Depth = 10
}, AddInternal);
// Have to construct this here, rather than in the constructor, because
// we depend on some dependencies to be loaded within OsuGameBase.load().
Add(new TestBrowser());
}
}
}
| // 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.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
namespace osu.Game.Tournament.Tests
{
public class TournamentTestBrowser : TournamentGameBase
{
protected override void LoadComplete()
{
base.LoadComplete();
LoadComponentAsync(new Background("Menu/menu-background-0")
{
Colour = OsuColour.Gray(0.5f),
Depth = 10
}, AddInternal);
MenuCursorContainer.Cursor.AlwaysPresent = true;
MenuCursorContainer.Cursor.Alpha = 0;
// Have to construct this here, rather than in the constructor, because
// we depend on some dependencies to be loaded within OsuGameBase.load().
Add(new TestBrowser());
}
}
}
|
Create list of used providers properly. | using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;
namespace Chalmers.ILL.Providers
{
public class ProviderService : IProviderService
{
IOrderItemSearcher _orderItemsSearcher;
public ProviderService(IOrderItemSearcher orderItemsSearcher)
{
_orderItemsSearcher = orderItemsSearcher;
}
public List<String> FetchAndCreateListOfUsedProviders()
{
var res = new List<String>();
// NOTE: Should probably only fetch orders that are not too old, to keep the numbers down and to keep the data relevant.
var allOrders = _orderItemsSearcher.Search("nodeTypeAlias:ChalmersILLOrderItem");
return allOrders.Where(x => x.ProviderName != "")
.Select(x => x.ProviderName)
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(x => x.Key)
.ToList();
}
public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
{
int res = 168;
if (!String.IsNullOrWhiteSpace(providerName) && providerName.ToLower().Contains("subito"))
{
res = 24;
}
return res;
}
}
} | using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;
namespace Chalmers.ILL.Providers
{
public class ProviderService : IProviderService
{
IOrderItemSearcher _orderItemsSearcher;
public ProviderService(IOrderItemSearcher orderItemsSearcher)
{
_orderItemsSearcher = orderItemsSearcher;
}
public List<String> FetchAndCreateListOfUsedProviders()
{
var res = new List<String>();
// NOTE: Should probably only fetch orders that are not too old, to keep the numbers down and to keep the data relevant.
var allOrders = _orderItemsSearcher.Search("*:*");
return allOrders.Where(x => x.ProviderName != "")
.Select(x => x.ProviderName)
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(x => x.Key)
.ToList();
}
public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
{
int res = 168;
if (!String.IsNullOrWhiteSpace(providerName) && providerName.ToLower().Contains("subito"))
{
res = 24;
}
return res;
}
}
} |
Use var instead of full type name | using LiteNetLib.Utils;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
namespace LiteNetLibHighLevel
{
public class NetFieldStruct<T> : LiteNetLibNetField<T>
where T : struct
{
public override void Deserialize(NetDataReader reader)
{
using (MemoryStream memoryStream = new MemoryStream(reader.GetBytesWithLength()))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
// Setup Unity's structs serialization surrogates
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddAllUnitySurrogate();
binaryFormatter.SurrogateSelector = surrogateSelector;
// Deserialize
var data = binaryFormatter.Deserialize(memoryStream);
Value = (T)data;
}
}
public override void Serialize(NetDataWriter writer)
{
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
// Setup Unity's structs serialization surrogates
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddAllUnitySurrogate();
binaryFormatter.SurrogateSelector = surrogateSelector;
// Serialize and put to packet
binaryFormatter.Serialize(memoryStream, Value);
memoryStream.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
var bytes = memoryStream.ToArray();
writer.PutBytesWithLength(bytes);
}
}
public override bool IsValueChanged(T newValue)
{
return !newValue.Equals(Value);
}
}
}
| using LiteNetLib.Utils;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
namespace LiteNetLibHighLevel
{
public class NetFieldStruct<T> : LiteNetLibNetField<T>
where T : struct
{
public override void Deserialize(NetDataReader reader)
{
using (MemoryStream memoryStream = new MemoryStream(reader.GetBytesWithLength()))
{
var binaryFormatter = new BinaryFormatter();
// Setup Unity's structs serialization surrogates
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddAllUnitySurrogate();
binaryFormatter.SurrogateSelector = surrogateSelector;
// Deserialize
var data = binaryFormatter.Deserialize(memoryStream);
Value = (T)data;
}
}
public override void Serialize(NetDataWriter writer)
{
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
// Setup Unity's structs serialization surrogates
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddAllUnitySurrogate();
binaryFormatter.SurrogateSelector = surrogateSelector;
// Serialize and put to packet
binaryFormatter.Serialize(memoryStream, Value);
memoryStream.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
var bytes = memoryStream.ToArray();
writer.PutBytesWithLength(bytes);
}
}
public override bool IsValueChanged(T newValue)
{
return !newValue.Equals(Value);
}
}
}
|
Add a confirm to revert while wrong operation. | @model IEnumerable<MMLibrarySystem.Models.BorrowRecord>
@{
ViewBag.Title = "Borrowed Books";
}
<table id="bookList">
<tr>
<td>
Book Number
</td>
<td>
Title
</td>
<td>
Borrowed By
</td>
<td>
Borrowed Start From
</td>
<td>
State
</td>
<td>
Operation
</td>
</tr>
@{
foreach (var item in Model)
{
<tr>
<td>@item.Book.BookNumber
</td>
<td>@item.Book.BookType.Title
</td>
<td>@item.User.DisplayName
</td>
<td>@item.BorrowedDate
</td>
<td>@(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted")
</td>
<td>
@{
if (item.IsCheckedOut)
{
@Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, null)
}
else
{
@Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null)
}
}
</td>
</tr>
}
}
</table>
| @model IEnumerable<MMLibrarySystem.Models.BorrowRecord>
@{
ViewBag.Title = "Borrowed Books";
}
<table id="bookList">
<tr>
<td>
Book Number
</td>
<td>
Title
</td>
<td>
Borrowed By
</td>
<td>
Borrowed Start From
</td>
<td>
State
</td>
<td>
Operation
</td>
</tr>
@{
foreach (var item in Model)
{
<tr>
<td>@item.Book.BookNumber
</td>
<td>@item.Book.BookType.Title
</td>
<td>@item.User.DisplayName
</td>
<td>@item.BorrowedDate
</td>
<td>@(item.IsCheckedOut ? "Checked Out" : "Borrow Accepted")
</td>
<td>
@{
if (item.IsCheckedOut)
{
@Html.ActionLink("Return", "Return", "Admin", new { borrowId = @item.BorrowRecordId }, new { onclick = "return confirm('Are you sure to return this book?')" })
}
else
{
@Html.ActionLink("Check Out", "CheckOut", "Admin", new { borrowId = @item.BorrowRecordId }, null)
}
}
</td>
</tr>
}
}
</table>
|
Set MinimumInteritemSpacing and MinimumLineSpacing on flow layout | using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
namespace SimpleCollectionView
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UICollectionViewController simpleCollectionViewController;
CircleLayout circleLayout;
LineLayout lineLayout;
UICollectionViewFlowLayout flowLayout;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
// Flow Layout
flowLayout = new UICollectionViewFlowLayout (){
HeaderReferenceSize = new System.Drawing.SizeF (100, 100),
SectionInset = new UIEdgeInsets (20,20,20,20),
ScrollDirection = UICollectionViewScrollDirection.Vertical
};
// Line Layout
lineLayout = new LineLayout (){
HeaderReferenceSize = new System.Drawing.SizeF (160, 100),
ScrollDirection = UICollectionViewScrollDirection.Horizontal
};
// Circle Layout
circleLayout = new CircleLayout ();
simpleCollectionViewController = new SimpleCollectionViewController (flowLayout);
// simpleCollectionViewController = new SimpleCollectionViewController (lineLayout);
// simpleCollectionViewController = new SimpleCollectionViewController (circleLayout);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0);
window.RootViewController = simpleCollectionViewController;
window.MakeKeyAndVisible ();
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
namespace SimpleCollectionView
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UICollectionViewController simpleCollectionViewController;
CircleLayout circleLayout;
LineLayout lineLayout;
UICollectionViewFlowLayout flowLayout;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
// Flow Layout
flowLayout = new UICollectionViewFlowLayout (){
HeaderReferenceSize = new System.Drawing.SizeF (100, 100),
SectionInset = new UIEdgeInsets (20,20,20,20),
ScrollDirection = UICollectionViewScrollDirection.Vertical,
MinimumInteritemSpacing = 50, // minimum spacing between cells
MinimumLineSpacing = 50 // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal
};
// Line Layout
lineLayout = new LineLayout (){
HeaderReferenceSize = new System.Drawing.SizeF (160, 100),
ScrollDirection = UICollectionViewScrollDirection.Horizontal
};
// Circle Layout
circleLayout = new CircleLayout ();
simpleCollectionViewController = new SimpleCollectionViewController (flowLayout);
// simpleCollectionViewController = new SimpleCollectionViewController (lineLayout);
// simpleCollectionViewController = new SimpleCollectionViewController (circleLayout);
simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0);
window.RootViewController = simpleCollectionViewController;
window.MakeKeyAndVisible ();
return true;
}
}
}
|
Include header in named pipe test | using System.Threading;
using Xunit;
namespace RockLib.Messaging.NamedPipes.Tests
{
public class NamedPipesTests
{
[Fact]
public void NamedPipeMessagesAreSentAndReceived()
{
var waitHandle = new AutoResetEvent(false);
using (var receiver = new NamedPipeReceiver("foo", "test-pipe"))
{
string payload = null;
receiver.Start(m =>
{
payload = m.StringPayload;
m.Acknowledge();
waitHandle.Set();
});
using (var sender = new NamedPipeSender("foo", "test-pipe"))
{
sender.Send("Hello, world!");
}
waitHandle.WaitOne();
Assert.Equal("Hello, world!", payload);
}
}
}
}
| using System.Threading;
using Xunit;
namespace RockLib.Messaging.NamedPipes.Tests
{
public class NamedPipesTests
{
[Fact]
public void NamedPipeMessagesAreSentAndReceived()
{
var waitHandle = new AutoResetEvent(false);
using (var receiver = new NamedPipeReceiver("foo", "test-pipe"))
{
string payload = null;
string headerValue = null;
receiver.Start(m =>
{
payload = m.StringPayload;
headerValue = m.Headers.GetValue<string>("bar");
m.Acknowledge();
waitHandle.Set();
});
using (var sender = new NamedPipeSender("foo", "test-pipe"))
{
sender.Send(new SenderMessage("Hello, world!") { Headers = { { "bar", "abc" } } });
}
waitHandle.WaitOne();
Assert.Equal("Hello, world!", payload);
Assert.Equal("abc", headerValue);
}
}
}
}
|
Add SMS to list page | @model IEnumerable<alert_roster.web.Models.User>
@{
ViewBag.Title = "View Subscriptions";
}
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Subscribe")
</p>
@if (TempData["Message"] != null)
{
<div class="alert alert-info">@TempData["Message"]</div>
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailEnabled)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailEnabled)
</td>
<td>
@Html.ActionLink("Unsubscribe", "Unsubscribe", new { id = item.ID })
</td>
</tr>
}
</table>
| @model IEnumerable<alert_roster.web.Models.User>
@{
ViewBag.Title = "View Subscriptions";
}
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Subscribe")
</p>
@if (TempData["Message"] != null)
{
<div class="alert alert-info">@TempData["Message"]</div>
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailEnabled)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailEnabled)
</td>
<td>
@Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.SMSEnabled)
</td>
<td>
@Html.ActionLink("Unsubscribe", "Unsubscribe", new { id = item.ID })
</td>
</tr>
}
</table>
|
Add unit test for at least one previously mistreated formula | using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Data;
namespace ClosedXML_Tests.Excel
{
public class NumberFormatTests
{
[Test]
public void PreserveCellFormat()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var table = new DataTable();
table.Columns.Add("Date", typeof(DateTime));
for (int i = 0; i < 10; i++)
{
table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i));
}
ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd";
ws.Cell("A1").InsertData(table);
Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format);
ws.Row(1).Style.NumberFormat.Format = "yy-MM-dd";
ws.Cell("A1").InsertData(table.AsEnumerable(), true);
Assert.AreEqual("yy-MM-dd", ws.Cell("E1").Style.DateFormat.Format);
}
}
}
}
| using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Data;
namespace ClosedXML_Tests.Excel
{
public class NumberFormatTests
{
[Test]
public void PreserveCellFormat()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var table = new DataTable();
table.Columns.Add("Date", typeof(DateTime));
for (int i = 0; i < 10; i++)
{
table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i));
}
ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd";
ws.Cell("A1").InsertData(table);
Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format);
ws.Row(1).Style.NumberFormat.Format = "yy-MM-dd";
ws.Cell("A1").InsertData(table.AsEnumerable(), true);
Assert.AreEqual("yy-MM-dd", ws.Cell("E1").Style.DateFormat.Format);
}
}
[Test]
public void TestExcelNumberFormats()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var c = ws.FirstCell()
.SetValue(41573.875)
.SetDataType(XLDataType.DateTime);
c.Style.NumberFormat.SetFormat("m/d/yy\\ h:mm;@");
Assert.AreEqual("10/26/13 21:00", c.GetFormattedString());
}
}
}
}
|
Fix EarTrumpet.Web deps after - to . rename | using System.Xml.Serialization;
namespace EarTrumpet.Actions.DataModel.Serialization
{
public class AppRef
{
public static readonly string EveryAppId = "EarTrumpet.EveryApp";
public static readonly string ForegroundAppId = "EarTrumpet.ForegroundApp";
public string Id { get; set; }
public override int GetHashCode()
{
return Id == null ? 0 : Id.GetHashCode();
}
public bool Equals(AppRef other)
{
return other.Id == Id;
}
}
} | namespace EarTrumpet.Actions.DataModel.Serialization
{
public class AppRef
{
public static readonly string EveryAppId = "EarTrumpet.EveryApp";
public static readonly string ForegroundAppId = "EarTrumpet.ForegroundApp";
public string Id { get; set; }
public override int GetHashCode()
{
return Id == null ? 0 : Id.GetHashCode();
}
public bool Equals(AppRef other)
{
return other.Id == Id;
}
}
} |
Move assembly directive out of namespace | using System.Web.Routing;
using ConsolR.Hosting.Web;
using SignalR;
namespace ConsolR.Hosting
{
[assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")]
public static class Bootstrapper
{
public static void PreApplicationStart()
{
var routes = RouteTable.Routes;
routes.MapHttpHandler<Handler>("consolr/validate");
routes.MapHttpHandler<Handler>("consolr");
routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}");
}
}
}
| using System.Web.Routing;
using ConsolR.Hosting.Web;
using SignalR;
[assembly: WebActivator.PostApplicationStartMethod(typeof(ConsolR.Hosting.Bootstrapper), "PreApplicationStart")]
namespace ConsolR.Hosting
{
public static class Bootstrapper
{
public static void PreApplicationStart()
{
var routes = RouteTable.Routes;
routes.MapHttpHandler<Handler>("consolr/validate");
routes.MapHttpHandler<Handler>("consolr");
routes.MapConnection<ExecuteEndPoint>("consolr-execute", "consolr/execute/{*operation}");
}
}
}
|
Fix paging next in service client level methods | @using System.Linq;
@using AutoRest.Core.ClientModel
@using AutoRest.Core.Utilities
@using AutoRest.Java.Azure.TemplateModels
@inherits AutoRest.Core.Template<AutoRest.Java.Azure.TemplateModels.AzureServiceClientTemplateModel>
/**
* The interface defining all the services for @Model.Name to be
* used by Retrofit to perform actually REST calls.
*/
interface @Model.ServiceClientServiceType {
@foreach (AzureMethodTemplateModel method in Model.MethodTemplateModels)
{
if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
{
@: @@Multipart
}
else
{
@: @@Headers("Content-Type: @method.RequestContentType")
}
if (method.HttpMethod == HttpMethod.Delete)
{
@: @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
}
else if (method.IsPagingNextOperation)
{
@: @@GET
}
else
{
@: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
}
if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
{
@: @@Streaming
}
@: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration);
@EmptyLine
}
} | @using System.Linq;
@using AutoRest.Core.ClientModel
@using AutoRest.Core.Utilities
@using AutoRest.Java.Azure.TemplateModels
@inherits AutoRest.Core.Template<AutoRest.Java.Azure.TemplateModels.AzureServiceClientTemplateModel>
/**
* The interface defining all the services for @Model.Name to be
* used by Retrofit to perform actually REST calls.
*/
interface @Model.ServiceClientServiceType {
@foreach (AzureMethodTemplateModel method in Model.MethodTemplateModels)
{
if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
{
@: @@Multipart
}
else
{
@: @@Headers("Content-Type: @method.RequestContentType")
}
if (method.HttpMethod == HttpMethod.Delete)
{
@: @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
}
else
{
@: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
}
if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
{
@: @@Streaming
}
@: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration);
@EmptyLine
}
} |
Add missing [Test] attribute on test method | using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Strategy;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Unit.Strategy.StrategyManagerTests
{
[TestFixture]
class When_creating_a_strategy
{
StrategyManager _sut;
[SetUp]
public void BeforeEach()
{
_sut = new StrategyManager();
}
[Test]
public void The_strategy_configuration_action_is_called()
{
var theActionWasCalled = false;
_sut.UpdateStrategy<ICloneable>(strategy => { theActionWasCalled = true; });
theActionWasCalled.Should().BeTrue();
}
public void Strategy_updates_are_applied_progressively()
{
var strategies = new List<IConfigureMappingStrategy<ICloneable>>();
for (var i = 0; i < 10; i++)
{
_sut.UpdateStrategy<ICloneable>(strategy => { strategies.Add(strategy); });
}
// 10 configurations were invoked
strategies.Count.Should().Be(10);
// all the configurations were invoked on the same strategy object
strategies.Distinct().Should().HaveCount(1);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Strategy;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Unit.Strategy.StrategyManagerTests
{
[TestFixture]
class When_creating_a_strategy
{
StrategyManager _sut;
[SetUp]
public void BeforeEach()
{
_sut = new StrategyManager();
}
[Test]
public void The_strategy_configuration_action_is_called()
{
var theActionWasCalled = false;
_sut.UpdateStrategy<ICloneable>(strategy => { theActionWasCalled = true; });
theActionWasCalled.Should().BeTrue();
}
[Test]
public void Strategy_updates_are_applied_progressively()
{
var strategies = new List<IConfigureMappingStrategy<ICloneable>>();
for (var i = 0; i < 10; i++)
{
_sut.UpdateStrategy<ICloneable>(strategy => { strategies.Add(strategy); });
}
// 10 configurations were invoked
strategies.Count.Should().Be(10);
// all the configurations were invoked on the same strategy object
strategies.Distinct().Should().HaveCount(1);
}
}
} |
Allow config file to passed in | using System.Dynamic;
using System.IO;
using System.Management.Automation;
using System.Reflection;
namespace ConfigPS
{
public class Global : DynamicObject
{
readonly PowerShell ps;
public Global()
{
var fileName = Path.GetFileName(Assembly.GetCallingAssembly().CodeBase);
var configFileName = fileName + ".ps1";
ps = PowerShell.Create();
if (File.Exists(configFileName))
{
const string initScript = @"
function Add-ConfigItem($name, $value)
{
Set-Variable -Name $name -Value $value -Scope global
}
";
ps.AddScript(initScript);
ps.Invoke();
var profileScript = File.ReadAllText(configFileName);
ps.AddScript(profileScript);
ps.Invoke();
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = ps.Runspace.SessionStateProxy.GetVariable(binder.Name);
return true;
}
}
}
| using System.Dynamic;
using System.IO;
using System.Management.Automation;
using System.Reflection;
namespace ConfigPS
{
public class Global : DynamicObject
{
readonly PowerShell ps;
public Global(string configFileName = null)
{
if (configFileName == null)
{
var fileName = Path.GetFileName(Assembly.GetCallingAssembly().CodeBase);
configFileName = fileName + ".ps1";
}
ps = PowerShell.Create();
if (File.Exists(configFileName))
{
const string initScript = @"
function Add-ConfigItem($name, $value)
{
Set-Variable -Name $name -Value $value -Scope global
}
";
ps.AddScript(initScript);
ps.Invoke();
var profileScript = File.ReadAllText(configFileName);
ps.AddScript(profileScript);
ps.Invoke();
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = ps.Runspace.SessionStateProxy.GetVariable(binder.Name);
return true;
}
}
}
|
Update demo app with more comments | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RailPhase.Demo
{
class Program
{
static void Main(string[] args)
{
// Create a simple web app and serve content on to URLs.
var app = new App();
// Define the URL patterns
app.AddUrlPattern("^/$", (request) => new HttpResponse("<h1>Hello World</h1>"));
app.AddUrlPattern("^/info$", InfoView);
app.RunTestServer();
}
/// <summary>
/// A view that generates a simple request info page
/// </summary>
static HttpResponse InfoView(RailPhase.HttpRequest request)
{
// Get the template for the info page.
var render = Template.FromFile("InfoTemplate.html");
// Pass the HttpRequest as the template context, because we want
// to display information about the request. Normally, we would
// pass some custom object here, containing the information we
// want to display.
var body = render(request);
// Return a simple Http response.
// We could also return non-HTML content or error codes here
// by setting the parameters in the HttpResponse constructor.
return new HttpResponse(body);
}
}
public class DemoContext
{
public string Heading;
public string Username;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RailPhase.Demo
{
class Program
{
static void Main(string[] args)
{
// Create a simple web app and serve content on to URLs.
var app = new App();
// Define the URL patterns to respond to incoming requests.
// Any request that does not match one of these patterns will
// be served by app.NotFoundView, which defaults to a simple
// 404 message.
// Easiest way to respond to a request: return a string
app.AddUrlPattern("^/$", (request) => "Hello World");
// More complex response, see below
app.AddUrlPattern("^/info$", InfoView);
// Start listening for HTTP requests. Default port is 8080.
// This method does never return!
app.RunTestServer();
// Now you should be able to visit me in your browser on http://localhost:8080
}
/// <summary>
/// A view that generates a simple request info page
/// </summary>
static HttpResponse InfoView(RailPhase.HttpRequest request)
{
// Get the template for the info page.
var render = Template.FromFile("InfoTemplate.html");
// Pass the HttpRequest as the template context, because we want
// to display information about the request. Normally, we would
// pass some custom object here, containing the information we
// want to display.
var body = render(context: request);
// Return a simple Http response.
// We could also return non-HTML content or error codes here
// by setting the parameters in the HttpResponse constructor.
return new HttpResponse(body);
}
}
public class DemoContext
{
public string Heading;
public string Username;
}
}
|
Set DebuggingSubProcess = Debugger.IsAttached rather than a hard coded value | using System;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private const bool debuggingSubProcess = true;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (debuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
| using System;
using System.Diagnostics;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private static readonly bool DebuggingSubProcess = Debugger.IsAttached;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
settings.LogSeverity = LogSeverity.Verbose;
if (DebuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
|
Add check for possible null reference | using System;
using System.Collections.Generic;
namespace compiler.middleend.ir
{
//TODO: redisign this class and its supporting classes
public class BasicBlock
{
public string Name { get; }
public List<Instruction> Instructions{ get; set; }
public Anchor AnchorBlock { get; set; }
public BasicBlock()
{
Instructions = new List<Instruction>();
AnchorBlock = new Anchor();
}
public BasicBlock(string pName)
{
Instructions = new List<Instruction>();
Name = pName;
AnchorBlock = new Anchor();
}
public void AddInstruction(Instruction ins)
{
Instructions.Add(ins);
AnchorBlock.Insert(ins);
}
public Instruction Search(Instruction ins)
{
var instList = AnchorBlock.FindOpChain(ins.Op);
foreach(var item in instList)
{
if (item.Equals(ins))
return item;
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
namespace compiler.middleend.ir
{
//TODO: redisign this class and its supporting classes
public class BasicBlock
{
public string Name { get; }
public List<Instruction> Instructions{ get; set; }
public Anchor AnchorBlock { get; set; }
public BasicBlock()
{
Instructions = new List<Instruction>();
AnchorBlock = new Anchor();
}
public BasicBlock(string pName)
{
Instructions = new List<Instruction>();
Name = pName;
AnchorBlock = new Anchor();
}
public void AddInstruction(Instruction ins)
{
Instructions.Add(ins);
AnchorBlock.Insert(ins);
}
public Instruction Search(Instruction ins)
{
var instList = AnchorBlock.FindOpChain(ins.Op);
if (instList != null)
{
foreach (var item in instList)
{
if (item.Equals(ins))
return item;
}
}
return null;
}
}
}
|
Clean up ToComment so it handles a few edge cases a bit better | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;
namespace StackExchange.DataExplorer.Models {
public partial class Query {
public string BodyWithoutComments {
get {
ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
return pq.ExecutionSql;
}
}
public void UpdateQueryBodyComment() {
StringBuilder buffer = new StringBuilder();
if (Name != null) {
buffer.Append(ToComment(Name));
buffer.Append("\n");
}
if (Description != null) {
buffer.Append(ToComment(Description));
buffer.Append("\n");
}
buffer.Append("\n");
buffer.Append(BodyWithoutComments);
QueryBody = buffer.ToString();
}
private string ToComment(string text) {
string rval = text.Replace("\r\n", "\n");
rval = "-- " + rval;
rval = rval.Replace("\n", "\n-- ");
if (rval.Contains("\n--")) {
rval = rval.Substring(0, rval.Length - 3);
}
return rval;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.DataExplorer.Helpers;
using System.Text;
namespace StackExchange.DataExplorer.Models {
public partial class Query {
public string BodyWithoutComments {
get {
ParsedQuery pq = new ParsedQuery(this.QueryBody, null);
return pq.ExecutionSql;
}
}
public void UpdateQueryBodyComment() {
StringBuilder buffer = new StringBuilder();
if (Name != null) {
buffer.Append(ToComment(Name));
buffer.Append("\n");
}
if (Description != null) {
buffer.Append(ToComment(Description));
buffer.Append("\n");
}
buffer.Append("\n");
buffer.Append(BodyWithoutComments);
QueryBody = buffer.ToString();
}
private string ToComment(string text) {
if (string.IsNullOrEmpty(text)) return "";
if (text != null) text = text.Trim();
string rval = text.Replace("\r\n", "\n");
rval = "-- " + rval;
rval = rval.Replace("\n", "\n-- ");
return rval;
}
}
} |
Add possibility to add custom AudioObject prefab. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct CategoryItem
{
public string name;
public SoundItem[] soundItems;
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct CategoryItem
{
public string name;
public SoundItem[] soundItems;
public GameObject audioObjectPrefab;
}
|
Use default AudioObject prefab if none is assigned. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct CategoryItem
{
public string name;
public SoundItem[] soundItems;
public GameObject audioObjectPrefab;
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct CategoryItem
{
public string name;
public SoundItem[] soundItems;
public GameObject audioObjectPrefab = null;
public bool usingDefaultPrefab = true;
}
|
Update display text on the view model. | using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Validation;
using System.ComponentModel;
namespace BTCPayServer.Models.InvoicingModels
{
public class CreateInvoiceModel
{
public CreateInvoiceModel()
{
Currency = "USD";
}
[Required]
public decimal? Amount
{
get; set;
}
[Required]
public string Currency
{
get; set;
}
[Required]
public string StoreId
{
get; set;
}
public string OrderId
{
get; set;
}
[DisplayName("Item Description")]
public string ItemDesc
{
get; set;
}
[DisplayName("POS Data")]
public string PosData
{
get; set;
}
[EmailAddress]
public string BuyerEmail
{
get; set;
}
[EmailAddress]
[DisplayName("Notification Email")]
public string NotificationEmail
{
get; set;
}
[Uri]
[DisplayName("Notification Url")]
public string NotificationUrl
{
get; set;
}
public SelectList Stores
{
get;
set;
}
[DisplayName("Supported Transaction Currencies")]
public List<string> SupportedTransactionCurrencies
{
get;
set;
}
[DisplayName("Available Payment Methods")]
public SelectList AvailablePaymentMethods
{
get;
set;
}
}
}
| using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Validation;
using System.ComponentModel;
namespace BTCPayServer.Models.InvoicingModels
{
public class CreateInvoiceModel
{
public CreateInvoiceModel()
{
Currency = "USD";
}
[Required]
public decimal? Amount
{
get; set;
}
[Required]
public string Currency
{
get; set;
}
[Required]
[DisplayName("Store Id")]
public string StoreId
{
get; set;
}
[DisplayName("Order Id")]
public string OrderId
{
get; set;
}
[DisplayName("Item Description")]
public string ItemDesc
{
get; set;
}
[DisplayName("POS Data")]
public string PosData
{
get; set;
}
[EmailAddress]
[DisplayName("Buyer Email")]
public string BuyerEmail
{
get; set;
}
[EmailAddress]
[DisplayName("Notification Email")]
public string NotificationEmail
{
get; set;
}
[Uri]
[DisplayName("Notification Url")]
public string NotificationUrl
{
get; set;
}
public SelectList Stores
{
get; set;
}
[DisplayName("Supported Transaction Currencies")]
public List<string> SupportedTransactionCurrencies
{
get; set;
}
[DisplayName("Available Payment Methods")]
public SelectList AvailablePaymentMethods
{
get; set;
}
}
}
|
Set AddDate on server for new transactions | using Quibill.Web.Contexts;
using System;
using System.Collections.Generic;
using Quibill.Domain.Models;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Quibill.Domain;
namespace Quibill.Web.Controllers
{
[Authorize]
public class TransactionsController : ApiController
{
private TransactionsDbContext transactionsContext;
public TransactionsController()
{
transactionsContext = new TransactionsDbContext();
}
// GET api/values
public IEnumerable<ITransaction> Get()
{
string userName = User.Identity.GetUserId();
List<SingleTransaction> allSingleTransactions = transactionsContext.SingleTransactions.ToList();
List<RecurringTransaction> allRecurringTransactions = transactionsContext.RecurringTransactions.ToList();
List<ITransaction> allTransactions = new List<ITransaction>();
allTransactions.AddRange(allRecurringTransactions);
allTransactions.AddRange(allSingleTransactions);
return allTransactions;
}
// GET api/values/5
public int Get(int id)
{
return id;
}
// POST api/values
public void Post([FromBody]SingleTransaction singleTransaction)
{
singleTransaction.BoundUserId = User.Identity.GetUserId();
transactionsContext.SingleTransactions.Add(singleTransaction);
transactionsContext.SaveChanges();
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| using Quibill.Web.Contexts;
using System;
using System.Collections.Generic;
using Quibill.Domain.Models;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Quibill.Domain;
namespace Quibill.Web.Controllers
{
[Authorize]
public class TransactionsController : ApiController
{
private TransactionsDbContext transactionsContext;
public TransactionsController()
{
transactionsContext = new TransactionsDbContext();
}
// GET api/values
public IEnumerable<ITransaction> Get()
{
string userName = User.Identity.GetUserId();
List<SingleTransaction> allSingleTransactions = transactionsContext.SingleTransactions.ToList();
List<RecurringTransaction> allRecurringTransactions = transactionsContext.RecurringTransactions.ToList();
List<ITransaction> allTransactions = new List<ITransaction>();
allTransactions.AddRange(allRecurringTransactions);
allTransactions.AddRange(allSingleTransactions);
return allTransactions;
}
// GET api/values/5
public int Get(int id)
{
return id;
}
// POST api/values
public void Post([FromBody]SingleTransaction singleTransaction)
{
singleTransaction.BoundUserId = User.Identity.GetUserId();
singleTransaction.AddDate = DateTime.Now;
transactionsContext.SingleTransactions.Add(singleTransaction);
transactionsContext.SaveChanges();
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
Add code to start generating the methods. | // Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using SmugMug.Shared.Descriptors;
using System.Collections.Generic;
using System.Text;
namespace SmugMugCodeGen
{
public partial class CodeGen
{
public static StringBuilder BuildMethods(List<Method> list)
{
return new StringBuilder();
}
}
}
| // Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using SmugMug.Shared.Descriptors;
using System.Collections.Generic;
using System.Text;
namespace SmugMugCodeGen
{
public partial class CodeGen
{
public static StringBuilder BuildMethods(List<Method> list)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("/*");
foreach (var item in list)
{
sb.AppendLine(string.Format("[{0}] -- {1}", item.ReturnType, item.Uri));
}
sb.AppendLine("*/");
return sb;
}
}
}
|
Change default to be once per month for a year | using System;
using System.ComponentModel.DataAnnotations;
namespace Cash_Flow_Projection.Models
{
public class RepeatingEntry
{
[DataType(DataType.Date)]
public DateTime FirstDate { get; set; } = DateTime.Today;
public String Description { get; set; }
public Decimal Amount { get; set; }
public int RepeatInterval { get; set; } = 1;
public RepeatUnit Unit { get; set; } = RepeatUnit.Days;
public int RepeatIterations { get; set; } = 10;
public Account Account { get; set; } = Account.Cash;
public enum RepeatUnit
{
Days,
Weeks,
Months
}
}
} | using System;
using System.ComponentModel.DataAnnotations;
namespace Cash_Flow_Projection.Models
{
public class RepeatingEntry
{
[DataType(DataType.Date)]
public DateTime FirstDate { get; set; } = DateTime.Today;
public String Description { get; set; }
public Decimal Amount { get; set; }
public int RepeatInterval { get; set; } = 1;
public RepeatUnit Unit { get; set; } = RepeatUnit.Months;
public int RepeatIterations { get; set; } = 12;
public Account Account { get; set; } = Account.Cash;
public enum RepeatUnit
{
Days,
Weeks,
Months
}
}
} |
Use camelCase and string enums with YAML serialization | using Halforbit.DataStores.FileStores.Serialization.Json.Implementation;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
using ISerializer = Halforbit.DataStores.FileStores.Interface.ISerializer;
namespace Halforbit.DataStores.FileStores.Serialization.Yaml.Implementation
{
public class YamlSerializer : ISerializer
{
readonly JsonSerializer _jsonSerializer = new JsonSerializer();
readonly Serializer _serializer = new Serializer();
readonly Deserializer _deserializer = new Deserializer();
public Task<TValue> Deserialize<TValue>(byte[] data)
{
return Task.FromResult(JToken.FromObject(_deserializer.Deserialize<ExpandoObject>(
Encoding.UTF8.GetString(data, 0, data.Length))).ToObject<TValue>());
}
public Task<byte[]> Serialize<TValue>(TValue value)
{
return Task.FromResult(Encoding.UTF8.GetBytes(_serializer.Serialize(
JToken.FromObject(value).ToObject<ExpandoObject>())));
}
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Dynamic;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
using ISerializer = Halforbit.DataStores.FileStores.Interface.ISerializer;
namespace Halforbit.DataStores.FileStores.Serialization.Yaml.Implementation
{
public class YamlSerializer : ISerializer
{
readonly JsonSerializer _jsonSerializer;
readonly Serializer _serializer = new Serializer();
readonly Deserializer _deserializer = new Deserializer();
public YamlSerializer()
{
_jsonSerializer = new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
_jsonSerializer.Converters.Add(new StringEnumConverter { CamelCaseText = true });
}
public Task<TValue> Deserialize<TValue>(byte[] data)
{
return Task.FromResult(JToken
.FromObject(
_deserializer.Deserialize<ExpandoObject>(
Encoding.UTF8.GetString(data, 0, data.Length)),
_jsonSerializer)
.ToObject<TValue>());
}
public Task<byte[]> Serialize<TValue>(TValue value)
{
return Task.FromResult(Encoding.UTF8.GetBytes(_serializer.Serialize(
JToken.FromObject(value, _jsonSerializer).ToObject<ExpandoObject>())));
}
}
}
|
Add template for Visual Studio C++ resource files | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bumpy
{
internal sealed class Template
{
private static readonly Dictionary<string, Template> Templates = new Dictionary<string, Template>()
{
{ ".csproj", new Template(@"<(?<marker>[Vv]ersion)>(?<version>\d+\.\d+\.\d+.*)<\/[Vv]ersion>", new UTF8Encoding(false)) },
{ ".nuspec", new Template(@"<(?<marker>[Vv]ersion)>(?<version>\d+\.\d+\.\d+.*)<\/[Vv]ersion>", new UTF8Encoding(false)) },
{ "AssemblyInfo.cs", new Template(@"(?<marker>Assembly(File)?Version).*(?<version>\d+\.\d+\.\d+\.\d+)", new UTF8Encoding(true)) }
};
private Template(string regularExpression, Encoding encoding)
{
Regex = regularExpression;
Encoding = encoding;
}
public string Regex { get; }
public Encoding Encoding { get; }
public static bool TryFindTemplate(string text, out Template template)
{
var matches = Templates.Where(t => text.EndsWith(t.Key, StringComparison.OrdinalIgnoreCase)).ToList();
template = null;
if (matches.Any())
{
template = matches[0].Value;
return true;
}
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bumpy
{
internal sealed class Template
{
private static readonly Dictionary<string, Template> Templates = new Dictionary<string, Template>()
{
{ ".csproj", new Template(@"<(?<marker>[Vv]ersion)>(?<version>\d+\.\d+\.\d+.*)<\/[Vv]ersion>", new UTF8Encoding(false)) },
{ ".nuspec", new Template(@"<(?<marker>[Vv]ersion)>(?<version>\d+\.\d+\.\d+.*)<\/[Vv]ersion>", new UTF8Encoding(false)) },
{ "AssemblyInfo.cs", new Template(@"(?<marker>Assembly(File)?Version).*(?<version>\d+\.\d+\.\d+\.\d+)", new UTF8Encoding(true)) },
{ ".cs", new Template("(?<tag>(FILEVERSION|PRODUCTVERSION|FileVersion|ProductVersion))[\", ]*(?<version>\\d+[\\.,]\\d+[\\.,]\\d+[\\.,]\\d+)", Encoding.GetEncoding(1200)) }
};
private Template(string regularExpression, Encoding encoding)
{
Regex = regularExpression;
Encoding = encoding;
}
public string Regex { get; }
public Encoding Encoding { get; }
public static bool TryFindTemplate(string text, out Template template)
{
var matches = Templates.Where(t => text.EndsWith(t.Key, StringComparison.OrdinalIgnoreCase)).ToList();
template = null;
if (matches.Any())
{
template = matches[0].Value;
return true;
}
return false;
}
}
}
|
Add test for preserving empty paragraphs | using Xunit;
using System.IO;
using Xunit.Sdk;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
ConvertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
[Fact]
public void CanReadFilesWithUtf8Bom() {
assertSuccessfulConversion(
ConvertToHtml("utf8-bom.docx"),
"<p>This XML has a byte order mark.</p>");
}
[Fact]
public void EmptyParagraphsAreIgnoredByDefault() {
assertSuccessfulConversion(
ConvertToHtml("empty.docx"),
"");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
if (result.Warnings.Count > 0) {
throw new XunitException("Unexpected warnings: " + string.Join(", ", result.Warnings));
}
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> ConvertToHtml(string name) {
return new DocumentConverter().ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
| using Xunit;
using System.IO;
using Xunit.Sdk;
using System;
namespace Mammoth.Tests {
public class DocumentConverterTests {
[Fact]
public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
assertSuccessfulConversion(
ConvertToHtml("single-paragraph.docx"),
"<p>Walking on imported air</p>");
}
[Fact]
public void CanReadFilesWithUtf8Bom() {
assertSuccessfulConversion(
ConvertToHtml("utf8-bom.docx"),
"<p>This XML has a byte order mark.</p>");
}
[Fact]
public void EmptyParagraphsAreIgnoredByDefault() {
assertSuccessfulConversion(
ConvertToHtml("empty.docx"),
"");
}
[Fact]
public void EmptyParagraphsArePreservedIfIgnoreEmptyParagraphsIsFalse() {
assertSuccessfulConversion(
ConvertToHtml("empty.docx", converter => converter.PreserveEmptyParagraphs()),
"<p></p>");
}
private void assertSuccessfulConversion(IResult<string> result, string expectedValue) {
if (result.Warnings.Count > 0) {
throw new XunitException("Unexpected warnings: " + string.Join(", ", result.Warnings));
}
Assert.Equal(expectedValue, result.Value);
}
private IResult<string> ConvertToHtml(string name) {
return ConvertToHtml(name, converter => converter);
}
private IResult<string> ConvertToHtml(string name, Func<DocumentConverter, DocumentConverter> configure) {
return configure(new DocumentConverter()).ConvertToHtml(TestFilePath(name));
}
private string TestFilePath(string name) {
return Path.Combine("../../TestData", name);
}
}
}
|
Add a couple of friend assemblies | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
|
Allow specifying a default localizer. | using System;
using System.Collections.Generic;
namespace Mios.Localization.Localizers {
public class DictionaryLocalizer {
private readonly IDictionary<string, string> source;
public DictionaryLocalizer(IDictionary<string,string> source) {
this.source = source;
}
public LocalizedString Localize(string original, params object[] args) {
if(original==null) return new LocalizedString();
string localized;
source.TryGetValue(original, out localized);
if(localized!=null) {
localized = String.Format(localized, args);
}
return new LocalizedString(String.Format(original, args), localized);
}
}
} | using System;
using System.Collections.Generic;
namespace Mios.Localization.Localizers {
public class DictionaryLocalizer {
private readonly IDictionary<string, string> source;
private readonly Localizer defaultLocalizer;
public DictionaryLocalizer(IDictionary<string, string> source) : this(source, NullLocalizer.Instance) {
}
public DictionaryLocalizer(IDictionary<string,string> source, Localizer defaultLocalizer) {
this.source = source;
this.defaultLocalizer = defaultLocalizer;
}
public LocalizedString Localize(string original, params object[] args) {
if(original==null) return new LocalizedString();
string localized;
if(!source.TryGetValue(original, out localized)) {
return defaultLocalizer(original, args);
}
if(localized!=null) {
localized = String.Format(localized, args);
}
return new LocalizedString(String.Format(original, args), localized);
}
}
} |
Remove the outter try/catch in BuildRaygunClient | using System;
using System.Diagnostics;
using Mindscape.Raygun4Net;
using MarkerMetro.Unity.WinIntegration.Logging;
using MarkerMetro.Unity.WinIntegration;
namespace UnityProject.Logging
{
/// <summary>
/// Implementation of IExceptionLogger for Raygun Exception Logger.
/// </summary>
public sealed class RaygunExceptionLogger : IExceptionLogger
{
Lazy<RaygunClient> _raygun;
public bool IsEnabled { get; set; }
public RaygunExceptionLogger(string apiKey)
{
_raygun = new Lazy<RaygunClient>(() => BuildRaygunClient(apiKey));
}
RaygunClient BuildRaygunClient(string apiKey)
{
try
{
string version = null, user = null;
version = Helper.Instance.GetAppVersion();
try
{
user = Helper.Instance.GetUserDeviceId();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to get UserDeviceId: {0}", ex);
}
return new RaygunClient(apiKey)
{
ApplicationVersion = version,
User = user,
};
}
catch (Exception ex)
{
Debug.WriteLine("Failed to BuildRaygunClient", ex);
throw;
}
}
public void Send(Exception ex)
{
if (_raygun != null)
{
_raygun.Value.Send(ex);
}
}
public void Send(string message, string stackTrace)
{
if (_raygun != null)
{
_raygun.Value.Send(new WrappedException(message, stackTrace));
}
}
}
} | using System;
using System.Diagnostics;
using Mindscape.Raygun4Net;
using MarkerMetro.Unity.WinIntegration.Logging;
using MarkerMetro.Unity.WinIntegration;
namespace UnityProject.Logging
{
/// <summary>
/// Implementation of IExceptionLogger for Raygun Exception Logger.
/// </summary>
public sealed class RaygunExceptionLogger : IExceptionLogger
{
Lazy<RaygunClient> _raygun;
public bool IsEnabled { get; set; }
public RaygunExceptionLogger(string apiKey)
{
_raygun = new Lazy<RaygunClient>(() => BuildRaygunClient(apiKey));
}
RaygunClient BuildRaygunClient(string apiKey)
{
string version = null, user = null;
version = Helper.Instance.GetAppVersion();
try
{
user = Helper.Instance.GetUserDeviceId();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to get UserDeviceId: {0}", ex);
}
return new RaygunClient(apiKey)
{
ApplicationVersion = version,
User = user,
};
}
public void Send(Exception ex)
{
if (_raygun != null)
{
_raygun.Value.Send(ex);
}
}
public void Send(string message, string stackTrace)
{
if (_raygun != null)
{
_raygun.Value.Send(new WrappedException(message, stackTrace));
}
}
}
} |
Add TODO regarding use of styling in VM | namespace StarsReloaded.Client.ViewModel.Fragments
{
using System.Windows;
using GalaSoft.MvvmLight.Command;
using StarsReloaded.Client.ViewModel.Attributes;
public class CollapsiblePanelViewModel : BaseViewModel
{
private bool isExpanded;
private string header;
public CollapsiblePanelViewModel()
{
this.ToggleExpansionCommand = new RelayCommand(this.ToggleExpansion);
this.IsExpanded = true; ////TODO: save/read from user's settings
if (this.IsInDesignMode)
{
this.Header = "Some Panel";
}
}
public string Header
{
get
{
return this.header;
}
set
{
this.Set(() => this.Header, ref this.header, value);
}
}
public bool IsExpanded
{
get
{
return this.isExpanded;
}
set
{
this.Set(() => this.IsExpanded, ref this.isExpanded, value);
}
}
[DependsUpon(nameof(IsExpanded))]
public string ExpandButtonSource
=> this.IsExpanded
? "../../Resources/Buttons/panel_collapse.png"
: "../../Resources/Buttons/panel_expand.png";
[DependsUpon(nameof(IsExpanded))]
public Visibility ContentVisibility => this.IsExpanded ? Visibility.Visible : Visibility.Collapsed;
public RelayCommand ToggleExpansionCommand { get; private set; }
private void ToggleExpansion()
{
this.IsExpanded = !this.IsExpanded;
}
}
} | namespace StarsReloaded.Client.ViewModel.Fragments
{
using System.Windows;
using GalaSoft.MvvmLight.Command;
using StarsReloaded.Client.ViewModel.Attributes;
public class CollapsiblePanelViewModel : BaseViewModel
{
private bool isExpanded;
private string header;
public CollapsiblePanelViewModel()
{
this.ToggleExpansionCommand = new RelayCommand(this.ToggleExpansion);
this.IsExpanded = true; ////TODO: save/read from user's settings
if (this.IsInDesignMode)
{
this.Header = "Some Panel";
}
}
public string Header
{
get
{
return this.header;
}
set
{
this.Set(() => this.Header, ref this.header, value);
}
}
public bool IsExpanded
{
get
{
return this.isExpanded;
}
set
{
this.Set(() => this.IsExpanded, ref this.isExpanded, value);
}
}
////TODO: Do it with styling
[DependsUpon(nameof(IsExpanded))]
public string ExpandButtonSource
=> this.IsExpanded
? "../../Resources/Buttons/panel_collapse.png"
: "../../Resources/Buttons/panel_expand.png";
[DependsUpon(nameof(IsExpanded))]
public Visibility ContentVisibility => this.IsExpanded ? Visibility.Visible : Visibility.Collapsed;
public RelayCommand ToggleExpansionCommand { get; private set; }
private void ToggleExpansion()
{
this.IsExpanded = !this.IsExpanded;
}
}
} |
Check receiver has at least email property | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = (string)null;
if (receiver.GetType().GetProperty("fullname") != null)
{
displayName = receiver.fullname;
}
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = (string)null;
if (receiver.GetType().GetProperty("fullname") != null)
{
displayName = receiver.fullname;
}
if (receiver.GetType().GetProperty("email") == null)
{
throw new Exception("The receiver object must have an email property denoting who to send the e-mail to.");
}
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
|
Add extra extension method for getting URI | using System;
namespace Glimpse.Web
{
public static class HttpRequestExtension
{
public static string Uri(this IHttpRequest request)
{
return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
}
}
} | using System;
namespace Glimpse.Web
{
public static class HttpRequestExtension
{
public static string Uri(this IHttpRequest request)
{
return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
}
public static string UriAbsolute(this IHttpRequest request)
{
return $"{request.Path}{request.QueryString}";
}
}
} |
Remove pause at end (left in accidentally) | using System;
namespace UpVer
{
class Program
{
static void Main(string[] args)
{
try
{
var settings = new Settings(args);
var updater = new VersionUpdater(settings);
var changes = updater.Process();
if (settings.Read)
{
Console.WriteLine("Current version: " + changes.Version(x => x.From));
}
else
{
Console.WriteLine("Bumped version from " + changes.Version(x => x.From) + " to " + changes.Version(x => x.To));
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
| using System;
namespace UpVer
{
class Program
{
static void Main(string[] args)
{
try
{
var settings = new Settings(args);
var updater = new VersionUpdater(settings);
var changes = updater.Process();
if (settings.Read)
{
Console.WriteLine("Current version: " + changes.Version(x => x.From));
}
else
{
Console.WriteLine("Bumped version from " + changes.Version(x => x.From) + " to " + changes.Version(x => x.To));
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
}
}
}
}
|
Add bootstrap and jquery using bower package management. | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link rel="stylesheet" type="text/css" href="~/css/styles.css" />
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/styles.css" />
</head>
<body>
<div>
@RenderBody()
</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.