Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Support full screen now that core MonoMac supports it | using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using Eto.Forms;
namespace Eto.Test.Mac
{
class Startup
{
static void Main (string [] args)
{
AddStyles ();
var generator = new Eto.Platform.Mac.Generator ();
var app = new TestApplication (generator);
app.Run (args);
}
static void AddStyles ()
{
// support full screen mode!
Style.Add<Window, NSWindow> ("main", (widget, control) => {
//control.CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary; // not in monomac/master yet..
});
Style.Add<Application, NSApplication> ("application", (widget, control) => {
if (control.RespondsToSelector (new Selector ("presentationOptions:"))) {
control.PresentationOptions |= NSApplicationPresentationOptions.FullScreen;
}
});
// other styles
Style.Add<TreeView, NSScrollView> ("sectionList", (widget, control) => {
control.BorderType = NSBorderType.NoBorder;
var table = control.DocumentView as NSTableView;
table.SelectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList;
});
}
}
}
| using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using Eto.Forms;
namespace Eto.Test.Mac
{
class Startup
{
static void Main (string [] args)
{
AddStyles ();
var generator = new Eto.Platform.Mac.Generator ();
var app = new TestApplication (generator);
app.Run (args);
}
static void AddStyles ()
{
// support full screen mode!
Style.Add<Window, NSWindow> ("main", (widget, control) => {
control.CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary;
});
Style.Add<Application, NSApplication> ("application", (widget, control) => {
if (control.RespondsToSelector (new Selector ("presentationOptions:"))) {
control.PresentationOptions |= NSApplicationPresentationOptions.FullScreen;
}
});
// other styles
Style.Add<TreeView, NSScrollView> ("sectionList", (widget, control) => {
control.BorderType = NSBorderType.NoBorder;
var table = control.DocumentView as NSTableView;
table.SelectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList;
});
}
}
}
|
Enable raven studio for port 8081 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using DragonContracts.Models;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Database.Server.Responders;
namespace DragonContracts.Base
{
public class RavenDbController : ApiController
{
public IDocumentStore Store { get { return LazyDocStore.Value; } }
private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new EmbeddableDocumentStore()
{
DataDirectory = "App_Data/Raven"
};
docStore.Initialize();
return docStore;
});
public IAsyncDocumentSession Session { get; set; }
public async override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
using (Session = Store.OpenAsyncSession())
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
await Session.SaveChangesAsync();
return result;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using DragonContracts.Models;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Database.Config;
using Raven.Database.Server.Responders;
namespace DragonContracts.Base
{
public class RavenDbController : ApiController
{
private const int RavenWebUiPort = 8081;
public IDocumentStore Store { get { return LazyDocStore.Value; } }
private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new EmbeddableDocumentStore()
{
DataDirectory = "App_Data/Raven",
UseEmbeddedHttpServer = true
};
docStore.Configuration.Port = RavenWebUiPort;
Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(RavenWebUiPort);
docStore.Initialize();
return docStore;
});
public IAsyncDocumentSession Session { get; set; }
public async override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
using (Session = Store.OpenAsyncSession())
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
await Session.SaveChangesAsync();
return result;
}
}
}
} |
Replace test with test stub | #region Usings
using System.Linq;
using System.Web.Mvc;
using NUnit.Framework;
using WebApplication.Controllers;
using WebApplication.Models;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var formCollection = new FormCollection();
formCollection["Name"] = "Habit";
var habitController = new HabitController();
habitController.Create(formCollection);
var habit = ApplicationDbContext.Create().Habits.Single();
Assert.AreEqual("Habit", habit.Name);
}
}
} | #region Usings
using NUnit.Framework;
#endregion
namespace UnitTests
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Assert.True(true);
}
}
} |
Add virtual pre/post build methods. | using UnityEngine;
using UnityEditor;
namespace UnityBuild
{
public abstract class BuildSettings
{
public abstract string binName { get; }
public abstract string binPath { get; }
public abstract string[] scenesInBuild { get; }
public abstract string[] copyToBuild { get; }
//// The name of executable file (e.g. mygame.exe, mygame.app)
//public const string BIN_NAME = "mygame";
//// The base path where builds are output.
//// Path is relative to the Unity project's base folder unless an absolute path is given.
//public const string BIN_PATH = "bin";
//// A list of scenes to include in the build. The first listed scene will be loaded first.
//public static string[] scenesInBuild = new string[] {
// // "Assets/Scenes/scene1.unity",
// // "Assets/Scenes/scene2.unity",
// // ...
//};
//// A list of files/directories to include with the build.
//// Paths are relative to Unity project's base folder unless an absolute path is given.
//public static string[] copyToBuild = new string[] {
// // "DirectoryToInclude/",
// // "FileToInclude.txt",
// // ...
//};
}
} | using UnityEngine;
using UnityEditor;
namespace UnityBuild
{
public abstract class BuildSettings
{
public abstract string binName { get; }
public abstract string binPath { get; }
public abstract string[] scenesInBuild { get; }
public abstract string[] copyToBuild { get; }
public virtual void PreBuild()
{
}
public virtual void PostBuild()
{
}
}
} |
Change mask variables to const values, remove from constructor | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJLib.Types
{
class FixedPoint
{
public int IntegralPart { get; set; }
public int DecimalPart { get; set; }
public FixedPoint(byte[] data)
{
if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }
byte[] _data = new byte[2];
data.CopyTo(_data, 0);
var signMask = (byte)128;
var integralMask = (byte)112;
var firstPartOfDecimalMask = (byte)15;
bool isNegative = (_data[0] & signMask) == 128;
int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1);
int decimalPart = (_data[0] & firstPartOfDecimalMask);
decimalPart <<= 8;
decimalPart += data[1];
IntegralPart = integralPart;
DecimalPart = decimalPart;
}
public override string ToString()
{
return IntegralPart + "." + DecimalPart;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJLib.Types
{
class FixedPoint
{
public int IntegralPart { get; set; }
public int DecimalPart { get; set; }
const byte SIGN_MASK = 128;
const byte INTEGRAL_MASK = 112;
const byte MANTISSA_MASK = 15;
public FixedPoint(byte[] data)
{
if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }
byte[] _data = new byte[2];
data.CopyTo(_data, 0);
bool isNegative = (_data[0] & SIGN_MASK) == 128;
int integralPart = (_data[0] & INTEGRAL_MASK) * (isNegative ? -1 : 1);
int decimalPart = (_data[0] & MANTISSA_MASK);
decimalPart <<= 8;
decimalPart += data[1];
IntegralPart = integralPart;
DecimalPart = decimalPart;
}
public override string ToString()
{
return IntegralPart + "." + DecimalPart;
}
}
}
|
Add SDL support to SampleGame | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Platform;
using osu.Framework;
namespace SampleGame.Desktop
{
public static class Program
{
[STAThread]
public static void Main()
{
using (GameHost host = Host.GetSuitableHost(@"sample-game"))
using (Game game = new SampleGameGame())
host.Run(game);
}
}
}
| // 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.Linq;
using osu.Framework;
using osu.Framework.Platform;
namespace SampleGame.Desktop
{
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
bool useSdl = args.Contains(@"--sdl");
using (GameHost host = Host.GetSuitableHost(@"sample-game", useSdl: useSdl))
using (Game game = new SampleGameGame())
host.Run(game);
}
}
}
|
Hide irrelevant tabs when the Writing System is a voice one. | using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.WritingSystems
{
public partial class WSPropertiesTabControl : UserControl
{
private WritingSystemSetupModel _model;
public WSPropertiesTabControl()
{
InitializeComponent();
}
public void BindToModel(WritingSystemSetupModel model)
{
_model = model;
_identifiersControl.BindToModel(_model);
_fontControl.BindToModel(_model);
_keyboardControl.BindToModel(_model);
_sortControl.BindToModel(_model);
_spellingControl.BindToModel(_model);
}
}
}
| using System;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.WritingSystems
{
public partial class WSPropertiesTabControl : UserControl
{
private WritingSystemSetupModel _model;
public WSPropertiesTabControl()
{
InitializeComponent();
}
public void BindToModel(WritingSystemSetupModel model)
{
if (_model != null)
{
_model.SelectionChanged -= ModelChanged;
_model.CurrentItemUpdated -= ModelChanged;
}
_model = model;
_identifiersControl.BindToModel(_model);
_fontControl.BindToModel(_model);
_keyboardControl.BindToModel(_model);
_sortControl.BindToModel(_model);
_spellingControl.BindToModel(_model);
if (_model != null)
{
_model.SelectionChanged+= ModelChanged;
_model.CurrentItemUpdated += ModelChanged;
}
this.Disposed += OnDisposed;
}
private void ModelChanged(object sender, EventArgs e)
{
if( !_model.CurrentIsVoice &&
_tabControl.Controls.Contains(_spellingPage))
{
return;// don't mess if we really don't need a change
}
_tabControl.Controls.Clear();
this._tabControl.Controls.Add(this._identifiersPage);
if( !_model.CurrentIsVoice)
{
this._tabControl.Controls.Add(this._spellingPage);
this._tabControl.Controls.Add(this._fontsPage);
this._tabControl.Controls.Add(this._keyboardsPage);
this._tabControl.Controls.Add(this._sortingPage);
}
}
void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
_model.SelectionChanged -= ModelChanged;
}
}
}
|
Remove sending big data test. | using System;
using System.Linq;
using System.Threading;
using Moq;
using SignalR.Client.Transports;
using SignalR.Hosting.Memory;
using Xunit;
namespace SignalR.Client.Tests
{
public class ConnectionFacts
{
public class Start
{
[Fact]
public void FailsIfProtocolVersionIsNull()
{
var connection = new Connection("http://test");
var transport = new Mock<IClientTransport>();
transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
{
ProtocolVersion = null
}));
var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
var ex = aggEx.Unwrap();
Assert.IsType(typeof(InvalidOperationException), ex);
Assert.Equal("Incompatible protocol version.", ex.Message);
}
}
public class Received
{
[Fact]
public void SendingBigData()
{
var host = new MemoryHost();
host.MapConnection<SampleConnection>("/echo");
var connection = new Connection("http://foo/echo");
var wh = new ManualResetEventSlim();
var n = 0;
var target = 20;
connection.Received += data =>
{
n++;
if (n == target)
{
wh.Set();
}
};
connection.Start(host).Wait();
var conn = host.ConnectionManager.GetConnection<SampleConnection>();
for (int i = 0; i < target; ++i)
{
var node = new BigData();
conn.Broadcast(node).Wait();
Thread.Sleep(1000);
}
Assert.True(wh.Wait(TimeSpan.FromMinutes(1)), "Timed out");
}
public class BigData
{
public string[] Dummy
{
get
{
return Enumerable.Range(0, 1000).Select(x => new String('*', 500)).ToArray();
}
}
}
public class SampleConnection : PersistentConnection
{
}
}
}
}
| using System;
using System.Linq;
using System.Threading;
using Moq;
using SignalR.Client.Transports;
using SignalR.Hosting.Memory;
using Xunit;
namespace SignalR.Client.Tests
{
public class ConnectionFacts
{
public class Start
{
[Fact]
public void FailsIfProtocolVersionIsNull()
{
var connection = new Connection("http://test");
var transport = new Mock<IClientTransport>();
transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
{
ProtocolVersion = null
}));
var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
var ex = aggEx.Unwrap();
Assert.IsType(typeof(InvalidOperationException), ex);
Assert.Equal("Incompatible protocol version.", ex.Message);
}
}
}
}
|
Remove commented code and unused usings | using System;
using System.Collections.Generic;
using Baseline;
using Confluent.Kafka;
using Jasper.Configuration;
using Jasper.Runtime.Routing;
namespace Jasper.ConfluentKafka.Internal
{
public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration>
{
//Dictionary<Uri, ProducerConfig> producerConfigs;
//public KafkaTopicRouter(Dictionary<Uri, ProducerConfig> producerConfigs)
//{
//}
public override Uri BuildUriForTopic(string topicName)
{
var endpoint = new KafkaEndpoint
{
IsDurable = true,
TopicName = topicName
};
return endpoint.Uri;
}
public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName,
IEndpoints endpoints)
{
var uri = BuildUriForTopic(topicName);
var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri);
return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint);
}
}
}
| using System;
using Baseline;
using Jasper.Configuration;
using Jasper.Runtime.Routing;
namespace Jasper.ConfluentKafka.Internal
{
public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration>
{
public override Uri BuildUriForTopic(string topicName)
{
var endpoint = new KafkaEndpoint
{
IsDurable = true,
TopicName = topicName
};
return endpoint.Uri;
}
public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName,
IEndpoints endpoints)
{
var uri = BuildUriForTopic(topicName);
var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri);
return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint);
}
}
}
|
Fix force selector reset clipping error. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Zenject;
public class FollowTarget : MonoBehaviour
{
[Inject]
public ForceSelector ForceSelector { get; set; }
public Rigidbody targetRb;
public float distanceToReset = 0.1f;
public float velocityThresh;
public float moveToTargetSpeed;
public bool isAtTarget;
void Update ()
{
isAtTarget = Vector3.Distance(targetRb.transform.position, transform.position) <= distanceToReset;
if (targetRb.velocity.magnitude < velocityThresh && !isAtTarget)
{
transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed);
}
ForceSelector.IsRunning = isAtTarget;
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UniRx;
using UnityEngine;
using Zenject;
public class FollowTarget : MonoBehaviour
{
[Inject]
public ForceSelector ForceSelector { get; set; }
public Rigidbody targetRb;
public float velocityThresh;
public float moveToTargetSpeed;
public float distanceToResume;
public float distanceToReset;
private IDisposable sub;
void Start()
{
sub = Observable
.IntervalFrame(5)
.Select(_ => Vector3.Distance(targetRb.transform.position, transform.position))
.Hysteresis((d, referenceDist) => d - referenceDist, distanceToResume, distanceToReset)
.Subscribe(isMoving =>
{
ForceSelector.IsRunning = !isMoving;
});
}
void OnDestroy()
{
if (sub != null)
{
sub.Dispose();
sub = null;
}
}
void Update ()
{
if (targetRb.velocity.magnitude < velocityThresh && !ForceSelector.IsRunning)
{
transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed);
}
}
}
|
Remove profanity - don't want to alienate folk | using Bands.Output;
using System;
namespace Bands.GettingStarted
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Getting started with Bands!");
var payload = new CounterPayload();
var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo);
var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand);
var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand);
outerConsoleBand.Enter(payload);
Console.WriteLine("Kinda badass, right?");
Console.Read();
}
public static void CallAddTwo(CounterPayload payload)
{
Console.WriteLine("Calling payload.AddTwo()");
payload.AddTwo();
}
}
}
| using Bands.Output;
using System;
namespace Bands.GettingStarted
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Getting started with Bands!");
var payload = new CounterPayload();
var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo);
var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand);
var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand);
outerConsoleBand.Enter(payload);
Console.WriteLine("Kinda awesome, right?");
Console.Read();
}
public static void CallAddTwo(CounterPayload payload)
{
Console.WriteLine("Calling payload.AddTwo()");
payload.AddTwo();
}
}
}
|
Support for parsing inequality operator with integral operands. | using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
}
} | using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;
namespace TestStack.FluentMVCTesting.Tests.Internal
{
[TestFixture]
public class ExpressionInspectorShould
{
[Test]
public void Correctly_parse_equality_comparison_with_string_operands()
{
Expression<Func<string, bool>> func = text => text == "any";
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("text => text == \"any\"", actual);
}
[Test]
public void Correctly_parse_equality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number == 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number == 5", actual);
}
[Test]
public void Correctly_parse_inequality_comparison_with_int_operands()
{
Expression<Func<int, bool>> func = number => number != 5;
ExpressionInspector sut = new ExpressionInspector();
var actual = sut.Inspect(func);
Assert.AreEqual("number => number != 5", actual);
}
}
} |
Fix failing test ORDRSP after change on Condition stacking behavior | using indice.Edi.Serialization;
using System;
using System.Collections.Generic;
namespace indice.Edi.Tests.Models
{
public class Interchange_ORDRSP
{
public Message_ORDRSP Message { get; set; }
}
[EdiMessage]
public class Message_ORDRSP
{
[EdiCondition("Z01", Path = "IMD/1/0")]
[EdiCondition("Z10", Path = "IMD/1/0")]
public List<IMD> IMD_List { get; set; }
[EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")]
public IMD IMD_Other { get; set; }
/// <summary>
/// Item Description
/// </summary>
[EdiSegment, EdiPath("IMD")]
public class IMD
{
[EdiValue(Path = "IMD/0")]
public string FieldA { get; set; }
[EdiValue(Path = "IMD/1")]
public string FieldB { get; set; }
[EdiValue(Path = "IMD/2")]
public string FieldC { get; set; }
}
}
}
| using indice.Edi.Serialization;
using System;
using System.Collections.Generic;
namespace indice.Edi.Tests.Models
{
public class Interchange_ORDRSP
{
public Message_ORDRSP Message { get; set; }
}
[EdiMessage]
public class Message_ORDRSP
{
[EdiCondition("Z01", "Z10", Path = "IMD/1/0")]
public List<IMD> IMD_List { get; set; }
[EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")]
public IMD IMD_Other { get; set; }
/// <summary>
/// Item Description
/// </summary>
[EdiSegment, EdiPath("IMD")]
public class IMD
{
[EdiValue(Path = "IMD/0")]
public string FieldA { get; set; }
[EdiValue(Path = "IMD/1")]
public string FieldB { get; set; }
[EdiValue(Path = "IMD/2")]
public string FieldC { get; set; }
}
}
}
|
Set message id by official's highest | namespace Suriyun.UnityIAP
{
public class IAPNetworkMessageId
{
public const short ToServerBuyProductMsgId = 3000;
public const short ToServerRequestProducts = 3001;
public const short ToClientResponseProducts = 3002;
}
}
| using UnityEngine.Networking;
namespace Suriyun.UnityIAP
{
public class IAPNetworkMessageId
{
// Developer can changes these Ids to avoid hacking while hosting
public const short ToServerBuyProductMsgId = MsgType.Highest + 201;
public const short ToServerRequestProducts = MsgType.Highest + 202;
public const short ToClientResponseProducts = MsgType.Highest + 203;
}
}
|
Fix hold note masks not working | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using OpenTK.Graphics;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class HoldNoteMask : HitObjectMask
{
private readonly BodyPiece body;
public HoldNoteMask(DrawableHoldNote hold)
: base(hold)
{
Position = hold.Position;
var holdObject = hold.HitObject;
InternalChildren = new Drawable[]
{
new NoteMask(hold.Head),
new NoteMask(hold.Tail),
body = new BodyPiece
{
AccentColour = Color4.Transparent
},
};
holdObject.ColumnChanged += _ => Position = hold.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
body.BorderColour = colours.Yellow;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using OpenTK.Graphics;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class HoldNoteMask : HitObjectMask
{
private readonly BodyPiece body;
public HoldNoteMask(DrawableHoldNote hold)
: base(hold)
{
var holdObject = hold.HitObject;
InternalChildren = new Drawable[]
{
new HoldNoteNoteMask(hold.Head),
new HoldNoteNoteMask(hold.Tail),
body = new BodyPiece
{
AccentColour = Color4.Transparent
},
};
holdObject.ColumnChanged += _ => Position = hold.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
body.BorderColour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
}
private class HoldNoteNoteMask : NoteMask
{
public HoldNoteNoteMask(DrawableNote note)
: base(note)
{
Select();
}
protected override void Update()
{
base.Update();
Position = HitObject.DrawPosition;
}
}
}
}
|
Fix bug where window instance was null on world map. | using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
| using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior (go to the world map)
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// don't add a new window if the window is already there; if it's not create a new one.
if (PrepareLanding.Instance.MainWindow == null)
PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
|
Reword settings text to be ruleset agnostic | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double>
{
LabelText = "Background dim",
Bindable = config.GetBindable<double>(OsuSetting.DimLevel),
KeyboardStep = 0.1f
},
new SettingsSlider<double>
{
LabelText = "Background blur",
Bindable = config.GetBindable<double>(OsuSetting.BlurLevel),
KeyboardStep = 0.1f
},
new SettingsCheckbox
{
LabelText = "Show score overlay",
Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface)
},
new SettingsCheckbox
{
LabelText = "Always show key overlay",
Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay)
},
new SettingsCheckbox
{
LabelText = "Show approach circle on first \"Hidden\" object",
Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility)
},
};
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsSlider<double>
{
LabelText = "Background dim",
Bindable = config.GetBindable<double>(OsuSetting.DimLevel),
KeyboardStep = 0.1f
},
new SettingsSlider<double>
{
LabelText = "Background blur",
Bindable = config.GetBindable<double>(OsuSetting.BlurLevel),
KeyboardStep = 0.1f
},
new SettingsCheckbox
{
LabelText = "Show score overlay",
Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface)
},
new SettingsCheckbox
{
LabelText = "Always show key overlay",
Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay)
},
new SettingsCheckbox
{
LabelText = "Increase visibility of first object with \"Hidden\" mod",
Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility)
},
};
}
}
}
|
Reduce the amount of persisted city statistics | using System.Collections.Generic;
using System.Linq;
using Mirage.Urbanization.ZoneStatisticsQuerying;
using System.Collections.Immutable;
namespace Mirage.Urbanization.Simulation.Persistence
{
public class PersistedCityStatisticsCollection
{
private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty;
private PersistedCityStatisticsWithFinancialData _mostRecentStatistics;
public void Add(PersistedCityStatisticsWithFinancialData statistics)
{
_persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics);
if (_persistedCityStatistics.Count() > 5200)
_persistedCityStatistics = _persistedCityStatistics.Dequeue();
_mostRecentStatistics = statistics;
}
public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics()
{
return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics);
}
public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll()
{
return _persistedCityStatistics;
}
}
} | using System.Collections.Generic;
using System.Linq;
using Mirage.Urbanization.ZoneStatisticsQuerying;
using System.Collections.Immutable;
namespace Mirage.Urbanization.Simulation.Persistence
{
public class PersistedCityStatisticsCollection
{
private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty;
private PersistedCityStatisticsWithFinancialData _mostRecentStatistics;
public void Add(PersistedCityStatisticsWithFinancialData statistics)
{
_persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics);
if (_persistedCityStatistics.Count() > 960)
_persistedCityStatistics = _persistedCityStatistics.Dequeue();
_mostRecentStatistics = statistics;
}
public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics()
{
return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics);
}
public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll()
{
return _persistedCityStatistics;
}
}
} |
Switch Collapse function to correctly call the Collapse function of the expand pattern | using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;
namespace FlaUI.Core.AutomationElements.PatternElements
{
/// <summary>
/// An element that supports the <see cref="IExpandCollapsePattern"/>.
/// </summary>
public class ExpandCollapseAutomationElement : AutomationElement
{
public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
{
}
public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;
/// <summary>
/// Gets the current expand / collapse state.
/// </summary>
public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;
/// <summary>
/// Expands the element.
/// </summary>
public void Expand()
{
ExpandCollapsePattern.Expand();
}
/// <summary>
/// Collapses the element.
/// </summary>
public void Collapse()
{
ExpandCollapsePattern.Expand();
}
}
}
| using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;
namespace FlaUI.Core.AutomationElements.PatternElements
{
/// <summary>
/// An element that supports the <see cref="IExpandCollapsePattern"/>.
/// </summary>
public class ExpandCollapseAutomationElement : AutomationElement
{
public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
{
}
public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;
/// <summary>
/// Gets the current expand / collapse state.
/// </summary>
public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;
/// <summary>
/// Expands the element.
/// </summary>
public void Expand()
{
ExpandCollapsePattern.Expand();
}
/// <summary>
/// Collapses the element.
/// </summary>
public void Collapse()
{
ExpandCollapsePattern.Collapse();
}
}
}
|
Fix tag line for Telegram | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;
namespace Core.Services.Crosspost
{
public class TelegramCrosspostService : ICrossPostService
{
private readonly Core.Logging.ILogger _logger;
private readonly string _token;
private readonly string _name;
public TelegramCrosspostService(string token, string name, ILogger logger)
{
_logger = logger;
_token = token;
_name = name;
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
var sb = new StringBuilder();
sb.Append(message);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(link);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(string.Join(", ", tags));
try
{
var bot = new TelegramBotClient(_token);
await bot.SendTextMessageAsync(_name, sb.ToString());
_logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");
}
catch (Exception ex)
{
_logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;
namespace Core.Services.Crosspost
{
public class TelegramCrosspostService : ICrossPostService
{
private readonly Core.Logging.ILogger _logger;
private readonly string _token;
private readonly string _name;
public TelegramCrosspostService(string token, string name, ILogger logger)
{
_logger = logger;
_token = token;
_name = name;
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
var sb = new StringBuilder();
sb.Append(message);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(link);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(string.Join(" ", tags));
try
{
var bot = new TelegramBotClient(_token);
await bot.SendTextMessageAsync(_name, sb.ToString());
_logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");
}
catch (Exception ex)
{
_logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
}
}
}
} |
Fix test failure due to triangle skin no longer being null intests | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Tests.Visual.Gameplay
{
public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
{
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[SetUp]
public void SetUp() => Schedule(() =>
{
SetContents(skin =>
{
var implementation = skin != null
? CreateLegacyImplementation()
: CreateDefaultImplementation();
implementation.Anchor = Anchor.Centre;
implementation.Origin = Anchor.Centre;
return implementation;
});
});
protected abstract Drawable CreateDefaultImplementation();
protected abstract Drawable CreateLegacyImplementation();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual.Gameplay
{
public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
{
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[SetUp]
public void SetUp() => Schedule(() =>
{
SetContents(skin =>
{
var implementation = skin is not TrianglesSkin
? CreateLegacyImplementation()
: CreateDefaultImplementation();
implementation.Anchor = Anchor.Centre;
implementation.Origin = Anchor.Centre;
return implementation;
});
});
protected abstract Drawable CreateDefaultImplementation();
protected abstract Drawable CreateLegacyImplementation();
}
}
|
Revert "the wrong id was used for getting the correct destination url." | using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models.Mapping
{
internal class RedirectUrlMapperProfile : Profile
{
public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
{
CreateMap<IRedirectUrl, ContentRedirectUrl>()
.ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
.ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
.ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
}
private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.ContentId, item.Culture);
}
}
| using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models.Mapping
{
internal class RedirectUrlMapperProfile : Profile
{
public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
{
CreateMap<IRedirectUrl, ContentRedirectUrl>()
.ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
.ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
.ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
}
private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.Id, item.Culture);
}
}
|
Add request and 'methodresponse' type in JSON body to account for other response types using the WebSocket APIs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Snowflake.Ajax
{
public class JSResponse : IJSResponse
{
public IJSRequest Request { get; private set; }
public dynamic Payload { get; private set; }
public bool Success { get; set; }
public JSResponse(IJSRequest request, dynamic payload, bool success = true)
{
this.Request = request;
this.Payload = payload;
this.Success = success;
}
public string GetJson()
{
return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
}
private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
{
if (request.MethodParameters.ContainsKey("jsoncallback"))
{
return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"payload", output},
{"success", success}
}) + ");";
}
else
{
return JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"payload", output},
{"success", success}
});
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Snowflake.Ajax
{
public class JSResponse : IJSResponse
{
public IJSRequest Request { get; private set; }
public dynamic Payload { get; private set; }
public bool Success { get; set; }
public JSResponse(IJSRequest request, dynamic payload, bool success = true)
{
this.Request = request;
this.Payload = payload;
this.Success = success;
}
public string GetJson()
{
return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
}
private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
{
if (request.MethodParameters.ContainsKey("jsoncallback"))
{
return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"request", request},
{"payload", output},
{"success", success},
{"type", "methodresponse"}
}) + ");";
}
else
{
return JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"request", request},
{"payload", output},
{"success", success},
{"type", "methodresponse"}
});
}
}
}
}
|
Tidy up github api calling code | using System.Web.Mvc;
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Web.Caching;
using System;
namespace Website.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Benefits()
{
return View();
}
public ActionResult Download()
{
return View();
}
public ActionResult Licensing()
{
return View();
}
public ActionResult Support()
{
return View();
}
public ActionResult Contact()
{
return View();
}
public ActionResult Donate()
{
var contributors = HttpContext.Cache.Get("github.contributors") as IEnumerable<Contributor>;
if (contributors == null)
{
var url = "https://api.github.com/repos/andrewdavey/cassette/contributors";
var client = new WebClient();
var json = client.DownloadString(url);
contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json);
HttpContext.Cache.Insert("github.contributors", contributors, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
}
ViewBag.Contributors = contributors;
return View();
}
public ActionResult Resources()
{
return View();
}
}
public class Contributor
{
public string avatar_url { get; set; }
public string login { get; set; }
public string url { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Caching;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace Website.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Benefits()
{
return View();
}
public ActionResult Download()
{
return View();
}
public ActionResult Licensing()
{
return View();
}
public ActionResult Support()
{
return View();
}
public ActionResult Contact()
{
return View();
}
public ActionResult Donate()
{
var contributors = GetContributors();
ViewBag.Contributors = contributors;
return View();
}
IEnumerable<Contributor> GetContributors()
{
const string cacheKey = "github.contributors";
var contributors = HttpContext.Cache.Get(cacheKey) as IEnumerable<Contributor>;
if (contributors != null) return contributors;
var json = DownoadContributorsJson();
contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json);
HttpContext.Cache.Insert(
cacheKey,
contributors,
null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromDays(1)
);
return contributors;
}
static string DownoadContributorsJson()
{
using (var client = new WebClient())
{
return client.DownloadString("https://api.github.com/repos/andrewdavey/cassette/contributors");
}
}
public ActionResult Resources()
{
return View();
}
}
public class Contributor
{
public string avatar_url { get; set; }
public string login { get; set; }
public string url { get; set; }
}
} |
Add DecryptionInProgress for EncryptionStatus enum | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.Compute.Models
{
enum EncryptionStatus
{
Encrypted,
NotEncrypted,
NotMounted,
EncryptionInProgress,
VMRestartPending,
Unknown
}
class AzureDiskEncryptionStatusContext
{
public EncryptionStatus OsVolumeEncrypted { get; set; }
public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
public EncryptionStatus DataVolumesEncrypted { get; set; }
public string ProgressMessage { get; set; }
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.Compute.Models
{
enum EncryptionStatus
{
Encrypted,
NotEncrypted,
NotMounted,
DecryptionInProgress,
EncryptionInProgress,
VMRestartPending,
Unknown
}
class AzureDiskEncryptionStatusContext
{
public EncryptionStatus OsVolumeEncrypted { get; set; }
public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
public EncryptionStatus DataVolumesEncrypted { get; set; }
public string ProgressMessage { get; set; }
}
}
|
Add analytics event for package rate | @using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@model Package
@{
bool editable = Convert.ToBoolean(ViewData["editable"]);
string ratingId = GuidHelper.GetUniqueKey(16);
}
@if (Model.RatingsAverage.HasValue || editable)
{
<div id="@ratingId" class="rating">
@{
int rating = 0;
if (Model.RatingsAverage.HasValue)
{
rating = (int)Math.Round(Model.RatingsAverage.Value);
}
}
@for (int i = 1; i <= 5; i++)
{
@Html.RadioButton("newrate", i, rating == i)
}
</div>
<span class="rating-response"></span>
}
<script language="javascript">
$("#@(ratingId)").stars({
oneVoteOnly: true,
@if (!editable)
{
@:disabled: true,
}
callback: function(ui, type, value){
var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value;
$("#@(ratingId)_iframe").get(0).src = url;
$(".rating-response").text("Thanks for your rating!");
}
});
</script>
@if (editable)
{
<iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe>
} | @using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@model Package
@{
bool editable = Convert.ToBoolean(ViewData["editable"]);
string ratingId = GuidHelper.GetUniqueKey(16);
}
@if (Model.RatingsAverage.HasValue || editable)
{
<div id="@ratingId" class="rating">
@{
int rating = 0;
if (Model.RatingsAverage.HasValue)
{
rating = (int)Math.Round(Model.RatingsAverage.Value);
}
}
@for (int i = 1; i <= 5; i++)
{
@Html.RadioButton("newrate", i, rating == i)
}
</div>
<span class="rating-response"></span>
}
<script language="javascript">
$("#@(ratingId)").stars({
oneVoteOnly: true,
@if (!editable)
{
@:disabled: true,
}
callback: function(ui, type, value){
var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value;
$("#@(ratingId)_iframe").get(0).src = url;
$(".rating-response").text("Thanks for your rating!");
// Track the rating event in analytics
debugger;
_gaq.push([
'_trackEvent',
'Package:@Model.Name',
'Rate',
value,
value]);
}
});
</script>
@if (editable)
{
<iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe>
} |
Check if status label is constructed before executing update | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
}
public override void Update(GameTime gameTime)
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.Update(gameTime);
}
private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
{
return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
private readonly bool _constructed;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
_constructed = true;
}
public override void Update(GameTime gameTime)
{
if (!_constructed)
return;
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.Update(gameTime);
}
private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
{
return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
}
}
}
|
Handle ObjectDisposedException just in case we do end up trying to read properties of a closed message | using System;
using System.ServiceModel.Channels;
namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
internal static class WcfExtensions
{
public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
{
if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
{
return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
}
return null;
}
public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
{
if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
{
return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
}
return null;
}
}
}
| using System;
using System.ServiceModel.Channels;
namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
internal static class WcfExtensions
{
public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
{
try
{
if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
{
return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
}
} catch ( ObjectDisposedException )
{
// WCF message is already disposed, just avoid it
}
return null;
}
public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
{
try
{
if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
{
return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
}
} catch ( ObjectDisposedException )
{
// WCF message is already disposed, just avoid it
}
return null;
}
}
}
|
Test console Run method updated | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;
namespace Arf.Console
{
class Program
{
public static bool IsProcessing;
public static void Main(string[] args)
{
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Please write image Url or local path");
while (true)
{
if (IsProcessing) continue;
System.Console.ResetColor();
var imgPath = System.Console.ReadLine();
Run(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGray;
System.Console.WriteLine("It takes a few time.Please wait!");
System.Console.ResetColor();
}
}
public static async void Run(string imgPath)
{
IsProcessing = true;
var isUpload = imgPath != null && !imgPath.StartsWith("http");
var service = new VisionService();
var analysisResult = isUpload
? await service.UploadAndDescripteImage(imgPath)
: await service.DescripteUrl(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGreen;
System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => s = "#" + s)));
System.Console.ResetColor();
IsProcessing = false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;
namespace Arf.Console
{
class Program
{
public static bool IsProcessing;
public static void Main(string[] args)
{
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Please write image Url or local path");
while (true)
{
if (IsProcessing) continue;
System.Console.ResetColor();
var imgPath = System.Console.ReadLine();
Run(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGray;
System.Console.WriteLine("It takes a few time.Please wait!");
System.Console.ResetColor();
}
}
public static async void Run(string imgPath)
{
IsProcessing = true;
var isUpload = imgPath != null && !imgPath.StartsWith("http");
var service = new VisionService();
var analysisResult = isUpload
? await service.UploadAndDescripteImage(imgPath)
: await service.DescripteUrl(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGreen;
System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => $"#{s}")));
System.Console.ResetColor();
IsProcessing = false;
}
}
}
|
Remove RandomTrace stuff from Main | using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
| using static System.Console;
using CIV.Ccs;
using CIV.Hml;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
var prova = HmlFacade.ParseAll(hmlText);
WriteLine(prova.Check(processes["Prison"]));
}
}
}
|
Fix typo in example comment. | To: @Model.To
From: example@website.com
Reply-To: another@website.com
Subject: @Model.Subject
@* NOTE: There MUST be a blank like after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message
Thanks! | To: @Model.To
From: example@website.com
Reply-To: another@website.com
Subject: @Model.Subject
@* NOTE: There MUST be a blank line after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message
Thanks! |
Refactor puzzle 10 to not use LINQ | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
Answer = Enumerable.Range(2, max - 2)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = 0;
for (int n = 2; n < max - 2; n++)
{
if (Maths.IsPrime(n))
{
sum += n;
}
}
Answer = sum;
return 0;
}
}
}
|
Fix some arrivals showing negative ETA minutes. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Common.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return String.Empty;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Common.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return String.Empty;
}
}
}
|
Revert "Try fix for tracking metrics with square brackets in name" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;
namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
public abstract class Metric : ICanReportToGoogleAnalytics
{
public abstract string Name { get; }
protected string TrackableName
{
get
{
return this.Name.Replace('[', '~').Replace(']', '~');
}
}
public virtual ParameterTextValue HitType
{
get
{
return HitTypeValue.Event;
}
}
public virtual IEnumerable<Parameter> Parameters
{
get
{
return new Parameter[] {
Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.TrackableName))
};
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;
namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
public abstract class Metric : ICanReportToGoogleAnalytics
{
public abstract string Name { get; }
public virtual ParameterTextValue HitType
{
get
{
return HitTypeValue.Event;
}
}
public virtual IEnumerable<Parameter> Parameters
{
get
{
return new Parameter[] {
Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.Name))
};
}
}
}
}
|
Add option to set app name | using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SilentHunter.FileFormats.Dat.Controllers;
using SilentHunter.FileFormats.DependencyInjection;
namespace SilentHunter.Controllers.Compiler.DependencyInjection
{
public static class ControllerConfigurerExtensions
{
public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths)
{
AddCSharpCompiler(controllerConfigurer);
return controllerConfigurer.FromAssembly(s =>
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
string applicationName = entryAssembly?.GetName().Name ?? "SilentHunter.Controllers";
var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), applicationName, controllerPath)
{
AssemblyName = assemblyName,
IgnorePaths = ignorePaths,
DependencySearchPaths = dependencySearchPaths
};
return new ControllerAssembly(assemblyCompiler.Compile());
});
}
private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer)
{
IServiceCollection services = controllerConfigurer.ServiceCollection;
#if NETFRAMEWORK
services.TryAddTransient<ICSharpCompiler, CSharpCompiler>();
#else
services.TryAddTransient<ICSharpCompiler, RoslynCompiler>();
#endif
}
}
} | using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SilentHunter.FileFormats.Dat.Controllers;
using SilentHunter.FileFormats.DependencyInjection;
namespace SilentHunter.Controllers.Compiler.DependencyInjection
{
public static class ControllerConfigurerExtensions
{
public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, string applicationName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths)
{
AddCSharpCompiler(controllerConfigurer);
return controllerConfigurer.FromAssembly(s =>
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
string appName = applicationName ?? entryAssembly?.GetName().Name ?? "SilentHunter.Controllers";
var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), appName, controllerPath)
{
AssemblyName = assemblyName,
IgnorePaths = ignorePaths,
DependencySearchPaths = dependencySearchPaths
};
return new ControllerAssembly(assemblyCompiler.Compile());
});
}
private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer)
{
IServiceCollection services = controllerConfigurer.ServiceCollection;
#if NETFRAMEWORK
services.TryAddTransient<ICSharpCompiler, CSharpCompiler>();
#else
services.TryAddTransient<ICSharpCompiler, RoslynCompiler>();
#endif
}
}
} |
Add Read and Write methods | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSX
{
public static Process FindPSX()
{
Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
return psx;
}
public static IntPtr OpenPSX(Process psx)
{
int PID = psx.Id;
IntPtr psxHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);
}
public static void ClosePSX(IntPtr processHandle)
{
int result = Memory.CloseHandle(processHandle);
if (result == 0)
{
Console.WriteLine("ERROR: Could not close psx handle");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSX
{
public static Process PSXProcess;
public static IntPtr PSXHandle;
public static bool FindPSX()
{
PSXProcess = Process.GetProcessesByName("psxfin").FirstOrDefault();
return (PSXProcess != null);
}
public static bool OpenPSX()
{
int PID = PSXProcess.Id;
PSXHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);
return (PSXHandle != null);
}
public static void ClosePSX(IntPtr processHandle)
{
int result = Memory.CloseHandle(processHandle);
if (result == 0)
{
Console.WriteLine("ERROR: Could not close psx handle");
}
}
public static string Read(IntPtr address, ref byte[] buffer)
{
int bytesRead = 0;
int absoluteAddress = Memory.PSXGameOffset + (int)address;
//IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress);
Memory.ReadProcessMemory((int)PSXHandle, absoluteAddress, buffer, buffer.Length, ref bytesRead);
return "Address " + address.ToString("x2") + " contains " + Memory.FormatToHexString(buffer);
}
public static string Write(IntPtr address, byte[] data)
{
int bytesWritten;
int absoluteAddress = Memory.PSXGameOffset + (int)address;
IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress);
Memory.WriteProcessMemory(PSXHandle, absoluteAddressPtr, data, (uint)data.Length, out bytesWritten);
return "Address " + address.ToString("x2") + " is now " + Memory.FormatToHexString(data);
}
}
}
|
Fix Size test using explicit conversions for assertions | using Xunit;
namespace VulkanCore.Tests
{
public class SizeTest
{
[Fact]
public void ImplicitConversions()
{
const int intVal = 1;
const long longVal = 2;
Size intSize = intVal;
Size longSize = longVal;
Assert.Equal(intVal, intSize);
Assert.Equal(longVal, longSize);
}
}
}
| using Xunit;
namespace VulkanCore.Tests
{
public class SizeTest
{
[Fact]
public void ImplicitConversions()
{
const int intVal = 1;
const long longVal = 2;
Size intSize = intVal;
Size longSize = longVal;
Assert.Equal(intVal, (int)intSize);
Assert.Equal(longVal, (long)longSize);
}
}
}
|
Add static factory method for neuron | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArtificialNeuralNetwork
{
[Serializable]
public class Neuron : INeuron
{
private readonly ISoma _soma;
private readonly IAxon _axon;
public Neuron(ISoma soma, IAxon axon)
{
_soma = soma;
_axon = axon;
}
public virtual double CalculateActivationFunction()
{
return 0.0;
}
public void Process()
{
_axon.ProcessSignal(_soma.CalculateSummation());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArtificialNeuralNetwork
{
[Serializable]
public class Neuron : INeuron
{
private readonly ISoma _soma;
private readonly IAxon _axon;
private Neuron(ISoma soma, IAxon axon)
{
_soma = soma;
_axon = axon;
}
public static INeuron Create(ISoma soma, IAxon axon)
{
return new Neuron(soma, axon);
}
public void Process()
{
_axon.ProcessSignal(_soma.CalculateSummation());
}
}
}
|
Add message types for nitro boosting and channel following | namespace Discore
{
public enum DiscordMessageType
{
Default = 0,
RecipientAdd = 1,
RecipientRemove = 2,
Call = 3,
ChannelNameChange = 4,
ChannelIconChange = 5,
ChannelPinnedMessage = 6,
GuildMemberJoin = 7
}
}
| namespace Discore
{
public enum DiscordMessageType
{
Default = 0,
RecipientAdd = 1,
RecipientRemove = 2,
Call = 3,
ChannelNameChange = 4,
ChannelIconChange = 5,
ChannelPinnedMessage = 6,
GuildMemberJoin = 7,
UserPremiumGuildSubscription = 8,
UserPremiumGuildSubscriptionTier1 = 9,
UserPremiumGuildSubscriptionTier2 = 10,
UserPremiumGuildSubscriptionTier3 = 11,
ChannelFollowAdd = 12
}
}
|
Rename function name in test fixture | using NUnit.Framework;
using Rivet.Operations;
namespace Rivet.Test.Operations
{
[TestFixture]
public sealed class NewUserDefinedFunctionTestFixture
{
const string SchemaName = "schemaName";
const string FunctionName = "functionName";
const string Definition = "as definition";
[SetUp]
public void SetUp()
{
}
[Test]
public void ShouldSetPropertiesForNewStoredProcedure()
{
var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
Assert.AreEqual(SchemaName, op.SchemaName);
Assert.AreEqual(FunctionName, op.Name);
Assert.AreEqual(Definition, op.Definition);
}
[Test]
public void ShouldWriteQueryForNewStoredProcedure()
{
var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
const string expectedQuery = "create function [schemaName].[functionName] as definition";
Assert.AreEqual(expectedQuery, op.ToQuery());
}
}
} | using NUnit.Framework;
using Rivet.Operations;
namespace Rivet.Test.Operations
{
[TestFixture]
public sealed class NewUserDefinedFunctionTestFixture
{
const string SchemaName = "schemaName";
const string FunctionName = "functionName";
const string Definition = "as definition";
[SetUp]
public void SetUp()
{
}
[Test]
public void ShouldSetPropertiesForNewUserDefinedFunction()
{
var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
Assert.AreEqual(SchemaName, op.SchemaName);
Assert.AreEqual(FunctionName, op.Name);
Assert.AreEqual(Definition, op.Definition);
}
[Test]
public void ShouldWriteQueryForNewUserDefinedFunction()
{
var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
const string expectedQuery = "create function [schemaName].[functionName] as definition";
Assert.AreEqual(expectedQuery, op.ToQuery());
}
}
} |
Update server to send proper response | using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;
namespace HelloServer
{
class HelloServerImpl : HelloService.HelloServiceBase
{
public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
{
return Task.FromResult(new HelloResp { Result = "Hey " + request.Name });
}
public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context)
{
if (request.Name.Length >= 10) {
const string msg = "Length of `Name` cannot be more than 10 characters";
throw new RpcException(new Status(StatusCode.InvalidArgument, msg));
}
return Task.FromResult(new HelloResp { Result = "Hey " + request.Name });
}
}
class Program
{
const int Port = 50051;
public static void Main(string[] args)
{
Server server = new Server
{
Services = { HelloService.BindService(new HelloServerImpl()) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("Hello server listening on port " + Port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
| using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;
namespace HelloServer
{
class HelloServerImpl : HelloService.HelloServiceBase
{
public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
{
return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"});
}
public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context)
{
if (request.Name.Length >= 10) {
const string msg = "Length of `Name` cannot be more than 10 characters";
throw new RpcException(new Status(StatusCode.InvalidArgument, msg));
}
return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"});
}
}
class Program
{
const int Port = 50051;
public static void Main(string[] args)
{
Server server = new Server
{
Services = { HelloService.BindService(new HelloServerImpl()) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("Hello server listening on port " + Port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
|
Add basic fields in Charge's PMD 3DS field | namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
}
}
| namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
[JsonProperty("succeeded")]
public bool Succeeded { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
}
}
|
Add a method to get settings from a url. | using System.Text;
using AzureStorage.Blob;
using Common;
namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public static class GeneralSettingsReader
{
public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName)
{
var settingsStorage = new AzureBlobStorage(connectionString);
var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes();
var str = Encoding.UTF8.GetString(settingsData);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
}
}
}
| using System.Net.Http;
using System.Text;
using AzureStorage.Blob;
using Common;
using Newtonsoft.Json;
namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public static class GeneralSettingsReader
{
public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName)
{
var settingsStorage = new AzureBlobStorage(connectionString);
var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes();
var str = Encoding.UTF8.GetString(settingsData);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
}
public static T ReadGeneralSettingsFromUrl<T>(string settingsUrl)
{
var httpClient = new HttpClient();
var settingsString = httpClient.GetStringAsync(settingsUrl).Result;
var serviceBusSettings = JsonConvert.DeserializeObject<T>(settingsString);
return serviceBusSettings;
}
}
}
|
Add test covering horrible fail scenario | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Visual.Platform
{
[Ignore("This test does not cover correct GL context acquire/release when run headless.")]
public class TestSceneExecutionModes : FrameworkTestScene
{
private Bindable<ExecutionMode> executionMode;
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager configManager)
{
executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
}
[Test]
public void ToggleModeSmokeTest()
{
AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
? ExecutionMode.SingleThread
: ExecutionMode.MultiThreaded, 2);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Visual.Platform
{
[Ignore("This test does not cover correct GL context acquire/release when run headless.")]
public class TestSceneExecutionModes : FrameworkTestScene
{
private Bindable<ExecutionMode> executionMode;
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager configManager)
{
executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
}
[Test]
public void ToggleModeSmokeTest()
{
AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
? ExecutionMode.SingleThread
: ExecutionMode.MultiThreaded, 2);
}
[Test]
public void TestRapidSwitching()
{
ScheduledDelegate switchStep = null;
int switchCount = 0;
AddStep("install quick switch step", () =>
{
switchStep = Scheduler.AddDelayed(() =>
{
executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded;
switchCount++;
}, 0, true);
});
AddUntilStep("switch count sufficiently high", () => switchCount > 1000);
AddStep("remove", () => switchStep.Cancel());
}
}
}
|
Fix spinenr tick samples not positioned at centre | // 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.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
public override bool DisplayResult => false;
protected DrawableSpinner DrawableSpinner => (DrawableSpinner)ParentHitObject;
public DrawableSpinnerTick()
: base(null)
{
}
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
}
protected override double MaximumJudgementOffset => DrawableSpinner.HitObject.Duration;
/// <summary>
/// Apply a judgement result.
/// </summary>
/// <param name="hit">Whether this tick was reached.</param>
internal void TriggerResult(bool hit) => ApplyResult(r => r.Type = hit ? r.Judgement.MaxResult : r.Judgement.MinResult);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
public override bool DisplayResult => false;
protected DrawableSpinner DrawableSpinner => (DrawableSpinner)ParentHitObject;
public DrawableSpinnerTick()
: this(null)
{
}
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override double MaximumJudgementOffset => DrawableSpinner.HitObject.Duration;
/// <summary>
/// Apply a judgement result.
/// </summary>
/// <param name="hit">Whether this tick was reached.</param>
internal void TriggerResult(bool hit) => ApplyResult(r => r.Type = hit ? r.Judgement.MaxResult : r.Judgement.MinResult);
}
}
|
Fix compile error in .NET Core 3.1 version of ASP.NET Core Web App blueprint | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace BlueprintBaseName._1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BlueprintBaseName._1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
|
Define a state that is modified by the actions | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace NBi.GenbiL
{
class GenerationState
{
public DataTable TestCases { get; set; }
public IEnumerable<string> Variables { get; set; }
public string Template { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using NBi.Service;
namespace NBi.GenbiL
{
public class GenerationState
{
public TestCasesManager TestCases { get; private set; }
public TemplateManager Template { get; private set; }
public SettingsManager Settings { get; private set; }
public TestListManager List { get; private set; }
public TestSuiteManager Suite { get; private set; }
public GenerationState()
{
TestCases = new TestCasesManager();
Template = new TemplateManager();
Settings = new SettingsManager();
List = new TestListManager();
Suite = new TestSuiteManager();
}
}
}
|
Fix potentially null reference if drawable was not assigned a `LoadThread` yet | // 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.Linq;
using osu.Framework.Development;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Lists;
namespace osu.Framework.Logging
{
internal static class LoadingComponentsLogger
{
private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>();
public static void Add(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Add(component);
}
public static void Remove(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Remove(component);
}
public static void LogAndFlush()
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
{
Logger.Log($"⏳ Currently loading components ({loading_components.Count()})");
foreach (var c in loading_components)
Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}");
loading_components.Clear();
Logger.Log("🧵 Task schedulers");
Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString());
Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString());
}
}
}
}
| // 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.Linq;
using osu.Framework.Development;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Lists;
namespace osu.Framework.Logging
{
internal static class LoadingComponentsLogger
{
private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>();
public static void Add(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Add(component);
}
public static void Remove(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Remove(component);
}
public static void LogAndFlush()
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
{
Logger.Log($"⏳ Currently loading components ({loading_components.Count()})");
foreach (var c in loading_components)
{
Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread?.Name ?? "none"}");
}
loading_components.Clear();
Logger.Log("🧵 Task schedulers");
Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString());
Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString());
}
}
}
}
|
Fix incorrect ruleset being sent to API | // 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;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (IsCurrentScreen)
Exit();
return true;
}
}
}
| // 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;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
RulesetID = Ruleset.Value.ID ?? 0
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (IsCurrentScreen)
Exit();
return true;
}
}
}
|
Revert "Cleaned up 0x60 0x21 warp packet model" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Payload sent when a client is begining a warp to a new area.
/// Contains client ID information and information about the warp itself.
/// </summary>
[WireDataContract]
[SubCommand60(SubCommand60OperationCode.GameStartWarpToArea)]
public sealed class Sub60StartNewWarpCommand : BaseSubCommand60, IMessageContextIdentifiable
{
//TODO: Is this client id?
[WireMember(1)]
public byte Identifier { get; }
[WireMember(2)]
public byte Unused1 { get; }
/// <summary>
/// The zone ID that the user is teleporting to.
/// </summary>
[WireMember(3)]
public short ZoneId { get; }
//Unused2 was padding, not sent in the payload.
public Sub60StartNewWarpCommand()
{
//Calc static 32bit size
CommandSize = 8 / 4;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Payload sent when a client is begining a warp to a new area.
/// Contains client ID information and information about the warp itself.
/// </summary>
[WireDataContract]
[SubCommand60(SubCommand60OperationCode.GameStartWarpToArea)]
public sealed class Sub60StartNewWarpCommand : BaseSubCommand60, IMessageContextIdentifiable
{
//TODO: Is this client id?
[WireMember(1)]
public byte Identifier { get; }
[WireMember(2)]
public byte Unused1 { get; }
/// <summary>
/// The zone ID that the user is teleporting to.
/// </summary>
[WireMember(3)]
public short ZoneId { get; }
//TODO: What is this?
[WireMember(4)]
public short Unused2 { get; }
public Sub60StartNewWarpCommand()
{
//Calc static 32bit size
CommandSize = 8 / 4;
}
}
}
|
Make sure that beginInvoke target exists | using System;
using System.Windows.Forms;
using osu_StreamCompanion.Code.Core;
using osu_StreamCompanion.Code.Helpers;
namespace osu_StreamCompanion.Code.Modules.ModParser
{
public partial class ModParserSettings : UserControl
{
private Settings _settings;
private bool init = true;
public ModParserSettings(Settings settings)
{
_settings = settings;
_settings.SettingUpdated+= SettingUpdated;
this.Enabled = _settings.Get("EnableMemoryScanner", true);
InitializeComponent();
textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None");
radioButton_longMods.Checked = _settings.Get("UseLongMods", false);
radioButton_shortMods.Checked = !radioButton_longMods.Checked;
init = false;
}
private void SettingUpdated(object sender, SettingUpdated settingUpdated)
{
this.BeginInvoke((MethodInvoker) (() =>
{
if (settingUpdated.Name == "EnableMemoryScanner")
this.Enabled = _settings.Get("EnableMemoryScanner", true);
}));
}
private void textBox_Mods_TextChanged(object sender, EventArgs e)
{
if (init) return;
_settings.Add("NoModsDisplayText", textBox_Mods.Text);
}
private void radioButton_longMods_CheckedChanged(object sender, EventArgs e)
{
if (init) return;
if (((RadioButton)sender).Checked)
{
_settings.Add("UseLongMods", radioButton_longMods.Checked);
}
}
}
}
| using System;
using System.Windows.Forms;
using osu_StreamCompanion.Code.Core;
using osu_StreamCompanion.Code.Helpers;
namespace osu_StreamCompanion.Code.Modules.ModParser
{
public partial class ModParserSettings : UserControl
{
private Settings _settings;
private bool init = true;
public ModParserSettings(Settings settings)
{
_settings = settings;
_settings.SettingUpdated += SettingUpdated;
this.Enabled = _settings.Get("EnableMemoryScanner", true);
InitializeComponent();
textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None");
radioButton_longMods.Checked = _settings.Get("UseLongMods", false);
radioButton_shortMods.Checked = !radioButton_longMods.Checked;
init = false;
}
private void SettingUpdated(object sender, SettingUpdated settingUpdated)
{
if (this.IsHandleCreated)
this.BeginInvoke((MethodInvoker)(() =>
{
if (settingUpdated.Name == "EnableMemoryScanner")
this.Enabled = _settings.Get("EnableMemoryScanner", true);
}));
}
private void textBox_Mods_TextChanged(object sender, EventArgs e)
{
if (init) return;
_settings.Add("NoModsDisplayText", textBox_Mods.Text);
}
private void radioButton_longMods_CheckedChanged(object sender, EventArgs e)
{
if (init) return;
if (((RadioButton)sender).Checked)
{
_settings.Add("UseLongMods", radioButton_longMods.Checked);
}
}
}
}
|
Use API to override the location of the dictionary file in the dictionary cache from our Web applicatoin | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Anagrams.Models;
namespace Anagrams
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DictionaryCache.Reader = new DictionaryReader();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Anagrams.Models;
namespace Anagrams
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DictionaryCache.Reader = new DictionaryReader();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
DictionaryCache.SetPath(HttpContext.Current.Server.MapPath(@"Content/wordlist.txt"));
}
}
} |
Fix async deadlock on Mono | using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mond.Libraries.Async
{
internal class Scheduler : TaskScheduler
{
private List<Task> _tasks;
public Scheduler()
{
_tasks = new List<Task>();
}
public void Run()
{
int count;
lock (_tasks)
{
count = _tasks.Count;
}
if (count == 0)
return;
while (--count >= 0)
{
Task task;
lock (_tasks)
{
if (_tasks.Count == 0)
return;
task = _tasks[0];
_tasks.RemoveAt(0);
}
if (!TryExecuteTask(task))
_tasks.Add(task);
}
}
protected override IEnumerable<Task> GetScheduledTasks()
{
lock (_tasks)
{
return _tasks.ToArray();
}
}
protected override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.Add(task);
}
}
protected override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mond.Libraries.Async
{
internal class Scheduler : TaskScheduler
{
private List<Task> _tasks;
public Scheduler()
{
_tasks = new List<Task>();
}
public void Run()
{
int count;
lock (_tasks)
{
count = _tasks.Count;
}
if (count == 0)
return;
while (--count >= 0)
{
Task task;
lock (_tasks)
{
if (_tasks.Count == 0)
return;
task = _tasks[0];
_tasks.RemoveAt(0);
}
if (TryExecuteTask(task))
continue;
lock (_tasks)
{
_tasks.Add(task);
}
}
}
protected override IEnumerable<Task> GetScheduledTasks()
{
lock (_tasks)
{
return _tasks.ToArray();
}
}
protected override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.Add(task);
}
}
protected override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued)
{
if (TryDequeue(task))
return TryExecuteTask(task);
return false;
}
return TryExecuteTask(task);
}
}
}
|
Set neutral language to English | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FreenetTray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreenetTray")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("220ea49e-e109-4bb4-86c6-ef477f1584e7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FreenetTray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreenetTray")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("220ea49e-e109-4bb4-86c6-ef477f1584e7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
|
Add function to get start of season | using RimWorld;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MTW_AncestorSpirits
{
public static class AncestorUtils
{
public static int DaysToTicks(float days)
{
return Mathf.RoundToInt(days * GenDate.TicksPerDay);
}
public static int HoursToTicks(float hours)
{
return Mathf.RoundToInt(hours * GenDate.TicksPerHour);
}
}
}
| using Verse;
using RimWorld;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MTW_AncestorSpirits
{
public static class AncestorUtils
{
public static int DaysToTicks(float days)
{
return Mathf.RoundToInt(days * GenDate.TicksPerDay);
}
public static int HoursToTicks(float hours)
{
return Mathf.RoundToInt(hours * GenDate.TicksPerHour);
}
public static long EstStartOfSeasonAt(long ticks)
{
var currentDayTicks = (int)(GenDate.CurrentDayPercent * GenDate.TicksPerDay);
var dayOfSeason = GenDate.DayOfSeasonZeroBasedAt(ticks);
var currentSeasonDayTicks = DaysToTicks(dayOfSeason);
return ticks - currentDayTicks - currentSeasonDayTicks;
}
}
}
|
Fix TryReadProblemJson: ensure problem json could be read and an object was created | namespace Hypermedia.Client.Reader.ProblemJson
{
using System;
using System.Net.Http;
using global::Hypermedia.Client.Exceptions;
using global::Hypermedia.Client.Resolver;
using Newtonsoft.Json;
public static class ProblemJsonReader
{
public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription)
{
problemDescription = null;
if (result.Content == null)
{
return false;
}
try
{
var content = result.Content.ReadAsStringAsync().Result;
problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer
}
catch (Exception)
{
return false;
}
return true;
}
}
}
| namespace Hypermedia.Client.Reader.ProblemJson
{
using System;
using System.Net.Http;
using global::Hypermedia.Client.Exceptions;
using global::Hypermedia.Client.Resolver;
using Newtonsoft.Json;
public static class ProblemJsonReader
{
public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription)
{
problemDescription = null;
if (result.Content == null)
{
return false;
}
try
{
var content = result.Content.ReadAsStringAsync().Result;
problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer
}
catch (Exception)
{
return false;
}
return problemDescription != null;
}
}
}
|
Add error message on exception | //
// Program.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using Xwt;
using Deblocus.Views;
namespace Deblocus
{
public static class Program
{
[STAThread]
public static void Main()
{
Application.Initialize(ToolkitType.Gtk);
var mainWindow = new MainWindow();
mainWindow.Show();
Application.Run();
mainWindow.Dispose();
Application.Dispose();
}
}
}
| //
// Program.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using Xwt;
using Deblocus.Views;
namespace Deblocus
{
public static class Program
{
[STAThread]
public static void Main()
{
Application.Initialize(ToolkitType.Gtk);
Application.UnhandledException += ApplicationException;
var mainWindow = new MainWindow();
mainWindow.Show();
Application.Run();
mainWindow.Dispose();
Application.Dispose();
}
private static void ApplicationException (object sender, ExceptionEventArgs e)
{
MessageDialog.ShowError("Unknown error. Please contact with the developer.\n" +
e.ErrorException);
}
}
}
|
Increase client version to 1.4.2.3 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2.2")]
[assembly: AssemblyFileVersion("1.4.2.2")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2.3")]
[assembly: AssemblyFileVersion("1.4.2.3")]
|
Change log lvl for history engine disable logging | using System.Diagnostics;
using Sitecore.Configuration;
using Sitecore.DataBlaster.Load.Sql;
namespace Sitecore.DataBlaster.Load.Processors
{
public class SyncHistoryTable : ISyncInTransaction
{
public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext)
{
if (!loadContext.UpdateHistory.GetValueOrDefault()) return;
if (loadContext.ItemChanges.Count == 0) return;
// In Sitecore 9, history engine is disabled by default
if (!HistoryEngineEnabled(loadContext))
{
loadContext.Log.Warn($"Skipped updating history because history engine is not enabled");
return;
}
var stopwatch = Stopwatch.StartNew();
var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql");
sqlContext.ExecuteSql(sql,
commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name));
loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s");
}
private bool HistoryEngineEnabled(BulkLoadContext context)
{
var db = Factory.GetDatabase(context.Database, true);
return db.Engines.HistoryEngine.Storage != null;
}
}
} | using System.Diagnostics;
using Sitecore.Configuration;
using Sitecore.DataBlaster.Load.Sql;
namespace Sitecore.DataBlaster.Load.Processors
{
public class SyncHistoryTable : ISyncInTransaction
{
public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext)
{
if (!loadContext.UpdateHistory.GetValueOrDefault()) return;
if (loadContext.ItemChanges.Count == 0) return;
// In Sitecore 9, history engine is disabled by default
if (!HistoryEngineEnabled(loadContext))
{
loadContext.Log.Info($"Skipped updating history because history engine is not enabled.");
return;
}
var stopwatch = Stopwatch.StartNew();
var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql");
sqlContext.ExecuteSql(sql,
commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name));
loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s");
}
private bool HistoryEngineEnabled(BulkLoadContext context)
{
var db = Factory.GetDatabase(context.Database, true);
return db.Engines.HistoryEngine.Storage != null;
}
}
} |
Change default background color to be more grey | using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace GUI.Utils
{
internal static class Settings
{
public static List<string> GameSearchPaths { get; } = new List<string>();
public static Color BackgroundColor { get; set; } = Color.Black;
public static void Load()
{
// TODO: Be dumb about it for now.
if (!File.Exists("gamepaths.txt"))
{
return;
}
GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt"));
}
public static void Save()
{
File.WriteAllLines("gamepaths.txt", GameSearchPaths);
}
}
}
| using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace GUI.Utils
{
internal static class Settings
{
public static List<string> GameSearchPaths { get; } = new List<string>();
public static Color BackgroundColor { get; set; }
public static void Load()
{
BackgroundColor = Color.FromArgb(60, 60, 60);
// TODO: Be dumb about it for now.
if (!File.Exists("gamepaths.txt"))
{
return;
}
GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt"));
}
public static void Save()
{
File.WriteAllLines("gamepaths.txt", GameSearchPaths);
}
}
}
|
Rollback functionality and hash computing | using System.Collections.Generic;
using System;
namespace MicroORM.Entity
{
internal sealed class EntityInfo
{
internal EntityInfo()
{
this.EntityState = EntityState.None;
this.EntityHashSet = new Dictionary<string, string>();
this.LastCallTime = DateTime.Now;
}
internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } }
internal EntityState EntityState { get; set; }
internal Dictionary<string, string> EntityHashSet { get; set; }
internal DateTime LastCallTime { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using MicroORM.Materialization;
using MicroORM.Reflection;
using MicroORM.Mapping;
namespace MicroORM.Entity
{
internal sealed class EntityInfo
{
internal EntityInfo()
{
this.EntityState = EntityState.None;
this.ValueSnapshot = new Dictionary<string, int>();
this.ChangesSnapshot = new Dictionary<string, int>();
this.LastCallTime = DateTime.Now;
}
internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } }
internal EntityState EntityState { get; set; }
internal Dictionary<string, int> ValueSnapshot { get; set; }
internal Dictionary<string, int> ChangesSnapshot { get; set; }
internal DateTime LastCallTime { get; set; }
internal void ClearChanges()
{
this.ChangesSnapshot.Clear();
}
internal void MergeChanges()
{
foreach (var change in this.ChangesSnapshot)
{
this.ValueSnapshot[change.Key] = change.Value;
}
ClearChanges();
}
internal void ComputeSnapshot<TEntity>(TEntity entity)
{
this.ValueSnapshot = EntityHashSetManager.ComputeEntityHashSet(entity);
}
internal KeyValuePair<string, object>[] ComputeUpdateValues<TEntity>(TEntity entity)
{
Dictionary<string, int> entityHashSet = EntityHashSetManager.ComputeEntityHashSet(entity);
KeyValuePair<string, object>[] entityValues = RemoveUnusedPropertyValues<TEntity>(entity);
Dictionary<string, object> valuesToUpdate = new Dictionary<string, object>();
foreach (var kvp in entityHashSet)
{
var oldHash = this.ValueSnapshot[kvp.Key];
if (oldHash.Equals(kvp.Value) == false)
{
valuesToUpdate.Add(kvp.Key, entityValues.FirstOrDefault(kvp1 => kvp1.Key == kvp.Key).Value);
this.ChangesSnapshot.Add(kvp.Key, kvp.Value);
}
}
return valuesToUpdate.ToArray();
}
private KeyValuePair<string, object>[] RemoveUnusedPropertyValues<TEntity>(TEntity entity)
{
KeyValuePair<string, object>[] entityValues = ParameterTypeDescriptor.ToKeyValuePairs(new object[] { entity });
TableInfo tableInfo = TableInfo<TEntity>.GetTableInfo;
return entityValues.Where(kvp => tableInfo.DbTable.DbColumns.Any(column => column.Name == kvp.Key)).ToArray();
}
}
}
|
Format for output window message changed | using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Sawczyn.EFDesigner.EFModel
{
internal static class Messages
{
private static readonly string MessagePaneTitle = "Entity Framework Designer";
private static IVsOutputWindow _outputWindow;
private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow);
private static IVsOutputWindowPane _outputWindowPane;
private static IVsOutputWindowPane OutputWindowPane
{
get
{
if (_outputWindowPane == null)
{
Guid paneGuid = new Guid(Constants.EFDesignerOutputPane);
OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane);
if (_outputWindowPane == null)
{
OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1);
OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane);
}
}
return _outputWindowPane;
}
}
public static void AddError(string message)
{
OutputWindowPane?.OutputString($"Error: {message}");
OutputWindowPane?.Activate();
}
public static void AddWarning(string message)
{
OutputWindowPane?.OutputString($"Warning: {message}");
OutputWindowPane?.Activate();
}
public static void AddMessage(string message)
{
OutputWindowPane?.OutputString(message);
OutputWindowPane?.Activate();
}
}
}
| using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Sawczyn.EFDesigner.EFModel
{
internal static class Messages
{
private static readonly string MessagePaneTitle = "Entity Framework Designer";
private static IVsOutputWindow _outputWindow;
private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow);
private static IVsOutputWindowPane _outputWindowPane;
private static IVsOutputWindowPane OutputWindowPane
{
get
{
if (_outputWindowPane == null)
{
Guid paneGuid = new Guid(Constants.EFDesignerOutputPane);
OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane);
if (_outputWindowPane == null)
{
OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1);
OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane);
}
}
return _outputWindowPane;
}
}
public static void AddError(string message)
{
AddMessage(message, "Error");
}
public static void AddWarning(string message)
{
AddMessage(message, "Warning");
}
public static void AddMessage(string message, string prefix = null)
{
OutputWindowPane?.OutputString($"{(string.IsNullOrWhiteSpace(prefix) ? "" : prefix + ": ")}{message}{(message.EndsWith("\n") ? "" : "\n")}");
OutputWindowPane?.Activate();
}
}
}
|
Allow custom date format when displaying published state | using System;
using System.Web;
using System.Web.Mvc;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.Descriptors;
using Orchard.Localization;
using Orchard.Mvc.Html;
namespace Orchard.Core.Common {
public class Shapes : IShapeTableProvider {
public Shapes() {
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Body_Editor")
.OnDisplaying(displaying => {
string flavor = displaying.Shape.EditorFlavor;
displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor);
});
}
[Shape]
public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc) {
if (!publisheddateTimeUtc.HasValue) {
return T("Draft");
}
return Display.DateTime(DateTimeUtc: createdDateTimeUtc);
}
[Shape]
public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) {
if (dateTimeUtc == null)
return T("as a Draft");
return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc);
}
}
}
| using System;
using System.Web;
using System.Web.Mvc;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.Descriptors;
using Orchard.Localization;
using Orchard.Mvc.Html;
namespace Orchard.Core.Common {
public class Shapes : IShapeTableProvider {
public Shapes() {
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Body_Editor")
.OnDisplaying(displaying => {
string flavor = displaying.Shape.EditorFlavor;
displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor);
});
}
[Shape]
public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc, LocalizedString customDateFormat) {
if (!publisheddateTimeUtc.HasValue) {
return T("Draft");
}
return Display.DateTime(DateTimeUtc: createdDateTimeUtc, CustomFormat: customDateFormat);
}
[Shape]
public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) {
if (dateTimeUtc == null)
return T("as a Draft");
return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc);
}
}
}
|
Add ability to save commands mapping | using Arduino;
using ArduinoWindowsRemoteControl.Repositories;
using Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArduinoWindowsRemoteControl.Services
{
/// <summary>
/// Service that returns parsers for different remote input devices
/// </summary>
public class RemoteCommandParserService
{
#region Private Fields
private DictionaryRepository _dictionaryRepository;
#endregion
#region Constructor
public RemoteCommandParserService()
{
_dictionaryRepository = new DictionaryRepository();
}
#endregion
#region Public Methods
public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename)
{
var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename);
return new ArduinoRemoteCommandParser(dictionary);
}
public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename)
{
}
#endregion
}
}
| using Arduino;
using ArduinoWindowsRemoteControl.Repositories;
using Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArduinoWindowsRemoteControl.Services
{
/// <summary>
/// Service that returns parsers for different remote input devices
/// </summary>
public class RemoteCommandParserService
{
#region Private Fields
private DictionaryRepository _dictionaryRepository;
#endregion
#region Constructor
public RemoteCommandParserService()
{
_dictionaryRepository = new DictionaryRepository();
}
#endregion
#region Public Methods
public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename)
{
var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename);
return new ArduinoRemoteCommandParser(dictionary);
}
public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename)
{
_dictionaryRepository.Save(commandParser.CommandsMapping, filename);
}
#endregion
}
}
|
Remove slider tail circle judgement requirements | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// Note that this should not be used for timing correctness.
/// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information.
/// </summary>
public class SliderTailCircle : SliderCircle
{
private readonly IBindable<int> pathVersion = new Bindable<int>();
public SliderTailCircle(Slider slider)
{
pathVersion.BindTo(slider.Path.Version);
pathVersion.BindValueChanged(_ => Position = slider.EndPosition);
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderRepeat.SliderRepeatJudgement();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// Note that this should not be used for timing correctness.
/// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information.
/// </summary>
public class SliderTailCircle : SliderCircle
{
private readonly IBindable<int> pathVersion = new Bindable<int>();
public SliderTailCircle(Slider slider)
{
pathVersion.BindTo(slider.Path.Version);
pathVersion.BindValueChanged(_ => Position = slider.EndPosition);
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderTailJudgement();
public class SliderTailJudgement : OsuJudgement
{
protected override int NumericResultFor(HitResult result) => 0;
public override bool AffectsCombo => false;
}
}
}
|
Fix audio thread not exiting correctly | // 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.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
{
for (var i = 0; i < managers.Count; i++)
{
var m = managers[i];
m.Update();
}
}
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
lock (managers)
{
// AudioManager's disposal triggers an un-registration
while (managers.Count > 0)
managers[0].Dispose();
}
ManagedBass.Bass.Free();
}
}
}
| // 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.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
{
for (var i = 0; i < managers.Count; i++)
{
var m = managers[i];
m.Update();
}
}
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
lock (managers)
{
foreach (var manager in managers)
manager.Dispose();
managers.Clear();
}
ManagedBass.Bass.Free();
}
}
}
|
Add missing changes for last commit | // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant">
// Copyright (c) Cognisant. All rights reserved.
// </copyright>
namespace CR.ViewModels.Persistence.RavenDB
{
/// <summary>
/// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>.
/// </summary>
// ReSharper disable once InconsistentNaming
internal static class RavenDBViewModelHelper
{
/// <summary>
/// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored.
/// </summary>
/// <typeparam name="TEntity">The type of the View Model.</typeparam>
/// <param name="key">The key of the view model.</param>
/// <returns>The ID of the RavenDB document.</returns>
internal static string MakeId<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}";
}
}
| // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant">
// Copyright (c) Cognisant. All rights reserved.
// </copyright>
namespace CR.ViewModels.Persistence.RavenDB
{
/// <summary>
/// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>.
/// </summary>
// ReSharper disable once InconsistentNaming
internal static class RavenDBViewModelHelper
{
/// <summary>
/// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored.
/// </summary>
/// <typeparam name="TEntity">The type of the View Model.</typeparam>
/// <param name="key">The key of the view model.</param>
/// <returns>The ID of the RavenDB document.</returns>
// ReSharper disable once InconsistentNaming
internal static string MakeID<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}";
}
}
|
Add support for dynamic resizing of iframe when disqus forum loads | @using CkanDotNet.Web.Models.Helpers
<div class="container">
<h2 class="container-title">Comments</h2>
<div class="container-content">
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname
@if (SettingsHelper.GetDisqusDeveloperModeEnabled())
{
<text>var disqus_developer = 1; // developer mode is on</text>
}
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
| @using CkanDotNet.Web.Models.Helpers
<div class="container">
<h2 class="container-title">Comments</h2>
<div class="container-content">
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname
@if (SettingsHelper.GetDisqusDeveloperModeEnabled())
{
<text>var disqus_developer = 1; // developer mode is on</text>
}
@if (SettingsHelper.GetIframeEnabled())
{
<text>
function disqus_config() {
this.callbacks.onNewComment = [function() { resizeFrame() }];
this.callbacks.onReady = [function() { resizeFrame() }];
}
</text>
}
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
|
Change the port to 8000 so we can run as non-admin. | /*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using uhttpsharp.Embedded;
namespace uhttpsharpdemo
{
class Program
{
static void Main(string[] args)
{
HttpServer.Instance.StartUp();
Console.ReadLine();
}
}
}
| /*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using uhttpsharp.Embedded;
namespace uhttpsharpdemo
{
class Program
{
static void Main(string[] args)
{
HttpServer.Instance.Port = 8000;
HttpServer.Instance.StartUp();
Console.ReadLine();
}
}
}
|
Fix dependency of environment gap | namespace ExcelX.AddIn.Command
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExcelX.AddIn.Config;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 「方眼紙」コマンド
/// </summary>
public class MakeGridCommand : ICommand
{
/// <summary>
/// コマンドを実行します。
/// </summary>
public void Execute()
{
// グリッドサイズはピクセル指定
var size = ConfigDocument.Current.Edit.Grid.Size;
// ワークシートを取得
var application = Globals.ThisAddIn.Application;
Excel.Workbook book = application.ActiveWorkbook;
Excel.Worksheet sheet = book.ActiveSheet;
// すべてのセルサイズを同一に設定
Excel.Range all = sheet.Cells;
all.ColumnWidth = size * 0.118;
all.RowHeight = size * 0.75;
}
}
}
| namespace ExcelX.AddIn.Command
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExcelX.AddIn.Config;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 「方眼紙」コマンド
/// </summary>
public class MakeGridCommand : ICommand
{
/// <summary>
/// コマンドを実行します。
/// </summary>
public void Execute()
{
// グリッドサイズはピクセル指定
var size = ConfigDocument.Current.Edit.Grid.Size;
// ワークシートを取得
var application = Globals.ThisAddIn.Application;
Excel.Workbook book = application.ActiveWorkbook;
Excel.Worksheet sheet = book.ActiveSheet;
// 環境値の取得
var cell = sheet.Range["A1"];
double x1 = 10, x2 = 20, y1, y2, a, b;
cell.ColumnWidth = x1;
y1 = cell.Width;
cell.ColumnWidth = x2;
y2 = cell.Width;
a = (y2 - y1) / (x2 - x1);
b = y2 - (y2 - y1) / (x2 - x1) * x2;
// すべてのセルサイズを同一に設定
Excel.Range all = sheet.Cells;
all.ColumnWidth = (size * 0.75 - b) / a;
all.RowHeight = size * 0.75;
}
}
}
|
Create a prefix for Git-Tfs metadata | using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
"git-tfs-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
}
}
| using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
}
}
|
Add support for older versions API | using VkNet.Utils;
namespace VkNet.Model
{
/// <summary>
/// Информация об аудиоальбоме.
/// </summary>
/// <remarks>
/// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>.
/// </remarks>
public class AudioAlbum
{
/// <summary>
/// Идентификатор владельца альбома.
/// </summary>
public long? OwnerId { get; set; }
/// <summary>
/// Идентификатор альбома.
/// </summary>
public long? AlbumId { get; set; }
/// <summary>
/// Название альбома.
/// </summary>
public string Title { get; set; }
#region Методы
/// <summary>
/// Разобрать из json.
/// </summary>
/// <param name="response">Ответ сервера.</param>
/// <returns></returns>
internal static AudioAlbum FromJson(VkResponse response)
{
var album = new AudioAlbum
{
OwnerId = response["owner_id"],
AlbumId = response["id"],
Title = response["title"]
};
return album;
}
#endregion
}
} | using VkNet.Utils;
namespace VkNet.Model
{
/// <summary>
/// Информация об аудиоальбоме.
/// </summary>
/// <remarks>
/// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>.
/// </remarks>
public class AudioAlbum
{
/// <summary>
/// Идентификатор владельца альбома.
/// </summary>
public long? OwnerId { get; set; }
/// <summary>
/// Идентификатор альбома.
/// </summary>
public long? AlbumId { get; set; }
/// <summary>
/// Название альбома.
/// </summary>
public string Title { get; set; }
#region Методы
/// <summary>
/// Разобрать из json.
/// </summary>
/// <param name="response">Ответ сервера.</param>
/// <returns></returns>
internal static AudioAlbum FromJson(VkResponse response)
{
var album = new AudioAlbum
{
OwnerId = response["owner_id"],
AlbumId = response["album_id"] ?? response["id"],
Title = response["title"]
};
return album;
}
#endregion
}
} |
Fix handling of CAST in type completion provider | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Syntax;
namespace NQuery.Authoring.Completion.Providers
{
internal sealed class TypeCompletionProvider : ICompletionProvider
{
public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var token = syntaxTree.Root.FindTokenOnLeft(position);
var castExpression = token.Parent.AncestorsAndSelf()
.OfType<CastExpressionSyntax>()
.FirstOrDefault(c => c.AsKeyword.Span.End <= position);
if (castExpression == null)
return Enumerable.Empty<CompletionItem>();
return from typeName in SyntaxFacts.GetTypeNames()
select GetCompletionItem(typeName);
}
private static CompletionItem GetCompletionItem(string typeName)
{
return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Syntax;
namespace NQuery.Authoring.Completion.Providers
{
internal sealed class TypeCompletionProvider : ICompletionProvider
{
public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var token = syntaxTree.Root.FindTokenOnLeft(position);
var castExpression = token.Parent.AncestorsAndSelf()
.OfType<CastExpressionSyntax>()
.FirstOrDefault(c => !c.AsKeyword.IsMissing && c.AsKeyword.Span.End <= position);
if (castExpression == null)
return Enumerable.Empty<CompletionItem>();
return from typeName in SyntaxFacts.GetTypeNames()
select GetCompletionItem(typeName);
}
private static CompletionItem GetCompletionItem(string typeName)
{
return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type);
}
}
} |
Fix bug with n-level undo of child objects. | using System;
using System.Collections.Generic;
using System.Text;
namespace Csla.Test.LazyLoad
{
[Serializable]
public class AParent : Csla.BusinessBase<AParent>
{
private Guid _id;
public Guid Id
{
get { return _id; }
set
{
_id = value;
PropertyHasChanged();
}
}
private AChildList _children;
public AChildList ChildList
{
get
{
if (_children == null)
{
_children = new AChildList();
for (int count = 0; count < EditLevel; count++)
((Csla.Core.IUndoableObject)_children).CopyState(EditLevel);
}
return _children;
}
}
public AChildList GetChildList()
{
return _children;
}
public int EditLevel
{
get { return base.EditLevel; }
}
protected override object GetIdValue()
{
return _id;
}
public AParent()
{
_id = Guid.NewGuid();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Csla.Test.LazyLoad
{
[Serializable]
public class AParent : Csla.BusinessBase<AParent>
{
private Guid _id;
public Guid Id
{
get { return _id; }
set
{
_id = value;
PropertyHasChanged();
}
}
private static PropertyInfo<AChildList> ChildListProperty =
RegisterProperty<AChildList>(typeof(AParent), new PropertyInfo<AChildList>("ChildList", "Child list"));
public AChildList ChildList
{
get
{
if (!FieldManager.FieldExists(ChildListProperty))
LoadProperty<AChildList>(ChildListProperty, new AChildList());
return GetProperty<AChildList>(ChildListProperty);
}
}
//private AChildList _children;
//public AChildList ChildList
//{
// get
// {
// if (_children == null)
// {
// _children = new AChildList();
// for (int count = 0; count < EditLevel; count++)
// ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel);
// }
// return _children;
// }
//}
public AChildList GetChildList()
{
if (FieldManager.FieldExists(ChildListProperty))
return ReadProperty<AChildList>(ChildListProperty);
else
return null;
//return _children;
}
public int EditLevel
{
get { return base.EditLevel; }
}
protected override object GetIdValue()
{
return _id;
}
public AParent()
{
_id = Guid.NewGuid();
}
}
}
|
Check the user-agent string for "Trident" in order to identify IE11 as an IE browser. This is only needed for a workaround for comments within select elements in IE below version 10 and should be abandoned when possible. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ExoWeb.Templates.MicrosoftAjax
{
/// <summary>
/// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports
/// parsing and loading templates using the Microsoft AJAX syntax.
/// </summary>
internal class AjaxPage : Page
{
internal AjaxPage()
{
IsIE = HttpContext.Current != null && HttpContext.Current.Request.Browser.IsBrowser("IE");
}
int nextControlId;
internal string NextControlId
{
get
{
return "exo" + nextControlId++;
}
}
internal bool IsIE { get; private set; }
public override ITemplate Parse(string name, string template)
{
return Template.Parse(name, template);
}
public override IEnumerable<ITemplate> ParseTemplates(string source, string template)
{
return Block.Parse(source, template).OfType<ITemplate>();
}
public override IEnumerable<ITemplate> LoadTemplates(string path)
{
return Template.Load(path).Cast<ITemplate>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ExoWeb.Templates.MicrosoftAjax
{
/// <summary>
/// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports
/// parsing and loading templates using the Microsoft AJAX syntax.
/// </summary>
internal class AjaxPage : Page
{
internal AjaxPage()
{
IsIE = HttpContext.Current != null &&
(HttpContext.Current.Request.Browser.IsBrowser("IE") ||
(!string.IsNullOrEmpty(HttpContext.Current.Request.UserAgent) && HttpContext.Current.Request.UserAgent.Contains("Trident")));
}
int nextControlId;
internal string NextControlId
{
get
{
return "exo" + nextControlId++;
}
}
internal bool IsIE { get; private set; }
public override ITemplate Parse(string name, string template)
{
return Template.Parse(name, template);
}
public override IEnumerable<ITemplate> ParseTemplates(string source, string template)
{
return Block.Parse(source, template).OfType<ITemplate>();
}
public override IEnumerable<ITemplate> LoadTemplates(string path)
{
return Template.Load(path).Cast<ITemplate>();
}
}
}
|
Add missing call to set content root on WebHostBuilder | using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
| using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
|
Update default converter to handle exception type | namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
} | namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest" || requestType == "System.ExceptionEncountered";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
}
|
Use Pins, not ints. We ain't Arduino! | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
int pinNumber = 10;
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
Console.WriteLine(String.Format("Connecting to {0} and starting SoftPwm on Pin{1}", board, pinNumber));
await board.ConnectAsync();
board[pinNumber].SoftPwm.Enabled = true;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
await board.ConnectAsync();
var pin = board[1];
pin.SoftPwm.Enabled = true;
pin.SoftPwm.DutyCycle = 0.8;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
|
Use ORM instead of open-coded SQL | using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser");
s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote");
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
} | using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
using Tomboy.Db;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = (int)conn.Count<DBUser> ();
s.TotalNumberOfNotes = (int)conn.Count<DBNote> ();
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
} |
Return int or decimal for usage stats | using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public double GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return record.Usage;
}
public double GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return record.Usage;
}
}
}
| using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public decimal GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return (decimal) record.Usage;
}
public int GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return (int) Math.Round(record.Usage);
}
}
}
|
Update root lib to Glimpse.Common | using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse.Common";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
} |
Add XML docs for DefaultSettingValueAttribute | using System;
namespace NFig
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
public object DefaultValue { get; protected set; }
public object SubApp { get; protected set; }
public object Tier { get; protected set; }
public object DataCenter { get; protected set; }
public bool AllowOverrides { get; protected set; } = true;
}
} | using System;
namespace NFig
{
/// <summary>
/// This is the base class for all NFig attributes which specify default values, except for the <see cref="SettingAttribute"/> itself. This attribute is
/// abstract because you should provide the attributes which make sense for your individual setup. The subApp/tier/dataCenter parameters in inheriting
/// attributes should be strongly typed (rather than using "object"), and match the generic parameters used for the NFigStore and Settings object.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
/// <summary>
/// The value of the default being applied. This must be either a convertable string, or a literal value whose type matches that of the setting. For
/// encrypted settings, a default value must always be an encrypted string.
/// </summary>
public object DefaultValue { get; protected set; }
/// <summary>
/// The sub-app which the default is applicable to. If null or the zero-value, it is considered applicable to the "Global" app, as well as any sub-app
/// which does not have another default applied. If your application only uses the Global app (no sub-apps), then you should not include this parameter
/// in inheriting attributes.
/// </summary>
public object SubApp { get; protected set; }
/// <summary>
/// The deployment tier (e.g. local/dev/prod) which the default is applicable to. If null or the zero-value, the default is applicable to any tier.
/// </summary>
public object Tier { get; protected set; }
/// <summary>
/// The data center which the default is applicable to. If null or the zero-value, the default is applicable to any data center.
/// </summary>
public object DataCenter { get; protected set; }
/// <summary>
/// Specifies whether NFig should accept runtime overrides for this default. Note that this only applies to environments where this particular default
/// is the active default. For example, if you set an default for Tier=Prod/DataCenter=Any which DOES NOT allow defaults, and another default for
/// Tier=Prod/DataCenter=East which DOES allow overrides, then you will be able to set overrides in Prod/East, but you won't be able to set overrides
/// in any other data center.
/// </summary>
public bool AllowOverrides { get; protected set; } = true;
}
} |
Check for specific bit now to check if a game is downloaded at the moment | using System;
namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
public bool IsDownloading
{
get { return CheckDownloading(State); }
}
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
/// <param name="appState"></param>
/// <returns></returns>
public static bool CheckDownloading(int appState)
{
// 6: In queue for update
// 1026: In queue
// 1042: download running
return appState == 6 || appState == 1026 || appState == 1042 || appState == 1062 || appState == 1030;
}
public override string ToString()
{
return Name;
}
}
}
| namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public bool IsDownloading => CheckDownloading(State);
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public static bool CheckDownloading(int appState)
{
// The second bit defines if anything for the app needs to be downloaded
// Doesn't matter if queued, download running and so on
return IsBitSet(appState, 1);
}
public override string ToString()
{
return Name;
}
private static bool IsBitSet(int b, int pos)
{
return (b & (1 << pos)) != 0;
}
}
}
|
Fix a bug where it didn't read .binlog files correctly. | using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
| using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
structuredLogger.Shutdown();
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
|
Append IIS queues with worker PID. | /* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}",
base.GetPrimaryQueueName(),
Environment.MachineName);
}
}
}
| /* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}_{2}",
base.GetPrimaryQueueName(),
Environment.MachineName,
Process.GetCurrentProcess().Id
);
}
}
}
|
Add "There are no commands". | namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
} | namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
if (commandsInfo.Count == 0)
{
Output.WriteInfo("There are no commands.");
return true;
}
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
} |
Fix - Included some missing cases for JSON string types. | using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
} | using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
case JTokenType.TimeSpan:
case JTokenType.Uri:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
} |
Return simple object representing the torrent. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var torrent = _torrentEngine.Add(data, savePath, label);
return torrent;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var manager = _torrentEngine.Add(data, savePath, label);
return new
{
manager.Torrent.Name,
manager.Torrent.Size
};
}
}
}
|
Make PowerShellScripts class static per review. | namespace NuGet.VisualStudio {
public class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
| namespace NuGet.VisualStudio {
public static class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
|
Update ReplyAsync Task to return the sent message. | using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
| using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
return await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
|
Update the level selector input at the bottom of the leaderboard | using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
_levelName.text = _levels[pos];
_leftArrow.gameObject.SetActive(false);
if (_levels.Length <= 1) _rightArrow.gameObject.SetActive(false);
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length > 1) _rightArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
_leftArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
}
| using System;
using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
var levelShown = FindObjectOfType<LevelToLoad>().GetLevelToLoad();
pos = GetPosOfLevelShown(levelShown);
_levelName.text = _levels[pos];
UpdateArrows();
}
private int GetPosOfLevelShown(string levelShown)
{
for (var i = 0; i < _levels.Length; ++i)
{
var level = _levels[i];
if (level.IndexOf(levelShown, StringComparison.InvariantCultureIgnoreCase) > -1)
return i;
}
//Defaults at loading the first entry if nothing found
return 0;
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
private void UpdateArrows()
{
_leftArrow.gameObject.SetActive(true);
_rightArrow.gameObject.SetActive(true);
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
}
}
|
Use official namespace (better for fallback) | namespace AngleSharp
{
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
| namespace System.Threading.Tasks
{
using System.Collections.Generic;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
|
Remove unit service reference to ignore for reporting | using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db, includeIgnored: true)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db, Boolean includeIgnored = false)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.Where(unit => includeIgnored || !unit.IgnoreForReports)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
} |
Fix binding validation which disallow publishing to HTTPS addresses. | using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
}
| using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
} |
Add exception handling to console | using System;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
var dds = new DDSImage(args[0]);
dds.Save(args[1]);
}
}
}
| using System;
using System.IO;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
System.Console.WriteLine("ERROR: input and output file required\n");
Environment.Exit(1);
}
var input = args[0];
var output = args[1];
if (!File.Exists(input))
{
System.Console.WriteLine("ERROR: input file does not exist\n");
Environment.Exit(1);
}
try
{
var dds = new DDSImage(input);
dds.Save(output);
}
catch (Exception e)
{
System.Console.WriteLine("ERROR: failed to convert DDS file\n");
System.Console.WriteLine(e);
Environment.Exit(1);
}
if (File.Exists(output))
{
System.Console.WriteLine("Successfully created " + output);
}
else
{
System.Console.WriteLine("ERROR: something went wrong!\n");
Environment.Exit(1);
}
}
}
}
|
Use “yield” instead of List for GetTransitions | using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
return new List<Transition>{
new Transition{
Label = Label,
Process = Inner
}
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
| using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
yield return new Transition
{
Label = Label,
Process = Inner
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
|
Set UserAgent on HTTP Client. | using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client = new HttpClient();
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
} | using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client;
static HttpClientWrapper()
{
Client = new HttpClient();
Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36");
}
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
} |
Revert "Using ternary instead of coalesce in fallback enumerable value selection" | namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Extensions;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var existingValueNotNull = existingValue.GetIsNotDefaultComparison();
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Condition(
existingValueNotNull,
existingValue,
emptyEnumerable,
existingValue.Type);
}
}
}
} | namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Coalesce(existingValue, emptyEnumerable);
}
}
}
} |
Test launching 10 listeners in CI | using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;
namespace IntegrationEngine.Tests.JobProcessor
{
public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
{
public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }
[SetUp]
public void Setup()
{
MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
.Returns<IMessageQueueListener>(null);
Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
}
[Test]
public void ShouldStartListener()
{
Subject.ListenerTaskCount = 1;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
}
[Test]
public void ShouldStartMultipleListeners()
{
var listenerTaskCount = 3;
Subject.ListenerTaskCount = listenerTaskCount;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
Times.Exactly(listenerTaskCount));
}
[Test]
public void ShouldSetCancellationTokenOnDispose()
{
Subject.CancellationTokenSource = new CancellationTokenSource();
Subject.Dispose();
Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
}
}
}
| using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;
namespace IntegrationEngine.Tests.JobProcessor
{
public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
{
public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }
[SetUp]
public void Setup()
{
MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
.Returns<IMessageQueueListener>(null);
Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
}
[Test]
public void ShouldStartListener()
{
Subject.ListenerTaskCount = 1;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
}
[Test]
public void ShouldStartMultipleListeners()
{
var listenerTaskCount = 10;
Subject.ListenerTaskCount = listenerTaskCount;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
Times.Exactly(listenerTaskCount));
}
[Test]
public void ShouldSetCancellationTokenOnDispose()
{
Subject.CancellationTokenSource = new CancellationTokenSource();
Subject.Dispose();
Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
}
}
}
|
Add get best id method for season images. | namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Basic;
using Newtonsoft.Json;
/// <summary>
/// A collection of images for a Trakt season.
/// </summary>
public class TraktSeasonImages
{
/// <summary>
/// A poster image set for various sizes.
/// </summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>
/// A thumbnail image.
/// </summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt season.</summary>
public class TraktSeasonImages
{
/// <summary>Gets or sets the screenshot image set.</summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>Gets or sets the thumb image.</summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.