Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use custom string comparer for RangeSortedDictionary | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsQuery.Implementation
{
public class TrueStringComparer : IComparer<string>, IEqualityComparer<string>
{
public int Compare(string x, string y)
{
int pos = 0;
int len = Math.Min(x.Length, y.Length);
while (pos < len)
{
var xi = (int)x[pos];
var yi = (int)y[pos];
if (xi < yi)
{
return -1;
}
else if (yi < xi)
{
return 1;
}
pos++;
}
if (x.Length < y.Length)
{
return -1;
}
else if (y.Length < x.Length)
{
return 1;
}
else
{
return 0;
}
}
public bool Equals(string x, string y)
{
return Compare(x, y) == 0;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsQuery.Implementation
{
public class TrueStringComparer : IComparer<string>, IEqualityComparer<string>
{
public int Compare(string x, string y)
{
int pos = 0;
int len = Math.Min(x.Length, y.Length);
while (pos < len)
{
var xi = (int)x[pos];
var yi = (int)y[pos];
if (xi < yi)
{
return -1;
}
else if (yi < xi)
{
return 1;
}
pos++;
}
if (x.Length < y.Length)
{
return -1;
}
else if (y.Length < x.Length)
{
return 1;
}
else
{
return 0;
}
}
public bool Equals(string x, string y)
{
return x.Length == y.Length && Compare(x, y) == 0;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
}
|
Add field names in returned tuple of EnumerateItemAndIfIsLast() | using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Sakuno.Collections
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class EnumerableExtensions
{
public static bool AnyNull<T>(this IEnumerable<T> source) where T : class
{
foreach (var item in source)
if (item == null)
return true;
return false;
}
public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source)
{
foreach (var item in source)
{
if (item is TExclusion)
continue;
yield return item;
}
}
public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance);
public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer);
public static IEnumerable<(T, bool)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items)
{
using (var enumerator = items.GetEnumerator())
{
var last = default(T);
if (!enumerator.MoveNext())
yield break;
var shouldYield = false;
do
{
if (shouldYield)
yield return (last, false);
shouldYield = true;
last = enumerator.Current;
} while (enumerator.MoveNext());
yield return (last, true);
}
}
}
}
| using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Sakuno.Collections
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class EnumerableExtensions
{
public static bool AnyNull<T>(this IEnumerable<T> source) where T : class
{
foreach (var item in source)
if (item == null)
return true;
return false;
}
public static IEnumerable<TSource> NotOfType<TSource, TExclusion>(this IEnumerable<TSource> source)
{
foreach (var item in source)
{
if (item is TExclusion)
continue;
yield return item;
}
}
public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> source) => source.OrderBy(IdentityFunction<T>.Instance);
public static IEnumerable<T> OrderBySelf<T>(this IEnumerable<T> items, IComparer<T> comparer) => items.OrderBy(IdentityFunction<T>.Instance, comparer);
public static IEnumerable<(T Item, bool IsLast)> EnumerateItemAndIfIsLast<T>(this IEnumerable<T> items)
{
using (var enumerator = items.GetEnumerator())
{
var last = default(T);
if (!enumerator.MoveNext())
yield break;
var shouldYield = false;
do
{
if (shouldYield)
yield return (last, false);
shouldYield = true;
last = enumerator.Current;
} while (enumerator.MoveNext());
yield return (last, true);
}
}
}
}
|
Correct ordering of method arguments. | namespace OpenRealEstate.Services
{
public interface ITransmorgrifier
{
/// <summary>
/// Converts some given data into a listing instance.
/// </summary>
/// <param name="data">some data source, like Xml data or json data.</param>
/// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param>
/// <param name="areBadCharactersRemoved">Help clean up the data.</param>
/// <returns>List of listings and any unhandled data.</returns>
/// <remarks>Why does <code>isClearAllIsModified</code> default to <code>false</code>? Because when you generally load some data into a new listing instance, you want to see which properties </remarks>
ConvertToResult ConvertTo(string data,
bool isClearAllIsModified = false,
bool areBadCharactersRemoved = false);
}
} | namespace OpenRealEstate.Services
{
public interface ITransmorgrifier
{
/// <summary>
/// Converts some given data into a listing instance.
/// </summary>
/// <param name="data">some data source, like Xml data or json data.</param>
/// <param name="areBadCharactersRemoved">Help clean up the data.</param>
/// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param>
/// <returns>List of listings and any unhandled data.</returns>
/// <remarks>Why does <code>isClearAllIsModified</code> default to <code>false</code>? Because when you generally load some data into a new listing instance, you want to see which properties </remarks>
ConvertToResult ConvertTo(string data,
bool areBadCharactersRemoved = false,
bool isClearAllIsModified = false);
}
} |
Set default values to sync field attribute | using LiteNetLib;
using System;
namespace LiteNetLibManager
{
[AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
public class SyncFieldAttribute : Attribute
{
/// <summary>
/// Sending method type
/// </summary>
public DeliveryMethod deliveryMethod;
/// <summary>
/// Interval to send network data (0.01f to 2f)
/// </summary>
public float sendInterval = 0.1f;
/// <summary>
/// If this is `TRUE` it will syncing although no changes
/// </summary>
public bool alwaysSync;
/// <summary>
/// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later)
/// </summary>
public bool doNotSyncInitialDataImmediately;
/// <summary>
/// How data changes handle and sync
/// </summary>
public LiteNetLibSyncField.SyncMode syncMode;
/// <summary>
/// Function name which will be invoked when data changed
/// </summary>
public string hook;
}
}
| using LiteNetLib;
using System;
namespace LiteNetLibManager
{
[AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
public class SyncFieldAttribute : Attribute
{
/// <summary>
/// Sending method type
/// </summary>
public DeliveryMethod deliveryMethod = DeliveryMethod.ReliableOrdered;
/// <summary>
/// Interval to send network data (0.01f to 2f)
/// </summary>
public float sendInterval = 0.1f;
/// <summary>
/// If this is `TRUE` it will syncing although no changes
/// </summary>
public bool alwaysSync = false;
/// <summary>
/// If this is `TRUE` it will not sync initial data immdediately with spawn message (it will sync later)
/// </summary>
public bool doNotSyncInitialDataImmediately = false;
/// <summary>
/// How data changes handle and sync
/// </summary>
public LiteNetLibSyncField.SyncMode syncMode = LiteNetLibSyncField.SyncMode.ServerToClients;
/// <summary>
/// Function name which will be invoked when data changed
/// </summary>
public string hook = string.Empty;
}
}
|
Fix Windows-style path separators not being migrated on Unix systems | using System;
using Microsoft.EntityFrameworkCore.Migrations;
using System.IO;
namespace osu.Game.Migrations
{
public partial class StandardizePaths : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
string sanitized = Path.DirectorySeparatorChar.ToString();
string standardized = "/";
// Escaping \ does not seem to be needed.
migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{sanitized}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{sanitized}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{sanitized}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{sanitized}', '{standardized}')");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| using System;
using Microsoft.EntityFrameworkCore.Migrations;
using System.IO;
namespace osu.Game.Migrations
{
public partial class StandardizePaths : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
string windowsStyle = @"\";
string standardized = "/";
// Escaping \ does not seem to be needed.
migrationBuilder.Sql($"UPDATE `BeatmapInfo` SET `Path` = REPLACE(`Path`, '{windowsStyle}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `AudioFile` = REPLACE(`AudioFile`, '{windowsStyle}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapMetadata` SET `BackgroundFile` = REPLACE(`BackgroundFile`, '{windowsStyle}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `BeatmapSetFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')");
migrationBuilder.Sql($"UPDATE `SkinFileInfo` SET `Filename` = REPLACE(`Filename`, '{windowsStyle}', '{standardized}')");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
|
Add one overload for Nullable<T>.SelectMany. | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System;
using Narvalo;
// Query Expression Pattern for nullables.
public static class Qullable
{
public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
where TSource : struct
where TResult : struct
{
Require.NotNull(selector, nameof(selector));
return @this.HasValue ? (TResult?)selector(@this.Value) : null;
}
public static TSource? Where<TSource>(
this TSource? @this,
Func<TSource, bool> predicate)
where TSource : struct
{
Require.NotNull(predicate, nameof(predicate));
return @this.HasValue && predicate(@this.Value) ? @this : null;
}
public static TResult? SelectMany<TSource, TMiddle, TResult>(
this TSource? @this,
Func<TSource, TMiddle?> valueSelector,
Func<TSource, TMiddle, TResult> resultSelector)
where TSource : struct
where TMiddle : struct
where TResult : struct
{
Require.NotNull(valueSelector, nameof(valueSelector));
Require.NotNull(resultSelector, nameof(resultSelector));
if (!@this.HasValue) { return null; }
var middle = valueSelector(@this.Value);
if (!middle.HasValue) { return null; }
return resultSelector(@this.Value, middle.Value);
}
}
}
| // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System;
using Narvalo;
// Query Expression Pattern for nullables.
public static class Qullable
{
public static TResult? Select<TSource, TResult>(this TSource? @this, Func<TSource, TResult> selector)
where TSource : struct
where TResult : struct
{
Require.NotNull(selector, nameof(selector));
return @this is TSource v ? (TResult?)selector(v) : null;
}
public static TSource? Where<TSource>(
this TSource? @this,
Func<TSource, bool> predicate)
where TSource : struct
{
Require.NotNull(predicate, nameof(predicate));
return @this is TSource v && predicate(v) ? @this : null;
}
public static TResult? SelectMany<TSource, TResult>(
this TSource? @this,
Func<TSource, TResult?> selector)
where TSource : struct
where TResult : struct
{
Require.NotNull(selector, nameof(selector));
return @this is TSource v ? selector(v) : null;
}
public static TResult? SelectMany<TSource, TMiddle, TResult>(
this TSource? @this,
Func<TSource, TMiddle?> valueSelector,
Func<TSource, TMiddle, TResult> resultSelector)
where TSource : struct
where TMiddle : struct
where TResult : struct
{
Require.NotNull(valueSelector, nameof(valueSelector));
Require.NotNull(resultSelector, nameof(resultSelector));
return @this is TSource v && valueSelector(v) is TMiddle m
? resultSelector(v, m)
: (TResult?)null;
}
}
}
|
Add a comma to the MvcTurbine filters, which will prevent MvcTurbine from being included but not block out MvcTurbine.*. | namespace MvcTurbine.ComponentModel {
using System;
/// <summary>
/// Defines common assemblies to filter. These assemblies are:
/// System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
[Serializable]
public class CommonAssemblyFilter : AssemblyFilter {
/// <summary>
/// Creates an instance and applies the default filters.
/// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
public CommonAssemblyFilter() {
AddDefaults();
}
/// <summary>
/// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
private void AddDefaults() {
AddFilter("System");
AddFilter("mscorlib");
AddFilter("Microsoft");
AddFilter("MvcTurbine");
AddFilter("MvcTurbine.Web");
// Ignore the Visual Studio extra assemblies!
AddFilter("WebDev");
AddFilter("CppCodeProvider");
}
}
} | namespace MvcTurbine.ComponentModel {
using System;
/// <summary>
/// Defines common assemblies to filter. These assemblies are:
/// System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
[Serializable]
public class CommonAssemblyFilter : AssemblyFilter {
/// <summary>
/// Creates an instance and applies the default filters.
/// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
public CommonAssemblyFilter() {
AddDefaults();
}
/// <summary>
/// Sets the following filters as default, (System, mscorlib, Microsoft, WebDev, CppCodeProvider).
/// </summary>
private void AddDefaults() {
AddFilter("System");
AddFilter("mscorlib");
AddFilter("Microsoft");
AddFilter("MvcTurbine,");
AddFilter("MvcTurbine.Web");
// Ignore the Visual Studio extra assemblies!
AddFilter("WebDev");
AddFilter("CppCodeProvider");
}
}
} |
Fix issue with null values returned by Memory provider | using System.Collections.Generic;
using TechSmith.Hyde.Table.Azure;
namespace TechSmith.Hyde.Table.Memory
{
internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
{
public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
: base( entities )
{
}
private DynamicMemoryQuery( DynamicMemoryQuery previous )
: base( previous )
{
}
protected override AbstractQuery<dynamic> CreateCopy()
{
return new DynamicMemoryQuery( this );
}
internal override dynamic Convert( GenericTableEntity e )
{
return e.ConvertToDynamic();
}
}
}
| using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using TechSmith.Hyde.Table.Azure;
namespace TechSmith.Hyde.Table.Memory
{
internal class DynamicMemoryQuery : AbstractMemoryQuery<dynamic>
{
public DynamicMemoryQuery( IEnumerable<GenericTableEntity> entities )
: base( entities )
{
}
private DynamicMemoryQuery( DynamicMemoryQuery previous )
: base( previous )
{
}
protected override AbstractQuery<dynamic> CreateCopy()
{
return new DynamicMemoryQuery( this );
}
internal override dynamic Convert( GenericTableEntity e )
{
return StripNullValues( e.ConvertToDynamic() );
}
private static dynamic StripNullValues( dynamic obj )
{
dynamic result = new ExpandoObject();
foreach ( var p in ( obj as IDictionary<string, object> ).Where( p => p.Value != null ) )
{
( (IDictionary<string, object>) result ).Add( p );
}
return result;
}
}
}
|
Add trivial history programming to overlay window to clear each turn | using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
public HearthWindow()
{
info = new HearthstoneTextBlock();
info.Text = "";
info.FontSize = 12;
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(info, fromTop);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
}
public void MoveToHistory()
{
return;
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
| using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
public HearthWindow()
{
info = new HearthstoneTextBlock();
info.Text = "";
info.FontSize = 12;
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(info, fromTop);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
}
public void MoveToHistory()
{
info.Text = "";
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
|
Remove unnecessary null coalescing operator | namespace NetIRC.Messages
{
public class PingMessage : IRCMessage, IServerMessage
{
public string Target { get; }
public PingMessage(ParsedIRCMessage parsedMessage)
{
Target = parsedMessage.Trailing ?? parsedMessage.Parameters[0];
}
}
}
| namespace NetIRC.Messages
{
public class PingMessage : IRCMessage, IServerMessage
{
public string Target { get; }
public PingMessage(ParsedIRCMessage parsedMessage)
{
Target = parsedMessage.Trailing;
}
}
}
|
Apply changes to AllowScreenSuspension bindable | // 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.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
// This is the only usage game-wide of suspension changes.
// Assert to ensure we don't accidentally forget this in the future.
Debug.Assert(host.AllowScreenSuspension.Value);
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
if (host != null)
host.AllowScreenSuspension.Value = true;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
private readonly Bindable<bool> disableSuspensionBindable = new Bindable<bool>();
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused =>
{
if (paused.NewValue)
host.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
else
host.AllowScreenSuspension.AddSource(disableSuspensionBindable);
}, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
host?.AllowScreenSuspension.RemoveSource(disableSuspensionBindable);
}
}
}
|
Use float instead of int | using System;
namespace FalconUDP
{
internal static class FalconHelper
{
internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort seq,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = seq;
*(ushort*)(ptr + 3) = payloadSize;
}
}
internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = payloadSize;
}
}
internal static void WriteAck(AckDetail ack,
byte[] dstBuffer,
int dstIndex)
{
float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000;
ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
? ushort.MaxValue
: (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue
WriteFalconHeader(dstBuffer,
dstIndex,
ack.Type,
ack.Channel,
ack.Seq,
stopoverMilliseconds);
}
}
}
| using System;
namespace FalconUDP
{
internal static class FalconHelper
{
internal static unsafe void WriteFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort seq,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = seq;
*(ushort*)(ptr + 3) = payloadSize;
}
}
internal static unsafe void WriteAdditionalFalconHeader(byte[] dstBuffer,
int dstIndex,
PacketType type,
SendOptions opts,
ushort payloadSize)
{
fixed (byte* ptr = &dstBuffer[dstIndex])
{
*ptr = (byte)((byte)opts | (byte)type);
*(ushort*)(ptr + 1) = payloadSize;
}
}
internal static void WriteAck(AckDetail ack,
byte[] dstBuffer,
int dstIndex)
{
float ellapsedMilliseconds = ack.EllapsedSecondsSinceEnqueud * 1000.0f;
ushort stopoverMilliseconds = ellapsedMilliseconds > ushort.MaxValue
? ushort.MaxValue
: (ushort)ellapsedMilliseconds; // TODO log warning if was greater than MaxValue
WriteFalconHeader(dstBuffer,
dstIndex,
ack.Type,
ack.Channel,
ack.Seq,
stopoverMilliseconds);
}
}
}
|
Change MembershipIdentity so it is not an abstract class. bugid: 153 | using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;
namespace Csla.Security
{
public abstract partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
{
public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
}
}
}
| using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.DataPortalClient;
using Csla.Silverlight;
using Csla.Core;
namespace Csla.Security
{
public partial class MembershipIdentity : ReadOnlyBase<MembershipIdentity>, IIdentity
{
public static void GetMembershipIdentity<T>(EventHandler<DataPortalResult<T>> completed, string userName, string password, bool isRunOnWebServer) where T : MembershipIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(new Criteria(userName, password, typeof(T), isRunOnWebServer));
}
}
}
|
Add missing enums for File purpose | namespace Stripe
{
public static class FilePurpose
{
public const string AdditionalVerification = "additional_verification";
public const string BusinessIcon = "business_icon";
public const string BusinessLogo = "business_logo";
public const string CustomerSignature = "customer_signature";
public const string DisputeEvidence = "dispute_evidence";
public const string DocumentProviderIdentityDocument = "document_provider_identity_document";
public const string FinanceReportRun = "finance_report_run";
public const string IdentityDocument = "identity_document";
public const string IncorporationArticle = "incorporation_article";
public const string IncorporationDocument = "incorporation_document";
public const string PaymentProviderTransfer = "payment_provider_transfer";
public const string PciDocument = "pci_document";
public const string ProductFeed = "product_feed";
public const string SigmaScheduledQuery = "sigma_scheduled_query";
public const string TaxDocumentUserUpload = "tax_document_user_upload";
}
}
| namespace Stripe
{
public static class FilePurpose
{
public const string AccountRequirement = "account_requirement";
public const string AdditionalVerification = "additional_verification";
public const string BusinessIcon = "business_icon";
public const string BusinessLogo = "business_logo";
public const string CustomerSignature = "customer_signature";
public const string DisputeEvidence = "dispute_evidence";
public const string DocumentProviderIdentityDocument = "document_provider_identity_document";
public const string FinanceReportRun = "finance_report_run";
public const string IdentityDocument = "identity_document";
public const string IdentityDocumentDownloadable = "identity_document_downloadable";
public const string IncorporationArticle = "incorporation_article";
public const string IncorporationDocument = "incorporation_document";
public const string PaymentProviderTransfer = "payment_provider_transfer";
public const string PciDocument = "pci_document";
public const string Selfie = "selfie";
public const string ProductFeed = "product_feed";
public const string SigmaScheduledQuery = "sigma_scheduled_query";
public const string TaxDocumentUserUpload = "tax_document_user_upload";
}
}
|
Add disableOnPlay option to changeOrderInLayer | using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ChangeOrderInLayer : MonoBehaviour
{
#pragma warning disable 0649
[SerializeField]
private Renderer _renderer;
[SerializeField]
private int orderInLayer;
#pragma warning restore 0649
void Start()
{
if (_renderer == null)
_renderer = GetComponent<Renderer>();
_renderer.sortingOrder = orderInLayer;
}
void Update ()
{
if (orderInLayer != _renderer.sortingOrder)
_renderer.sortingOrder = orderInLayer;
}
}
| using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ChangeOrderInLayer : MonoBehaviour
{
[SerializeField]
private Renderer _renderer;
[SerializeField]
private int orderInLayer;
[SerializeField]
private string sortingLayer = "Default";
[SerializeField]
private bool disableOnPlay = true;
private void Awake()
{
if (disableOnPlay && Application.isPlaying)
enabled = false;
}
void Start()
{
if (_renderer == null)
_renderer = GetComponent<Renderer>();
_renderer.sortingOrder = orderInLayer;
}
void Update ()
{
if (orderInLayer != _renderer.sortingOrder)
_renderer.sortingOrder = orderInLayer;
if (!string.IsNullOrEmpty(sortingLayer))
_renderer.sortingLayerName = sortingLayer;
}
}
|
Use Be instead of BeEquivalentTo | using FluentAssertions;
using FluentAssertions.Execution;
namespace Bearded.Utilities.Testing
{
public sealed class MaybeAssertions<T>
{
private readonly Maybe<T> subject;
public MaybeAssertions(Maybe<T> instance) => subject = instance;
[CustomAssertion]
public void BeJust(T value, string because = "", params object[] becauseArgs)
{
BeJust().Which.Should().BeEquivalentTo(value, because, becauseArgs);
}
[CustomAssertion]
public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs)
{
var onValueCalled = false;
var matched = default(T);
subject.Match(
onValue: actual =>
{
onValueCalled = true;
matched = actual;
}, onNothing: () => { });
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(onValueCalled)
.FailWith("Expected maybe to have value, but had none.");
return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched);
}
[CustomAssertion]
public void BeNothing(string because = "", params object[] becauseArgs)
{
var onNothingCalled = false;
subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(onNothingCalled)
.FailWith("Expected maybe to be nothing, but had value.");
}
}
}
| using FluentAssertions;
using FluentAssertions.Execution;
namespace Bearded.Utilities.Testing
{
public sealed class MaybeAssertions<T>
{
private readonly Maybe<T> subject;
public MaybeAssertions(Maybe<T> instance) => subject = instance;
[CustomAssertion]
public void BeJust(T value, string because = "", params object[] becauseArgs)
{
BeJust().Which.Should().Be(value, because, becauseArgs);
}
[CustomAssertion]
public AndWhichConstraint<MaybeAssertions<T>, T> BeJust(string because = "", params object[] becauseArgs)
{
var onValueCalled = false;
var matched = default(T);
subject.Match(
onValue: actual =>
{
onValueCalled = true;
matched = actual;
}, onNothing: () => { });
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(onValueCalled)
.FailWith("Expected maybe to have value, but had none.");
return new AndWhichConstraint<MaybeAssertions<T>, T>(this, matched);
}
[CustomAssertion]
public void BeNothing(string because = "", params object[] becauseArgs)
{
var onNothingCalled = false;
subject.Match(onValue: _ => { }, onNothing: () => onNothingCalled = true);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(onNothingCalled)
.FailWith("Expected maybe to be nothing, but had value.");
}
}
}
|
Fix certificate generation not refreshing test | using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using Procon.Service.Shared;
using Procon.Setup.Models;
namespace Procon.Setup.Test.Models {
[TestFixture]
public class CertificateModelTest {
/// <summary>
/// Tests a certificate will be generated and can be read by .NET
/// </summary>
[Test]
public void TestGenerate() {
CertificateModel model = new CertificateModel();
// Delete the certificate if it exists.
Defines.CertificatesDirectoryCommandServerPfx.Delete();
// Create a new certificate
model.Generate();
// Certificate exists
Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists);
// Loads the certificates
var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password);
// Certificate can be loaded.
Assert.IsNotNull(loadedCertificate);
Assert.IsNotNull(loadedCertificate.PrivateKey);
}
}
}
| using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using Procon.Service.Shared;
using Procon.Setup.Models;
namespace Procon.Setup.Test.Models {
[TestFixture]
public class CertificateModelTest {
/// <summary>
/// Tests a certificate will be generated and can be read by .NET
/// </summary>
[Test]
public void TestGenerate() {
CertificateModel model = new CertificateModel();
// Delete the certificate if it exists.
Defines.CertificatesDirectoryCommandServerPfx.Delete();
// Create a new certificate
model.Generate();
// Certificate exists
Defines.CertificatesDirectoryCommandServerPfx.Refresh();
Assert.IsTrue(Defines.CertificatesDirectoryCommandServerPfx.Exists);
// Loads the certificates
var loadedCertificate = new X509Certificate2(Defines.CertificatesDirectoryCommandServerPfx.FullName, model.Password);
// Certificate can be loaded.
Assert.IsNotNull(loadedCertificate);
Assert.IsNotNull(loadedCertificate.PrivateKey);
}
}
}
|
Fix the help message of output_pattern | namespace BigEgg.Tools.JsonComparer.Parameters
{
using BigEgg.Tools.ConsoleExtension.Parameters;
[Command("split", "Split the big JSON file to multiple small files.")]
public class SplitParameter
{
[StringProperty("input", "i", "The path of JSON file to split.", Required = true)]
public string FileName { get; set; }
[StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)]
public string OutputPath { get; set; }
[StringProperty("node_name", "n", "The name of node to split.", Required = true)]
public string NodeName { get; set; }
[StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, ${index} for the child index.")]
public string OutputFileNamePattern { get; set; }
}
}
| namespace BigEgg.Tools.JsonComparer.Parameters
{
using BigEgg.Tools.ConsoleExtension.Parameters;
[Command("split", "Split the big JSON file to multiple small files.")]
public class SplitParameter
{
[StringProperty("input", "i", "The path of JSON file to split.", Required = true)]
public string FileName { get; set; }
[StringProperty("output", "o", "The path to store the splited JSON files.", Required = true)]
public string OutputPath { get; set; }
[StringProperty("node_name", "n", "The name of node to split.", Required = true)]
public string NodeName { get; set; }
[StringProperty("output_pattern", "op", "The output file name pattern. Use '${name}' for node name, '${index}' for the child index.")]
public string OutputFileNamePattern { get; set; }
}
}
|
Improve how much space we reserve for tag changes | using System.IO;
using System.Linq;
using SpotifyRecorder.Core.Abstractions.Entities;
using SpotifyRecorder.Core.Abstractions.Services;
using TagLib;
using TagLib.Id3v2;
using File = TagLib.File;
namespace SpotifyRecorder.Core.Implementations.Services
{
public class ID3TagService : IID3TagService
{
public ID3Tags GetTags(RecordedSong song)
{
var tagFile = File.Create(new MemoryFileAbstraction(new MemoryStream(song.Data)));
return new ID3Tags
{
Title = tagFile.Tag.Title,
Artists = tagFile.Tag.Performers,
Picture = tagFile.Tag.Pictures.FirstOrDefault()?.Data.Data
};
}
public void UpdateTags(ID3Tags tags, RecordedSong song)
{
using (var stream = new MemoryStream(song.Data.Length + 1000))
{
stream.Write(song.Data, 0, song.Data.Length);
stream.Position = 0;
var tagFile = File.Create(new MemoryFileAbstraction(stream));
tagFile.Tag.Title = tags.Title;
tagFile.Tag.Performers = tags.Artists;
if (tags.Picture != null)
{
tagFile.Tag.Pictures = new IPicture[]
{
new Picture(new ByteVector(tags.Picture, tags.Picture.Length)),
};
}
tagFile.Save();
song.Data = stream.ToArray();
}
}
}
} | using System.IO;
using System.Linq;
using SpotifyRecorder.Core.Abstractions.Entities;
using SpotifyRecorder.Core.Abstractions.Services;
using TagLib;
using TagLib.Id3v2;
using File = TagLib.File;
namespace SpotifyRecorder.Core.Implementations.Services
{
public class ID3TagService : IID3TagService
{
public ID3Tags GetTags(RecordedSong song)
{
var tagFile = File.Create(new MemoryFileAbstraction(new MemoryStream(song.Data)));
return new ID3Tags
{
Title = tagFile.Tag.Title,
Artists = tagFile.Tag.Performers,
Picture = tagFile.Tag.Pictures.FirstOrDefault()?.Data.Data
};
}
public void UpdateTags(ID3Tags tags, RecordedSong song)
{
using (var stream = new MemoryStream(song.Data.Length * 2))
{
stream.Write(song.Data, 0, song.Data.Length);
stream.Position = 0;
var tagFile = File.Create(new MemoryFileAbstraction(stream));
tagFile.Tag.Title = tags.Title;
tagFile.Tag.Performers = tags.Artists;
if (tags.Picture != null)
{
tagFile.Tag.Pictures = new IPicture[]
{
new Picture(new ByteVector(tags.Picture, tags.Picture.Length)),
};
}
tagFile.Save();
song.Data = stream.ToArray();
}
}
}
} |
Remove extra char that sneaked onto XML comment | using System.Collections.Generic;
using Autofac.Core;
namespace Autofac
{
/// <summary>
/// The details of an individual request to resolve a service.
/// </summary>
public class ResolveRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="ResolveRequest"/> class.
/// </summary>
/// <param name="service">The service being resolved.</param>
/// <param name="registration">The component registration for the service.</param>
/// <param name="parameters">The parameters used when resolving the service.</param>
/// <param name="decoratorTarget">The target component to be decorated.</param>
public ResolveRequest(Service service, IComponentRegistration registration, IEnumerable<Parameter> parameters, IComponentRegistration? decoratorTarget = null)
{
Service = service;
Registration = registration;
Parameters = parameters;
DecoratorTarget = decoratorTarget;
}
/// <summary>
/// Gets the service being resolved.
/// </summary>
public Service Service { get; }
/// <summary>
/// Gets the component registration for the service being resolved.
/// </summary>
public IComponentRegistration Registration { get; }
/// <summary>
/// Gets the parameters used when resolving the service.
/// </summary>
public IEnumerable<Parameter> Parameters { get; }
/// <summary>
/// Gets the component registration for the decorator target if configured.
/// </summary>2
public IComponentRegistration? DecoratorTarget { get; }
}
}
| using System.Collections.Generic;
using Autofac.Core;
namespace Autofac
{
/// <summary>
/// The details of an individual request to resolve a service.
/// </summary>
public class ResolveRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="ResolveRequest"/> class.
/// </summary>
/// <param name="service">The service being resolved.</param>
/// <param name="registration">The component registration for the service.</param>
/// <param name="parameters">The parameters used when resolving the service.</param>
/// <param name="decoratorTarget">The target component to be decorated.</param>
public ResolveRequest(Service service, IComponentRegistration registration, IEnumerable<Parameter> parameters, IComponentRegistration? decoratorTarget = null)
{
Service = service;
Registration = registration;
Parameters = parameters;
DecoratorTarget = decoratorTarget;
}
/// <summary>
/// Gets the service being resolved.
/// </summary>
public Service Service { get; }
/// <summary>
/// Gets the component registration for the service being resolved.
/// </summary>
public IComponentRegistration Registration { get; }
/// <summary>
/// Gets the parameters used when resolving the service.
/// </summary>
public IEnumerable<Parameter> Parameters { get; }
/// <summary>
/// Gets the component registration for the decorator target if configured.
/// </summary>
public IComponentRegistration? DecoratorTarget { get; }
}
}
|
Set RenderProcessMessageHandler and LoadHandler to null on Dispose Reoder so they match the order in IWebBrowser so they're easier to compare | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using CefSharp.Internals;
namespace CefSharp
{
internal static class InternalWebBrowserExtensions
{
internal static void SetHandlersToNull(this IWebBrowserInternal browser)
{
browser.ResourceHandlerFactory = null;
browser.JsDialogHandler = null;
browser.DialogHandler = null;
browser.DownloadHandler = null;
browser.KeyboardHandler = null;
browser.LifeSpanHandler = null;
browser.MenuHandler = null;
browser.FocusHandler = null;
browser.RequestHandler = null;
browser.DragHandler = null;
browser.GeolocationHandler = null;
}
}
}
| // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using CefSharp.Internals;
namespace CefSharp
{
internal static class InternalWebBrowserExtensions
{
internal static void SetHandlersToNull(this IWebBrowserInternal browser)
{
browser.DialogHandler = null;
browser.RequestHandler = null;
browser.DisplayHandler = null;
browser.LoadHandler = null;
browser.LifeSpanHandler = null;
browser.KeyboardHandler = null;
browser.JsDialogHandler = null;
browser.DragHandler = null;
browser.DownloadHandler = null;
browser.MenuHandler = null;
browser.FocusHandler = null;
browser.ResourceHandlerFactory = null;
browser.GeolocationHandler = null;
browser.RenderProcessMessageHandler = null;
}
}
}
|
Fix revision number of support libraries to 0 | /*
Copyright 2015 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
// Attributes common to all assemblies.
[assembly: AssemblyCompany("Google Inc")]
[assembly: AssemblyCopyright("Copyright 2016 Google Inc")]
[assembly: AssemblyVersion("1.11.0.*")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| /*
Copyright 2015 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
// Attributes common to all assemblies.
[assembly: AssemblyCompany("Google Inc")]
[assembly: AssemblyCopyright("Copyright 2016 Google Inc")]
[assembly: AssemblyVersion("1.11.0.0")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
|
Stop filtering out stop words in package ids and titles. | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
namespace NuGetGallery
{
public class PerFieldAnalyzer : PerFieldAnalyzerWrapper
{
public PerFieldAnalyzer()
: base(new StandardAnalyzer(LuceneCommon.LuceneVersion), CreateFieldAnalyzers())
{
}
private static IDictionary CreateFieldAnalyzers()
{
return new Dictionary<string, Analyzer>(StringComparer.OrdinalIgnoreCase)
{
{ "Title", new TitleAnalyzer() }
};
}
class TitleAnalyzer : Analyzer
{
private readonly Analyzer innerAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion);
public override TokenStream TokenStream(string fieldName, TextReader reader)
{
// Split the title based on IdSeparators, then run it through the standardAnalyzer
string title = reader.ReadToEnd();
string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries));
return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized));
}
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
namespace NuGetGallery
{
public class PerFieldAnalyzer : PerFieldAnalyzerWrapper
{
public PerFieldAnalyzer()
: base(new StandardAnalyzer(LuceneCommon.LuceneVersion), CreateFieldAnalyzers())
{
}
private static IDictionary CreateFieldAnalyzers()
{
// For idAnalyzer we use the 'standard analyzer' but with no stop words (In, Of, The, etc are indexed).
var stopWords = new Hashtable();
StandardAnalyzer idAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion, stopWords);
return new Dictionary<string, Analyzer>(StringComparer.OrdinalIgnoreCase)
{
{ "Id", idAnalyzer },
{ "Title", new TitleAnalyzer() },
};
}
class TitleAnalyzer : Analyzer
{
private readonly StandardAnalyzer innerAnalyzer;
public TitleAnalyzer()
{
// For innerAnalyzer we use the 'standard analyzer' but with no stop words (In, Of, The, etc are indexed).
var stopWords = new Hashtable();
innerAnalyzer = new StandardAnalyzer(LuceneCommon.LuceneVersion, stopWords);
}
public override TokenStream TokenStream(string fieldName, TextReader reader)
{
// Split the title based on IdSeparators, then run it through the innerAnalyzer
string title = reader.ReadToEnd();
string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries));
return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized));
}
}
}
} |
Implement transform to tree for option as skeleton only | using slang.Lexing.Rules.Extensions;
using slang.Lexing.Trees.Nodes;
namespace slang.Lexing.Trees.Transformers
{
public static class OptionRuleExtensions
{
public static Node Transform (this Option rule, Node parent)
{
var option = rule.Value.Transform (parent);
return option;
}
}
}
| using slang.Lexing.Rules.Extensions;
using slang.Lexing.Trees.Nodes;
namespace slang.Lexing.Trees.Transformers
{
public static class OptionRuleExtensions
{
public static Tree Transform (this Option rule, Node parent)
{
return new Tree ();
}
}
}
|
Test that finds members with "admin" in username now works when there's more than one. | using NUnit.Framework;
namespace VersionOne.SDK.APIClient.Tests.QueryTests
{
[TestFixture]
public class QueryFindTester
{
private EnvironmentContext _context;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_context = new EnvironmentContext();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
_context = null;
}
[Test]
public void FindMemberTest()
{
var assetType = _context.MetaModel.GetAssetType("Member");
var query = new Query(assetType);
var nameAttribute = assetType.GetAttributeDefinition("Username");
query.Selection.Add(nameAttribute);
query.Find = new QueryFind("admin", new AttributeSelection("Username", assetType));
QueryResult result = _context.Services.Retrieve(query);
Assert.AreEqual(1, result.TotalAvaliable);
}
}
} | using NUnit.Framework;
namespace VersionOne.SDK.APIClient.Tests.QueryTests
{
[TestFixture]
public class QueryFindTester
{
private EnvironmentContext _context;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_context = new EnvironmentContext();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
_context = null;
}
[Test]
public void FindMemberTest()
{
var memberType = _context.MetaModel.GetAssetType("Member");
var memberQuery = new Query(memberType);
var userNameAttr = memberType.GetAttributeDefinition("Username");
memberQuery.Selection.Add(userNameAttr);
memberQuery.Find = new QueryFind("admin", new AttributeSelection("Username", memberType));
QueryResult result = _context.Services.Retrieve(memberQuery);
foreach (var member in result.Assets)
{
var name = member.GetAttribute(userNameAttr).Value as string;
Assert.IsNotNullOrEmpty(name);
if (name != null) Assert.That(name.IndexOf("admin") > -1);
}
}
}
} |
Mark field as const instead of static readonly | using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Pingy.Common;
namespace Pingy.Gui
{
public partial class App : Application
{
private readonly static string defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private readonly static string defaultFileName = "Pingy.txt";
private readonly static string defaultFilePath = Path.Combine(defaultDirectory, defaultFileName);
public App()
: this(defaultFilePath)
{ }
public App(string path)
{
if (String.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
InitializeComponent();
MainWindowViewModel viewModel = new MainWindowViewModel(path);
MainWindow = new MainWindow(viewModel);
MainWindow.Show();
}
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (e.Exception is Exception ex)
{
Log.Exception(ex, true);
}
else
{
Log.Message("an empty unhandled exception occurred");
}
}
}
}
| using System;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Pingy.Common;
namespace Pingy.Gui
{
public partial class App : Application
{
private static readonly string defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private const string defaultFileName = "Pingy.txt";
private readonly static string defaultFilePath = Path.Combine(defaultDirectory, defaultFileName);
public App()
: this(defaultFilePath)
{ }
public App(string path)
{
if (String.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
InitializeComponent();
MainWindowViewModel viewModel = new MainWindowViewModel(path);
MainWindow = new MainWindow(viewModel);
MainWindow.Show();
}
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (e.Exception is Exception ex)
{
Log.Exception(ex, true);
}
else
{
Log.Message("an empty unhandled exception occurred");
}
}
}
}
|
Reposition taiko playfield to be closer to the top of the screen | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Taiko.UI
{
public class TaikoPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
private const float default_relative_height = TaikoPlayfield.DEFAULT_HEIGHT / 768;
private const float default_aspect = 16f / 9f;
public TaikoPlayfieldAdjustmentContainer()
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
}
protected override void Update()
{
base.Update();
float aspectAdjust = Math.Clamp(Parent.ChildSize.X / Parent.ChildSize.Y, 0.4f, 4) / default_aspect;
Size = new Vector2(1, default_relative_height * aspectAdjust);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Taiko.UI
{
public class TaikoPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
private const float default_relative_height = TaikoPlayfield.DEFAULT_HEIGHT / 768;
private const float default_aspect = 16f / 9f;
protected override void Update()
{
base.Update();
float aspectAdjust = Math.Clamp(Parent.ChildSize.X / Parent.ChildSize.Y, 0.4f, 4) / default_aspect;
Size = new Vector2(1, default_relative_height * aspectAdjust);
// Position the taiko playfield exactly one playfield from the top of the screen.
RelativePositionAxes = Axes.Y;
Y = Size.Y;
}
}
}
|
Make the green slightly darker, so that the text is readable. | namespace NuGetPackageVisualizer
{
public class DgmlColorConfiguration : IColorConfiguration
{
public string VersionMismatchPackageColor
{
get { return "#FF0000"; }
}
public string PackageHasDifferentVersionsColor
{
get { return "#FCE428"; }
}
public string DefaultColor
{
get { return "#15FF00"; }
}
}
} | namespace NuGetPackageVisualizer
{
public class DgmlColorConfiguration : IColorConfiguration
{
public string VersionMismatchPackageColor
{
get { return "#FF0000"; }
}
public string PackageHasDifferentVersionsColor
{
get { return "#FCE428"; }
}
public string DefaultColor
{
get { return "#339933"; }
}
}
} |
Disable logging so the performance profiling is more accurate. | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
namespace Slp.Evi.Test.System.Sparql
{
public abstract class SparqlFixture
{
private readonly ConcurrentDictionary<string, EviQueryableStorage> _storages = new ConcurrentDictionary<string, EviQueryableStorage>();
private IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
if (Environment.GetEnvironmentVariable("APPVEYOR") != "True")
{
loggerFactory.AddConsole(LogLevel.Trace);
}
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
public EviQueryableStorage GetStorage(string storageName)
{
return _storages.GetOrAdd(storageName, CreateStorage);
}
private EviQueryableStorage CreateStorage(string storageName)
{
return SparqlTestHelpers.InitializeDataset(storageName, GetSqlDb(), GetStorageFactory());
}
protected abstract ISqlDatabase GetSqlDb();
}
} | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
namespace Slp.Evi.Test.System.Sparql
{
public abstract class SparqlFixture
{
private readonly ConcurrentDictionary<string, EviQueryableStorage> _storages = new ConcurrentDictionary<string, EviQueryableStorage>();
private IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
//if (Environment.GetEnvironmentVariable("APPVEYOR") != "True")
//{
// loggerFactory.AddConsole(LogLevel.Trace);
//}
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
public EviQueryableStorage GetStorage(string storageName)
{
return _storages.GetOrAdd(storageName, CreateStorage);
}
private EviQueryableStorage CreateStorage(string storageName)
{
return SparqlTestHelpers.InitializeDataset(storageName, GetSqlDb(), GetStorageFactory());
}
protected abstract ISqlDatabase GetSqlDb();
}
} |
Test can get by LINQ statement | using LazyLibrary.Storage;
using LazyLibrary.Storage.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace LazyLibrary.Tests.Storage.Memory
{
[TestClass]
public class MemoryRepositoryTests
{
[TestMethod]
public void CanAdd()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsTrue(repo.Get().Any(), "The object could not be added to the repository");
}
[TestMethod]
public void CanGetById()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsNotNull(repo.GetById(1), "The object could not be retrieved from the repository");
}
}
} | using LazyLibrary.Storage;
using LazyLibrary.Storage.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace LazyLibrary.Tests.Storage.Memory
{
[TestClass]
public class MemoryRepositoryTests
{
[TestMethod]
public void CanAdd()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsTrue(repo.Get().Any(), "The object could not be added to the repository");
}
[TestMethod]
public void CanGetById()
{
var repo = new MemoryRepository<TestObject>();
var obj = new TestObject();
repo.Upsert(obj);
Assert.IsNotNull(repo.GetById(1), "The object could not be retrieved from the repository");
}
[TestMethod]
public void CanGetByLINQ()
{
var repo = new MemoryRepository<TestObject>();
var objOne = new TestObject() { Name = "one" };
var objTwo = new TestObject() { Name = "two" };
repo.Upsert(objOne);
repo.Upsert(objTwo);
var result = repo.Get(x => x.Name == "one").SingleOrDefault();
Assert.IsNotNull(result, "The object could not be retrieved from the repository");
Assert.IsTrue(result.Equals(objOne), "The object could not be retrieved from the repository");
}
}
} |
Add test explicitly checking recursion | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Api
{
[TestFixture]
public class NUnitIssue52
{
class SelfContainer : IEnumerable
{
public IEnumerator GetEnumerator() { yield return this; }
}
[Test]
public void SelfContainedItemFoundInArray()
{
var item = new SelfContainer();
var items = new SelfContainer[] { new SelfContainer(), item };
// work around
//Assert.True(((ICollection<SelfContainer>)items).Contains(item));
// causes StackOverflowException
//Assert.Contains(item, items);
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
var equal = equalityComparer.AreEqual(item, items, ref tolerance);
Assert.IsFalse(equal);
//Console.WriteLine("test completed");
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Api
{
[TestFixture]
public class NUnitIssue52
{
[TestCaseSource(nameof(GetTestCases))]
public void SelfContainedItemFoundInCollection<T>(T x, ICollection y)
{
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
var actualResult = equalityComparer.AreEqual(x, y, ref tolerance);
Assert.IsFalse(actualResult);
Assert.Contains(x, y);
}
[TestCaseSource(nameof(GetTestCases))]
public void SelfContainedItemDoesntRecurseForever<T>(T x, ICollection y)
{
var equalityComparer = new NUnitEqualityComparer();
var tolerance = Tolerance.Default;
equalityComparer.ExternalComparers.Add(new DetectRecursionComparer(30));
Assert.DoesNotThrow(() =>
{
var equality = equalityComparer.AreEqual(x, y, ref tolerance);
Assert.IsFalse(equality);
Assert.Contains(x, y);
});
}
public static IEnumerable<TestCaseData> GetTestCases()
{
var item = new SelfContainer();
var items = new SelfContainer[] { new SelfContainer(), item };
yield return new TestCaseData(item, items);
}
private class DetectRecursionComparer : EqualityAdapter
{
private readonly int maxRecursion;
[MethodImpl(MethodImplOptions.NoInlining)]
public DetectRecursionComparer(int maxRecursion)
{
var callerDepth = new StackTrace().FrameCount - 1;
this.maxRecursion = callerDepth + maxRecursion;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override bool CanCompare(object x, object y)
{
var currentDepth = new StackTrace().FrameCount - 1;
return currentDepth >= maxRecursion;
}
public override bool AreEqual(object x, object y)
{
throw new InvalidOperationException("Recurses");
}
}
private class SelfContainer : IEnumerable
{
public IEnumerator GetEnumerator() { yield return this; }
}
}
}
|
Add docs re wrapped stream ownership |
namespace Serilog
{
using System.IO;
/// <summary>
/// Enables hooking into log file lifecycle events
/// </summary>
public abstract class FileLifecycleHooks
{
/// <summary>
/// Wraps <paramref name="sourceStream"/> in another stream, such as a GZipStream, then returns the wrapped stream
/// </summary>
/// <param name="sourceStream">The source log file stream</param>
/// <returns>The wrapped stream</returns>
public abstract Stream Wrap(Stream sourceStream);
}
}
|
namespace Serilog
{
using System.IO;
/// <summary>
/// Enables hooking into log file lifecycle events
/// </summary>
public abstract class FileLifecycleHooks
{
/// <summary>
/// Wraps <paramref name="underlyingStream"/> in another stream, such as a GZipStream, then returns the wrapped stream
/// </summary>
/// <remarks>
/// Serilog is responsible for disposing of the wrapped stream
/// </remarks>
/// <param name="underlyingStream">The underlying log file stream</param>
/// <returns>The wrapped stream</returns>
public abstract Stream Wrap(Stream underlyingStream);
}
}
|
Raise authentication server prerelease version number. | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Affecto Authentication Server")]
[assembly: AssemblyProduct("Affecto Authentication Server")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0-prerelease01")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")] | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Affecto Authentication Server")]
[assembly: AssemblyProduct("Affecto Authentication Server")]
[assembly: AssemblyCompany("Affecto")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0-prerelease02")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Tests")]
[assembly: InternalsVisibleTo("Affecto.AuthenticationServer.Configuration.Tests")] |
Move settings menu to the "Edit" category | /*
* 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 Borodar.RainbowFolders.Editor.Settings;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor
{
public static class RainbowFoldersMenu
{
[MenuItem("Rainbow Folders/Show Settings")]
public static void OpenSettings()
{
var settings = RainbowFoldersSettings.Load();
Selection.activeObject = settings;
}
}
} | /*
* 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 Borodar.RainbowFolders.Editor.Settings;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor
{
public static class RainbowFoldersMenu
{
[MenuItem("Edit/Rainbow Folders Settings", false, 500)]
public static void OpenSettings()
{
var settings = RainbowFoldersSettings.Load();
Selection.activeObject = settings;
}
}
} |
Refactor notification object and add methods for static property changed event | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Common
{
public abstract class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetPropertyValue<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return;
storage = value;
RaisePropertyChanged(propertyName);
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression is null)
throw new ArgumentNullException(nameof(propertyExpression));
if (!(propertyExpression.Body is MemberExpression memberExpression))
throw new ArgumentException("The expression is not a member access expression.", nameof(propertyExpression));
RaisePropertyChanged(memberExpression.Member.Name);
}
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace SnowyImageCopy.Common
{
public abstract class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetPropertyValue<T>(ref T storage, in T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected static bool SetPropertyValue<T>(ref T storage, in T value, EventHandler<PropertyChangedEventArgs> handler, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
RaisePropertyChanged(handler, propertyName);
return true;
}
protected static void RaisePropertyChanged(EventHandler<PropertyChangedEventArgs> handler, [CallerMemberName] string propertyName = null) =>
handler?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
} |
Allow multiple files on the command line. | // -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
using System.IO;
using Weave.Compiler;
using Weave.Parser;
internal class Program
{
private static void Main(string[] args)
{
var input = File.ReadAllText(args[0]);
var parser = new WeaveParser();
var parsed = parser.Parse(input);
var output = WeaveCompiler.Compile(parsed);
File.WriteAllText(args[0] + ".cs", output.Code);
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
using System.IO;
using Weave.Compiler;
using Weave.Parser;
internal class Program
{
private static void Main(string[] args)
{
foreach (var arg in args)
{
var input = File.ReadAllText(arg);
var parser = new WeaveParser();
var parsed = parser.Parse(input, arg);
var output = WeaveCompiler.Compile(parsed);
File.WriteAllText(arg + ".cs", output.Code);
}
}
}
}
|
Make var name more descriptive | using UnityEngine;
using System.Collections;
using ArabicSupport;
public class FixArabic3DText : MonoBehaviour {
public bool showTashkeel = true;
public bool useHinduNumbers = true;
// Use this for initialization
void Start () {
TextMesh textMesh = gameObject.GetComponent<TextMesh>();
string fixedFixed = ArabicFixer.Fix(textMesh.text, showTashkeel, useHinduNumbers);
gameObject.GetComponent<TextMesh>().text = fixedFixed;
Debug.Log(fixedFixed);
}
}
| using UnityEngine;
using System.Collections;
using ArabicSupport;
public class FixArabic3DText : MonoBehaviour {
public bool showTashkeel = true;
public bool useHinduNumbers = true;
// Use this for initialization
void Start () {
TextMesh textMesh = gameObject.GetComponent<TextMesh>();
string fixedText = ArabicFixer.Fix(textMesh.text, showTashkeel, useHinduNumbers);
gameObject.GetComponent<TextMesh>().text = fixedText;
Debug.Log(fixedFixed);
}
}
|
Rename file to .css for new stream | using PvcCore;
using System.Collections.Generic;
using System.IO;
namespace PvcPlugins
{
public class PvcLess : PvcPlugin
{
public override string[] SupportedTags
{
get
{
return new string[] { ".less" };
}
}
public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
{
var lessEngine = new dotless.Core.LessEngine();
var resultStreams = new List<PvcStream>();
foreach (var inputStream in inputStreams)
{
var lessContent = inputStream.ToString();
var cssContent = lessEngine.TransformToCss(lessContent, "");
var resultStream = PvcUtil.StringToStream(cssContent, inputStream.StreamName);
resultStreams.Add(resultStream);
}
return resultStreams;
}
}
}
| using PvcCore;
using System.Collections.Generic;
using System.IO;
namespace PvcPlugins
{
public class PvcLess : PvcPlugin
{
public override string[] SupportedTags
{
get
{
return new string[] { ".less" };
}
}
public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams)
{
var lessEngine = new dotless.Core.LessEngine();
var resultStreams = new List<PvcStream>();
foreach (var inputStream in inputStreams)
{
var lessContent = inputStream.ToString();
var cssContent = lessEngine.TransformToCss(lessContent, "");
var newStreamName = Path.Combine(Path.GetDirectoryName(inputStream.StreamName), Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".css");
var resultStream = PvcUtil.StringToStream(cssContent, newStreamName);
resultStreams.Add(resultStream);
}
return resultStreams;
}
}
}
|
Replace reflection to call API. | using System.Linq;
using System.Reflection;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
if (obj.GetType().Namespace != "Castle.Proxies")
{
return obj;
}
var targetField = obj.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.FirstOrDefault(f => f.Name == "__target");
if (targetField == null)
{
return obj;
}
return targetField.GetValue(obj);
}
}
}
| using Castle.DynamicProxy;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
return ProxyUtil.GetUnproxiedInstance(obj);
}
}
}
|
Change the default font for the header. | using System;
using System.Drawing;
namespace DrawIt
{
public static class FontHelpers
{
public static Font GetHeaderFont()
{
float fontSize = Configuration.GetSettingOrDefault<float>(Constants.Application.Header.FontSize, float.TryParse, Constants.Application.Defaults.HeaderTextSize);
string fontName = Configuration.GetSetting(Constants.Application.Header.FontName) ?? "Calibri";
FontStyle fontStyle = Configuration.GetSettingOrDefault<FontStyle>(Constants.Application.Header.FontStyle, Enum.TryParse<FontStyle>, FontStyle.Regular);
return new Font(fontName, fontSize, fontStyle);
}
}
}
| using System;
using System.Drawing;
namespace DrawIt
{
public static class FontHelpers
{
public static Font GetHeaderFont()
{
float fontSize = Configuration.GetSettingOrDefault<float>(Constants.Application.Header.FontSize, float.TryParse, Constants.Application.Defaults.HeaderTextSize);
string fontName = Configuration.GetSetting(Constants.Application.Header.FontName) ?? "Segoe Script";
FontStyle fontStyle = Configuration.GetSettingOrDefault<FontStyle>(Constants.Application.Header.FontStyle, Enum.TryParse<FontStyle>, FontStyle.Regular);
return new Font(fontName, fontSize, fontStyle);
}
}
}
|
Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using Giles.Core.Utility;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
if (filters.Count() == 0)
remoteTestRunner.Run(listener);
else
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
} |
Use name only for reporting missing file | using System.Collections.Generic;
using System.Linq;
namespace Arkivverket.Arkade.Core.Base
{
public class ArchiveXmlUnit
{
public ArchiveXmlFile File { get; }
public List<ArchiveXmlSchema> Schemas { get; }
public ArchiveXmlUnit(ArchiveXmlFile file, List<ArchiveXmlSchema> schemas)
{
File = file;
Schemas = schemas;
}
public ArchiveXmlUnit(ArchiveXmlFile file, ArchiveXmlSchema schema)
: this(file, new List<ArchiveXmlSchema> {schema})
{
}
public bool AllFilesExists()
{
return !GetMissingFiles().Any();
}
public IEnumerable<string> GetMissingFiles()
{
var missingFiles = new List<string>();
if (!File.Exists)
missingFiles.Add(File.FullName);
missingFiles.AddRange(
from schema in
from schema in Schemas
where schema.IsUserProvided()
select (UserProvidedXmlSchema) schema
where !schema.FileExists
select schema.FullName
);
return missingFiles;
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Arkivverket.Arkade.Core.Base
{
public class ArchiveXmlUnit
{
public ArchiveXmlFile File { get; }
public List<ArchiveXmlSchema> Schemas { get; }
public ArchiveXmlUnit(ArchiveXmlFile file, List<ArchiveXmlSchema> schemas)
{
File = file;
Schemas = schemas;
}
public ArchiveXmlUnit(ArchiveXmlFile file, ArchiveXmlSchema schema)
: this(file, new List<ArchiveXmlSchema> {schema})
{
}
public bool AllFilesExists()
{
return !GetMissingFiles().Any();
}
public IEnumerable<string> GetMissingFiles()
{
var missingFiles = new List<string>();
if (!File.Exists)
missingFiles.Add(File.Name);
missingFiles.AddRange(
from schema in
from schema in Schemas
where schema.IsUserProvided()
select (UserProvidedXmlSchema) schema
where !schema.FileExists
select schema.FullName
);
return missingFiles;
}
}
}
|
Tweak for .net Standard 1.1 compatibility | using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utils.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of a field in an enumeration. If there is no
/// description attribute, the raw name of the field is provided.
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
}
| using System;
using System.ComponentModel;
using System.Reflection;
namespace MarkEmbling.Utils.Extensions {
public static class EnumExtensions {
/// <summary>
/// Gets the description of a field in an enumeration. If there is no
/// description attribute, the raw name of the field is provided.
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>Description or raw name</returns>
public static string GetDescription(this Enum value) {
var field = value.GetType().GetRuntimeField(value.ToString());
var attribute = field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
}
|
Test receive and send message | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vikekh.Stepbot
{
class Program
{
static void Main(string[] args)
{
}
}
}
| using SlackAPI;
using System;
using System.Threading;
namespace Vikekh.Stepbot
{
class Program
{
static void Main(string[] args)
{
var botAuthToken = "";
var userAuthToken = "";
var name = "@stepdot";
var age = (new DateTime(2017, 1, 18) - DateTime.Now).Days / 365.0;
var ageString = age.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
var version = "0.1.0";
var mommy = "@vem";
ManualResetEventSlim clientReady = new ManualResetEventSlim(false);
SlackSocketClient client = new SlackSocketClient(botAuthToken);
client.Connect((connected) =>
{
// This is called once the client has emitted the RTM start command
clientReady.Set();
}, () =>
{
// This is called once the RTM client has connected to the end point
});
client.OnMessageReceived += (message) =>
{
// Handle each message as you receive them
Console.WriteLine(message.text);
var textData = string.Format("hello w0rld my name is {0} I am {1} years old and my version is {2} and my mommy is {3}", name, ageString, version, mommy);
client.SendMessage((x) => { }, message.channel, textData);
};
clientReady.Wait();
Console.ReadLine();
}
}
}
|
Add additional functional test cases. | using System;
using System.Collections.Generic;
using TimeSeries;
using TimeSeriesService.Client.TimeSeriesReference;
namespace TimeSeriesService.Client
{
class Program
{
static void Main()
{
var proxy = new TimeSeriesServiceClient();
var oneDataPoint = new List<DataPoint>
{
new DataPoint()
}.ToArray();
var oneDataPointResult = proxy.New(oneDataPoint);
Console.WriteLine("Irregular: {0}", oneDataPointResult);
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using TimeSeries;
using TimeSeriesService.Client.TimeSeriesReference;
namespace TimeSeriesService.Client
{
class Program
{
static void Main()
{
var proxy = new TimeSeriesServiceClient();
var oneDataPoint = new List<DataPoint>
{
new DataPoint()
}.ToArray();
var oneDataPointResult = proxy.New(oneDataPoint);
Console.WriteLine("One data point: {0}", oneDataPointResult);
var twoDataPoints = new List<DataPoint>
{
new DataPoint(),
new DataPoint()
}.ToArray();
var twoDataPointsResult = proxy.New(twoDataPoints);
Console.WriteLine("Two data points: {0}", twoDataPointsResult);
var threeDataPoints = new List<DataPoint>
{
new DataPoint(),
new DataPoint(),
new DataPoint()
}.ToArray();
var threeDataPointsResult = proxy.New(threeDataPoints);
Console.WriteLine("Three data points: {0}",
threeDataPointsResult);
Console.WriteLine();
Console.WriteLine("--");
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
|
Remove redundant LINQ method call | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.Core.EntityFramework
{
public class ScopeStore : IScopeStore
{
private readonly string _connectionString;
public ScopeStore(string connectionString)
{
_connectionString = connectionString;
}
public Task<IEnumerable<Models.Scope>> GetScopesAsync()
{
using (var db = new CoreDbContext(_connectionString))
{
var scopes = db.Scopes
.Include("ScopeClaims")
.ToArray();
var models = scopes.ToList().Select(x => x.ToModel());
return Task.FromResult(models);
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.Core.EntityFramework
{
public class ScopeStore : IScopeStore
{
private readonly string _connectionString;
public ScopeStore(string connectionString)
{
_connectionString = connectionString;
}
public Task<IEnumerable<Models.Scope>> GetScopesAsync()
{
using (var db = new CoreDbContext(_connectionString))
{
var scopes = db.Scopes
.Include("ScopeClaims");
var models = scopes.ToList().Select(x => x.ToModel());
return Task.FromResult(models);
}
}
}
}
|
Fix small offset in low quality minimap image | namespace Mappy.Util.ImageSampling
{
using System.Drawing;
public class NearestNeighbourWrapper : IPixelImage
{
private readonly IPixelImage source;
public NearestNeighbourWrapper(IPixelImage source, int width, int height)
{
this.source = source;
this.Width = width;
this.Height = height;
}
public int Width { get; private set; }
public int Height { get; private set; }
public Color this[int x, int y]
{
get
{
int imageX = (int)((x / (float)this.Width) * this.source.Width);
int imageY = (int)((y / (float)this.Height) * this.source.Height);
return this.source[imageX, imageY];
}
}
}
}
| namespace Mappy.Util.ImageSampling
{
using System.Drawing;
public class NearestNeighbourWrapper : IPixelImage
{
private readonly IPixelImage source;
public NearestNeighbourWrapper(IPixelImage source, int width, int height)
{
this.source = source;
this.Width = width;
this.Height = height;
}
public int Width { get; private set; }
public int Height { get; private set; }
public Color this[int x, int y]
{
get
{
// sample at the centre of each pixel
float ax = x + 0.5f;
float ay = y + 0.5f;
int imageX = (int)((ax / this.Width) * this.source.Width);
int imageY = (int)((ay / this.Height) * this.source.Height);
return this.source[imageX, imageY];
}
}
}
}
|
Fix stress test not creating v2 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NiceIO;
using NUnit.Framework;
using SaferMutex.Tests.BaseSuites;
namespace SaferMutex.Tests.FileBased
{
[TestFixture]
public class ThreadedStressTestsV2 : BaseThreadedStressTests
{
protected override ISaferMutexMutex CreateMutexImplementation(bool initiallyOwned, string name, out bool owned, out bool createdNew)
{
return new SaferMutex.FileBased(initiallyOwned, name, Scope.CurrentProcess, out owned, out createdNew, _tempDirectory.ToString());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NiceIO;
using NUnit.Framework;
using SaferMutex.Tests.BaseSuites;
namespace SaferMutex.Tests.FileBased
{
[TestFixture]
public class ThreadedStressTestsV2 : BaseThreadedStressTests
{
protected override ISaferMutexMutex CreateMutexImplementation(bool initiallyOwned, string name, out bool owned, out bool createdNew)
{
return new SaferMutex.FileBased2(initiallyOwned, name, Scope.CurrentProcess, out owned, out createdNew, _tempDirectory.ToString());
}
}
}
|
Change ApiKey to AppId add RequireApiAuthToken | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hanc.AspNetAPI
{
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and ValuesController.cs for implimentation code
/// </summary>
public class SecretOptions
{
public SecretOptions()
{
MacSecret = "default_secret";
}
public string MacSecret { get; set; }
public string ApiKey { get; set; }
}
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and HelloController.cs for implimentation code
/// </summary>
public class HelloOptions
{
public HelloOptions()
{
HelloValue = "...";
}
public string HelloValue { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hanc.AspNetAPI
{
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and ValuesController.cs for implimentation code
/// </summary>
public class SecretOptions
{
public SecretOptions()
{
MacSecret = "default_secret";
}
public string MacSecret { get; set; }
public string AppId { get; set; }
public bool RequireApiAuthToken { get; set; }
}
/// <summary>
/// The options pattern uses custom options classes to represent a group of related settings.
/// See Startup.cs and HelloController.cs for implimentation code
/// </summary>
public class HelloOptions
{
public HelloOptions()
{
HelloValue = "...";
}
public string HelloValue { get; set; }
}
}
|
Make the designer work in the sandbox project. | using Avalonia;
namespace Sandbox
{
public class Program
{
static void Main(string[] args)
{
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.StartWithClassicDesktopLifetime(args);
}
}
}
| using Avalonia;
namespace Sandbox
{
public class Program
{
static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
}
|
Add GET All Names endpoint | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using DataReader.BusinessLogic;
using DataReader.Models;
namespace DataReader.Controllers
{
[RoutePrefix("api")]
public class NameQueryController : ApiController
{
private readonly INameBusinessLogic _nameBusinessLogic;
public NameQueryController(INameBusinessLogic nameBusinessLogic)
{
_nameBusinessLogic = nameBusinessLogic;
}
[Route("fullName/{id}")]
[HttpGet]
public async Task<IHttpActionResult> GetData(string id)
{
var result = default(NameDTO);
try
{
result = _nameBusinessLogic.GetById(id);
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using DataReader.BusinessLogic;
using DataReader.Models;
namespace DataReader.Controllers
{
[RoutePrefix("api")]
public class NameQueryController : ApiController
{
private readonly INameBusinessLogic _nameBusinessLogic;
public NameQueryController(INameBusinessLogic nameBusinessLogic)
{
_nameBusinessLogic = nameBusinessLogic;
}
[Route("fullName/{id}")]
[HttpGet]
public IHttpActionResult GetName(string id)
{
var result = default(NameDTO);
try
{
result = _nameBusinessLogic.GetById(id);
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
[Route("fullName")]
[HttpGet]
public IHttpActionResult GetAllNames()
{
var result = default(string[]);
try
{
result = _nameBusinessLogic.GetAllNameIds();
}
catch (Exception ex)
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
return Ok(result);
}
}
} |
Add TODO on fake CallNumber | using System;
using System.Linq;
using Microsoft.Practices.ObjectBuilder2;
namespace SignInCheckIn.Models.DTO
{
public class ParticipantDto
{
public int EventParticipantId { get; set; }
public int ParticipantId { get; set; }
public int ContactId { get; set; }
public int HouseholdId { get; set; }
public int HouseholdPositionId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public bool Selected { get; set; } = false;
public int ParticipationStatusId { get; set; }
public int? AssignedRoomId { get; set; }
public string AssignedRoomName { get; set; }
public int? AssignedSecondaryRoomId { get; set; } // adventure club field
public string AssignedSecondaryRoomName { get; set; } // adventure club field
public string CallNumber
{
get
{
var c = $"0000{EventParticipantId}";
return c.Substring(c.Length - 4);
}
}
}
} | using System;
using System.Linq;
using Microsoft.Practices.ObjectBuilder2;
namespace SignInCheckIn.Models.DTO
{
public class ParticipantDto
{
public int EventParticipantId { get; set; }
public int ParticipantId { get; set; }
public int ContactId { get; set; }
public int HouseholdId { get; set; }
public int HouseholdPositionId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public bool Selected { get; set; } = false;
public int ParticipationStatusId { get; set; }
public int? AssignedRoomId { get; set; }
public string AssignedRoomName { get; set; }
public int? AssignedSecondaryRoomId { get; set; } // adventure club field
public string AssignedSecondaryRoomName { get; set; } // adventure club field
public string CallNumber
{
// TODO Faking out a call number for now (last 4 of EventParticipantId), eventually need to store a real call number on Event Participant
get
{
var c = $"0000{EventParticipantId}";
return c.Substring(c.Length - 4);
}
}
}
} |
Improve TCP reading code to read more than 4096 bytes if available | using MultiMiner.Xgminer.Api.Parsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public class ApiContext
{
private TcpClient tcpClient;
public ApiContext(int port)
{
tcpClient = new TcpClient("127.0.0.1", port);
}
public List<DeviceInformation> GetDeviceInformation()
{
string textResponse = GetResponse(ApiVerb.Devs);
List<DeviceInformation> result = new List<DeviceInformation>();
DeviceInformationParser.ParseTextForDeviceInformation(textResponse, result);
return result;
}
public void QuitMining()
{
GetResponse(ApiVerb.Quit);
}
private string GetResponse(string apiVerb)
{
NetworkStream stream = tcpClient.GetStream();
Byte[] request = System.Text.Encoding.ASCII.GetBytes(apiVerb);
stream.Write(request, 0, request.Length);
Byte[] responseBuffer = new Byte[4096];
string response = string.Empty;
int bytesRead = stream.Read(responseBuffer, 0, responseBuffer.Length);
response = System.Text.Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
return response;
}
}
}
| using MultiMiner.Xgminer.Api.Parsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public class ApiContext
{
private TcpClient tcpClient;
public ApiContext(int port)
{
tcpClient = new TcpClient("127.0.0.1", port);
}
public List<DeviceInformation> GetDeviceInformation()
{
string textResponse = GetResponse(ApiVerb.Devs);
List<DeviceInformation> result = new List<DeviceInformation>();
DeviceInformationParser.ParseTextForDeviceInformation(textResponse, result);
return result;
}
public void QuitMining()
{
GetResponse(ApiVerb.Quit);
}
private string GetResponse(string apiVerb)
{
NetworkStream tcpStream = tcpClient.GetStream();
Byte[] request = Encoding.ASCII.GetBytes(apiVerb);
tcpStream.Write(request, 0, request.Length);
Byte[] responseBuffer = new Byte[4096];
string response = string.Empty;
do
{
int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length);
response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
} while (tcpStream.DataAvailable);
return response;
}
}
}
|
Add Rotate methods contributed by CLA signers | namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
}
| using Mapsui.Utilities;
namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="centerX">X coordinate of point about which to rotate</param>
/// <param name="centerY">Y coordinate of point about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, double centerX, double centerY)
{
// translate this point back to the center
var newX = X - centerX;
var newY = Y - centerY;
// rotate the values
var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees);
// translate back to original reference frame
newX = p.X + centerX;
newY = p.Y + centerY;
return new MPoint(newX, newY);
}
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="center">MPoint about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, MPoint center)
{
return Rotate(degrees, center.X, center.Y);
}
}
|
Update the version number to 1.4.0 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Version.cs" company="">
// Copyright 2013 Thomas PIERRAIN
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
// 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.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")] | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Version.cs" company="">
// Copyright 2013 Thomas PIERRAIN
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
// 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.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")] |
Check background job worker before using that in jobs info controller | using System;
using System.Threading;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using Bit.Model.Dtos;
namespace Bit.OData.ODataControllers
{
public class JobsInfoController : DtoController<JobInfoDto>
{
public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; }
[Get]
public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken);
return new JobInfoDto
{
Id = jobInfo.Id,
CreatedAt = jobInfo.CreatedAt,
State = jobInfo.State
};
}
}
}
| using Bit.Core.Contracts;
using Bit.Core.Models;
using Bit.Model.Dtos;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Bit.OData.ODataControllers
{
public class JobsInfoController : DtoController<JobInfoDto>
{
public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; }
[Get]
public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (BackgroundJobWorker == null)
throw new InvalidOperationException("No background job worker is configured");
JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken);
return new JobInfoDto
{
Id = jobInfo.Id,
CreatedAt = jobInfo.CreatedAt,
State = jobInfo.State
};
}
}
}
|
Add xml comment on namespace. | using System.Windows;
namespace Kinugasa.UI
{
/// <summary>
/// Proxy class for binding sorce.
/// </summary>
public class BindingProxy : Freezable
{
/// <summary>
/// Define dependencyProperty.
/// </summary>
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
/// <summary>
/// Create freezable object's instance.
/// </summary>
/// <returns></returns>
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
/// <summary>
/// Proxy property.
/// </summary>
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
}
}
| using System.Windows;
/// <summary>
/// Provide userinterface components.
/// </summary>
namespace Kinugasa.UI
{
/// <summary>
/// Proxy class for binding sorce.
/// </summary>
public class BindingProxy : Freezable
{
/// <summary>
/// Define dependencyProperty.
/// </summary>
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
/// <summary>
/// Create freezable object's instance.
/// </summary>
/// <returns></returns>
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
/// <summary>
/// Proxy property.
/// </summary>
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
}
}
|
Check IsTogglePatternAvailable insted of using ControlType | namespace Winium.Desktop.Driver.CommandExecutors
{
#region using
using System.Windows.Automation;
using Winium.Cruciatus.Extensions;
using Winium.StoreApps.Common;
#endregion
internal class IsElementSelectedExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
var controlType = element.GetAutomationPropertyValue<ControlType>(AutomationElement.ControlTypeProperty);
if (controlType.Equals(ControlType.CheckBox))
{
return this.JsonResponse(ResponseStatus.Success, element.ToCheckBox().IsToggleOn);
}
var property = SelectionItemPattern.IsSelectedProperty;
var isSelected = element.GetAutomationPropertyValue<bool>(property);
return this.JsonResponse(ResponseStatus.Success, isSelected);
}
#endregion
}
}
| namespace Winium.Desktop.Driver.CommandExecutors
{
#region using
using System.Windows.Automation;
using Winium.Cruciatus.Exceptions;
using Winium.Cruciatus.Extensions;
using Winium.StoreApps.Common;
#endregion
internal class IsElementSelectedExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
var isSelected = false;
try
{
var isTogglePattrenAvailable =
element.GetAutomationPropertyValue<bool>(AutomationElement.IsTogglePatternAvailableProperty);
if (isTogglePattrenAvailable)
{
var toggleStateProperty = TogglePattern.ToggleStateProperty;
var toggleState = element.GetAutomationPropertyValue<ToggleState>(toggleStateProperty);
isSelected = toggleState == ToggleState.On;
}
}
catch (CruciatusException)
{
var selectionItemProperty = SelectionItemPattern.IsSelectedProperty;
isSelected = element.GetAutomationPropertyValue<bool>(selectionItemProperty);
}
return this.JsonResponse(ResponseStatus.Success, isSelected);
}
#endregion
}
}
|
Update AssemblyInfo to reference Couchbase as owner / copyright | using System.Runtime.InteropServices;
using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("MeepMeep (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("MeepMeep (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .Net client.")]
[assembly: AssemblyCompany("Daniel Wertheim")]
[assembly: AssemblyCopyright("Copyright © 2013 Daniel Wertheim")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.1.0.*")]
[assembly: AssemblyFileVersion("0.1.0")]
| using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("MeepMeep (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("MeepMeep (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .NET client.")]
[assembly: AssemblyCompany("Couchbase")]
[assembly: AssemblyCopyright("Copyright © 2017 Couchbase")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.1.0.*")]
[assembly: AssemblyFileVersion("0.1.0")]
|
Update catalog list item style | @model List<Catalog>
<div class="am-panel-hd">Catalog</div>
<div class="am-panel-bd">
@foreach (var catalog in Model)
{
<a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url">
@catalog.Title
<span class="am-badge am-badge-secondary am-round">@catalog.Posts.Count()</span>
</a>
}
</div> | @model List<Catalog>
<div class="am-panel-hd">Catalog</div>
<div class="am-panel-bd">
@foreach (var catalog in Model)
{
<a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url">
@catalog.Title
<span class="am-badge am-badge-success am-round">@catalog.Posts.Count()</span>
</a>
}
</div> |
Return whether the target has any dispellable debuff | using Buddy.Swtor.Objects;
namespace DefaultCombat.Extensions
{
public static class TorCharacterExtensions
{
public static bool ShouldDispel(this TorCharacter target, string debuffName)
{
if (target == null)
return false;
return target.HasDebuff(debuffName);
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Buddy.Swtor.Objects;
namespace DefaultCombat.Extensions
{
public static class TorCharacterExtensions
{
private static readonly IReadOnlyList<string> _dispellableDebuffs = new List<string>
{
"Hunting Trap",
"Burning (Physical)"
};
public static bool ShouldDispel(this TorCharacter target)
{
return target != null && _dispellableDebuffs.Any(target.HasDebuff);
}
}
}
|
Use new ActionLink extension method. | @using Orchard.ContentManagement.MetaData.Models
@{
var containerId = (int) Model.ContainerId;
var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes;
}
<div class="item-properties actions">
<p>
@Html.ActionLink(T("{0} Properties", Html.Raw((string)Model.ContainerDisplayName)).Text, "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl })
</p>
</div>
<div class="manage">
@if (itemContentTypes.Any()) {
foreach (var contentType in itemContentTypes) {
@Html.ActionLink(T("New {0}", Html.Raw(contentType.DisplayName)).Text, "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" })
}
}
else {
@Html.ActionLink(T("New Content").ToString(), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" })
}
<a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a>
</div>
| @using Orchard.ContentManagement.MetaData.Models
@{
var containerId = (int) Model.ContainerId;
var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes;
}
<div class="item-properties actions">
<p>
@Html.ActionLink(T("{0} Properties", (string)Model.ContainerDisplayName), "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl })
</p>
</div>
<div class="manage">
@if (itemContentTypes.Any()) {
foreach (var contentType in itemContentTypes) {
@Html.ActionLink(T("New {0}", contentType.DisplayName), "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" })
}
}
else {
@Html.ActionLink(T("New Content"), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" })
}
<a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a>
</div>
|
Update package version to 0.1.1 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: InternalsVisibleTo("FakeHttpContext.Tests")]
[assembly: AssemblyTitle("FakeHttpContext")]
[assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vadim Zozulya")]
[assembly: AssemblyProduct("FakeHttpContext")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: InternalsVisibleTo("FakeHttpContext.Tests")]
[assembly: AssemblyTitle("FakeHttpContext")]
[assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vadim Zozulya")]
[assembly: AssemblyProduct("FakeHttpContext")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1.1")]
[assembly: AssemblyInformationalVersion("0.1.1")]
|
Fix create smtpclient with UseDefaultCredentials | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace Postal.AspNetCore
{
public class EmailServiceOptions
{
public EmailServiceOptions()
{
CreateSmtpClient = () => new SmtpClient(Host, Port)
{
Credentials = new NetworkCredential(UserName, Password),
EnableSsl = EnableSSL
};
}
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSSL { get; set; }
public string FromAddress { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Func<SmtpClient> CreateSmtpClient { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace Postal.AspNetCore
{
public class EmailServiceOptions
{
public EmailServiceOptions()
{
CreateSmtpClient = () => new SmtpClient(Host, Port)
{
UseDefaultCredentials = string.IsNullOrWhiteSpace(UserName),
Credentials = string.IsNullOrWhiteSpace(UserName) ? null : new NetworkCredential(UserName, Password),
EnableSsl = EnableSSL
};
}
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSSL { get; set; }
public string FromAddress { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Func<SmtpClient> CreateSmtpClient { get; set; }
}
}
|
Add helper functions for ApiKind | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Cci.Extensions
{
public static class ApiKindExtensions
{
public static bool IsInfrastructure(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Cci.Extensions
{
public static class ApiKindExtensions
{
public static bool IsInfrastructure(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
public static bool IsNamespace(this ApiKind kind)
{
return kind == ApiKind.Namespace;
}
public static bool IsType(this ApiKind kind)
{
switch (kind)
{
case ApiKind.Interface:
case ApiKind.Delegate:
case ApiKind.Enum:
case ApiKind.Struct:
case ApiKind.Class:
return true;
default:
return false;
}
}
public static bool IsMember(this ApiKind kind)
{
switch (kind)
{
case ApiKind.EnumField:
case ApiKind.DelegateMember:
case ApiKind.Field:
case ApiKind.Property:
case ApiKind.Event:
case ApiKind.Constructor:
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
case ApiKind.Method:
return true;
default:
return false;
}
}
public static bool IsAccessor(this ApiKind kind)
{
switch (kind)
{
case ApiKind.PropertyAccessor:
case ApiKind.EventAccessor:
return true;
default:
return false;
}
}
}
}
|
Add under load sample module | namespace Nancy.JohnnyFive.Sample
{
using System.Collections.Generic;
using System.IO;
using Circuits;
public class SampleModule : NancyModule
{
public SampleModule()
{
Get["/"] = _ =>
{
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<FileNotFoundException>()
.WithCircuitOpenTimeInSeconds(10));
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<KeyNotFoundException>()
.WithCircuitOpenTimeInSeconds(30));
if (this.Request.Query["fileNotFound"] != null)
throw new FileNotFoundException();
if (this.Request.Query["keyNotFound"] != null)
throw new KeyNotFoundException();
return "Hello, World!";
};
Get["/underload"] = _ =>
{
this.CanShortCircuit(new LastGoodResponseUnderLoad()
.WithRequestSampleTimeInSeconds(10)
.WithRequestThreshold(40));
};
}
}
} | namespace Nancy.JohnnyFive.Sample
{
using System;
using System.Collections.Generic;
using System.IO;
using Circuits;
public class SampleModule : NancyModule
{
public SampleModule()
{
Get["/"] = _ =>
{
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<FileNotFoundException>()
.WithCircuitOpenTimeInSeconds(10));
this.CanShortCircuit(new NoContentOnErrorCircuit()
.ForException<KeyNotFoundException>()
.WithCircuitOpenTimeInSeconds(30));
if (this.Request.Query["fileNotFound"] != null)
throw new FileNotFoundException();
if (this.Request.Query["keyNotFound"] != null)
throw new KeyNotFoundException();
return "Hello, World!";
};
Get["/underload"] = _ =>
{
this.CanShortCircuit(new NoContentUnderLoadCircuit()
.WithRequestSampleTimeInSeconds(10)
.WithRequestThreshold(5));
return "Under load " + DateTime.Now;
};
}
}
} |
Allow mirror to accept parameters to specify what to mount and where | using System;
using DokanNet;
namespace DokanNetMirror
{
internal class Program
{
private static void Main(string[] args)
{
try
{
bool unsafeReadWrite = args.Length > 0 && args[0].Equals("-unsafe", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}");
var mirror = unsafeReadWrite ? new UnsafeMirror("C:") : new Mirror("C:");
mirror.Mount("n:\\", DokanOptions.DebugMode, 5);
Console.WriteLine(@"Success");
}
catch (DokanException ex)
{
Console.WriteLine(@"Error: " + ex.Message);
}
}
}
} | using System;
using System.Linq;
using DokanNet;
namespace DokanNetMirror
{
internal class Program
{
private const string MirrorKey = "-what";
private const string MountKey = "-where";
private const string UseUnsafeKey = "-unsafe";
private static void Main(string[] args)
{
try
{
var arguments = args
.Select(x => x.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x => x[0], x => x.Length > 1 ? x[1] as object : true, StringComparer.OrdinalIgnoreCase);
var mirrorPath = arguments.ContainsKey(MirrorKey)
? arguments[MirrorKey] as string
: @"C:\";
var mountPath = arguments.ContainsKey(MountKey)
? arguments[MountKey] as string
: @"N:\";
var unsafeReadWrite = arguments.ContainsKey(UseUnsafeKey);
Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}");
var mirror = unsafeReadWrite
? new UnsafeMirror(mirrorPath)
: new Mirror(mirrorPath);
mirror.Mount(mountPath, DokanOptions.DebugMode, 5);
Console.WriteLine(@"Success");
}
catch (DokanException ex)
{
Console.WriteLine(@"Error: " + ex.Message);
}
}
}
} |
Add prototype movement for MetallKefer | using UnityEngine;
using System.Collections;
public class MetallKeferController : MonoBehaviour {
public GameObject gameControllerObject;
private GameController gameController;
private GameObject[] towerBasesBuildable;
void Start () {
this.gameController = this.gameControllerObject.GetComponent<GameController>();
this.FindInititalWaypoint ();
}
void FindInititalWaypoint() {
}
}
| using UnityEngine;
using System.Collections;
public class MetallKeferController : MonoBehaviour {
public GameObject gameControllerObject;
private GameController gameController;
private GameObject[] towerBasesBuildable;
private GameObject nextWaypiont;
private int currentWaypointIndex = 0;
private int movementSpeed = 2;
private float step = 10f;
void Start () {
this.gameController = this.gameControllerObject.GetComponent<GameController>();
this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex];
}
void Update() {
this.moveToNextWaypoint ();
}
void SetNextWaypoint() {
if (this.currentWaypointIndex < this.gameController.getWaypoints ().Length - 1) {
this.currentWaypointIndex += 1;
this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex];
this.nextWaypiont.GetComponent<Renderer> ().material.color = this.getRandomColor();
}
}
private Color getRandomColor() {
Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f );
return newColor;
}
private void moveToNextWaypoint() {
float step = movementSpeed * Time.deltaTime;
this.transform.LookAt (this.nextWaypiont.transform);
this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step);
this.SetNextWaypoint ();
}
}
|
Add lock around Get in session cache, and add default "unknown" username. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Plugin.MySqlLogger
{
class SessionCache
{
private Dictionary<int, string> m_cache;
public SessionCache()
{
m_cache = new Dictionary<int, string>();
}
public void Add(int sessId, string userName)
{
lock(this)
{
if (!m_cache.ContainsKey(sessId))
m_cache.Add(sessId, userName);
else
m_cache[sessId] = userName;
}
}
public string Get(int sessId)
{
if (m_cache.ContainsKey(sessId))
return m_cache[sessId];
return "";
}
public void Clear()
{
lock (this)
{
m_cache.Clear();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pGina.Plugin.MySqlLogger
{
class SessionCache
{
private Dictionary<int, string> m_cache;
public SessionCache()
{
m_cache = new Dictionary<int, string>();
}
public void Add(int sessId, string userName)
{
lock(this)
{
if (!m_cache.ContainsKey(sessId))
m_cache.Add(sessId, userName);
else
m_cache[sessId] = userName;
}
}
public string Get(int sessId)
{
string result = "--Unknown--";
lock (this)
{
if (m_cache.ContainsKey(sessId))
result = m_cache[sessId];
}
return result;
}
public void Clear()
{
lock (this)
{
m_cache.Clear();
}
}
}
}
|
Add order constructor and Payment | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Shop.Core.BaseObjects;
using Shop.Core.Interfaces;
namespace Shop.Core.Entites
{
public class Order : LifetimeBase, IReferenceable<Order>
{
[Key]
public int OrderId { get; set; }
public string OrderReference { get; set; }
public List<OrderProduct> Products { get; set; }
public DiscountCode DiscountCode { get; set; }
public ShippingDetails ShippingMethod { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
public Order CreateReference(IReferenceGenerator referenceGenerator)
{
OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength);
return this;
}
}
} | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Shop.Core.BaseObjects;
using Shop.Core.Interfaces;
namespace Shop.Core.Entites
{
public class Order : LifetimeBase, IReferenceable<Order>
{
[Key]
public int OrderId { get; set; }
public string OrderReference { get; set; }
public List<ProductConfiguration> Products { get; set; }
public DiscountCode DiscountCode { get; set; }
public ShippingDetails ShippingMethod { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
public Payment Payment { get; set; }
public Order()
{
OrderId = 0;
OrderReference = string.Empty;
Products = new List<ProductConfiguration>();
}
public Order CreateReference(IReferenceGenerator referenceGenerator)
{
OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength);
return this;
}
}
} |
Make DllImport exclusive to iOS | using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
| using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
#if UNITY_IOS
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
#endif
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
|
Split tests and deduplicated code | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
[TestMethod]
public void TestProduction()
{
IFactoryMethod factory = new IncompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
try
{
factory.Build(ProductType.Baz);
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
// Try again with a complete factory
factory = new CompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(BazProduct));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
using System.Collections.Generic;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
private Dictionary<ProductType, Type> ProductionProvider()
{
var products = new Dictionary<ProductType, Type>();
products.Add(ProductType.Foo, typeof(FooProduct));
products.Add(ProductType.Bar, typeof(BarProduct));
products.Add(ProductType.Baz, typeof(BazProduct));
return products;
}
[TestMethod]
public void TestFactoryProducesProducts()
{
var factory = new CompleteFactory();
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
}
[TestMethod]
public void TestIncompleteFactoryThrowsException()
{
IFactoryMethod factory = new IncompleteFactory();
try
{
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
// Must not get here
Assert.Fail();
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
}
}
}
|
Create JSon Reader command is ready | using System;
using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
public string Execute(List<string> parameters)
{
throw new NotImplementedException();
}
}
} | using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
using MovieTheater.Framework.Core.Providers;
using MovieTheater.Framework.Core.Providers.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
private IReader reader;
private IWriter writer;
public CreateJsonReaderCommand()
{
this.reader = new ConsoleReader();
this.writer = new ConsoleWriter();
}
public string Execute(List<string> parameters)
{
var jsonReader = new JsonReader(reader, writer);
jsonReader.Read();
return "Successfully read json file!";
}
}
} |
Remove extra `public`s from interface | using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
public void UnapplyAll();
}
}
| using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
void UnapplyAll();
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: AssemblyDescription("Autofac Castle.DynamicProxy2 Integration")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: ComVisible(false)] |
Add webhooks to the client interface. | namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
| namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets access to the webhooks resource of the SparkPost API.
/// </summary>
IWebhooks Webhooks { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
|
Sort battle roster by group, then by position desc | using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenBy(s => s.Rank)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
} | using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenByDescending(s => s.Position)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
} |
Return ShaderContent for built-in shader stages. | using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
throw new NotImplementedException("ImportShaderStage $basic");
}
if (filename == "$skinned")
{
throw new NotImplementedException("ImportShaderStage $skinned");
}
return next2(filename, type, importer);
}
}
}
| using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$basic\"");
return BuiltinShaders.BasicVertexShaderContent;
}
if (filename == "$skinned")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$skinned\"");
return BuiltinShaders.SkinnedVertexShaderContent;
}
if (filename == "$fragment")
{
if (type != ShaderType.Fragment)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$fragment\"");
return BuiltinShaders.BuiltinFragmentShaderContent;
}
return next2(filename, type, importer);
}
}
}
|
Add Public to build target | using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
} | using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
"GenericGraphEditor/Public",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
} |
Support listing charges by PaymentIntent id | namespace Stripe
{
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
/// <summary>
/// Only return charges for the customer specified by this customer ID.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// Only return charges that were created by the PaymentIntent specified by this
/// PaymentIntent ID.
/// </summary>
[JsonProperty("payment_intent")]
public string PaymentIntentId { get; set; }
[Obsolete("This parameter is deprecated. Filter the returned list of charges instead.")]
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
/// <summary>
/// Only return charges for this transfer group.
/// </summary>
[JsonProperty("transfer_group")]
public string TransferGroup { get; set; }
}
}
|
Extend test for Jobs list | using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => !string.IsNullOrEmpty(job.Department)));
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
|
Revert "Update comment to reflect possible config.json path" | using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the config.json file inside a sub directory called 'configuration' with the current directory.
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
} | using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the configuration file at .\configuration\config.json
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
} |
Make CatchStacker testcase more useful | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 512; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f + (i / 2048f * ((i % 10) - 5)), StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
|
Remove the nuget environment variable. | using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
_msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
// Disable this for now
// _msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
|
Fix header behavior for the fixed length types | namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container);
return descriptor;
}
}
} | namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container)
{
HasHeader = false
};
return descriptor;
}
}
} |
Clean up type checking code | using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature registration.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of feature registrations.</param>
/// <returns>List of feature registrations.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.Any(i => i.GetType() == typeof(T)))
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
} | using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature list.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of features.</param>
/// <returns>List of features.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.OfType<T>().Any())
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
} |
Improve Beam-weapon toString to include rating value | // <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Class-1 Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1,
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
}
} | // <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private const string BaseSystemName = "Beam Battery System";
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
public override string ToString()
{
this.SystemName = $"Class-{this.Rating} {BaseSystemName}";
return base.ToString();
}
}
} |
Bump to v0.9 - this is going to be the beta for 1.0 | #region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette 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.
Cassette 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
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.8.3")]
[assembly: AssemblyFileVersion("0.8.3")]
| #region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette 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.
Cassette 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
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.9.0")]
[assembly: AssemblyFileVersion("0.9.0")]
|
Add a default value for changeset.workitems. | using System.Collections.Generic;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
public TfsChangesetInfo()
{
Workitems = Enumerable.Empty<ITfsWorkitem>();
}
}
}
|
Improve handling of bad format for intervals | using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
| using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
if (!builder.IsValid())
throw builder.GetException();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
|
Remove custom SQL CE checks from IsConnectionStringConfigured | // Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
{
var dbIsSqlCe = false;
if (databaseSettings?.ProviderName != null)
{
dbIsSqlCe = databaseSettings.ProviderName == Constants.DbProviderNames.SqlCe;
}
var sqlCeDatabaseExists = false;
if (dbIsSqlCe)
{
var parts = databaseSettings.ConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dataSourcePart = parts.FirstOrDefault(x => x.InvariantStartsWith("Data Source="));
if (dataSourcePart != null)
{
var datasource = dataSourcePart.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
var filePath = datasource.Replace("Data Source=", string.Empty);
sqlCeDatabaseExists = File.Exists(filePath);
}
}
// Either the connection details are not fully specified or it's a SQL CE database that doesn't exist yet
if (databaseSettings == null
|| string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) || string.IsNullOrWhiteSpace(databaseSettings.ProviderName)
|| (dbIsSqlCe && sqlCeDatabaseExists == false))
{
return false;
}
return true;
}
}
}
| // Copyright (c) Umbraco.
// See LICENSE for more details.
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
=> databaseSettings != null &&
!string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) &&
!string.IsNullOrWhiteSpace(databaseSettings.ProviderName);
}
}
|
Remove type constraint for ChildrenOfType<T> | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable) where T : Drawable
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
| // 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.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable)
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
|
Add <exception> tags to CreateReader. | using System;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
| using System;
using System.IO;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs if <paramref name="address"/> is not a valid address.</exception>
/// <exception cref="EndOfStreamException">Occurs if <paramref name="length"/> is too long.</exception>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
|
Allow replace separator in crypt helper | using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value)
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes);
return hexString;
}
private static string BytesToHexString(byte[] bytes)
{
var result = string.Empty;
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
result += ((char)(n2 - 10 + 'A')).ToString();
}
else
{
result += n2.ToString();
}
if (n1 > 9)
{
result += ((char)(n1 - 10 + 'A')).ToString();
}
else
{
result += n1.ToString();
}
if ((i + 1) != bytes.Length && (i + 1) % 2 == 0)
{
result += "-";
}
}
return result;
}
}
} | using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value, char? separator = '-')
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes, separator);
return hexString;
}
private static string BytesToHexString(byte[] bytes, char? separator)
{
var stringBuilder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
stringBuilder.Append((char) n2 - 10 + 'A');
}
else
{
stringBuilder.Append(n2);
}
if (n1 > 9)
{
stringBuilder.Append((char) n1 - 10 + 'A');
}
else
{
stringBuilder.Append(n1);
}
if (separator.HasValue && ((i + 1) != bytes.Length && (i + 1) % 2 == 0))
{
stringBuilder.Append(separator.Value);
}
}
return stringBuilder.ToString();
}
}
} |
Add Options setup registration in DI container | using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web.Options;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
} | using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(null);
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Transient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
} |
Fix typo in Model-Repositories Service Register | using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class Repositories
{
public static void Register(IServiceCollection services) {
services.AddSingleton<IAdministratorsRepository, AdministratorsRepository>();
services.AddSingleton<IBookmarksRepository, BookmarksRepository>();
services.AddSingleton<ICommentsRepository, CommentsRepository>();
services.AddSingleton<IFollowersRepository, FollowersRepository>();
services.AddSingleton<ILikesRepository, LikesRepository>();
services.AddSingleton<ILocationsRepository, LocationsRepository>();
services.AddSingleton<IPostsRepository, IPostsRepository>();
services.AddSingleton<IReportsRepository, ReportsRepository>();
services.AddSingleton<ITagsRepository, TagsRepository>();
}
}
}
| using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class ModelRepositories
{
public static void Register(IServiceCollection services) {
services.AddScoped<IAdministratorsRepository, AdministratorsRepository>();
services.AddScoped<IBookmarksRepository, BookmarksRepository>();
services.AddScoped<ICommentsRepository, CommentsRepository>();
services.AddScoped<IFollowersRepository, FollowersRepository>();
services.AddScoped<ILikesRepository, LikesRepository>();
services.AddScoped<ILocationsRepository, LocationsRepository>();
services.AddScoped<IPostsRepository, PostsRepository>();
services.AddScoped<IReportsRepository, ReportsRepository>();
services.AddScoped<ITagsRepository, TagsRepository>();
}
}
}
|
Add documentation and remove unused using statements | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facile.Core
{
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Facile.Core
{
/// <summary>
/// Defines the result of a command's execution
/// </summary>
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
/// <summary>
/// Defines the result of a command's execution and returns a value of T
/// </summary>
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
|
Add TODO to handle serialization for null key | using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
| using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO Need to not include key in serialization when its null to allow mb to use self-signed certificate.
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
|
Remove a redundant ToArray call | using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).ToArray().FirstOrDefault();
}
}
}
}
| using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
// IQueryable.FirstOrDefault では不正な SQL 文が発行される
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).AsEnumerable().FirstOrDefault();
}
}
}
}
|
Fix the proxy test, why the body was even there? | using System;
using System.Net;
using NUnit.Framework;
using RestSharp.Tests.Shared.Fixtures;
namespace RestSharp.IntegrationTests
{
[TestFixture]
public class ProxyTests
{
class RequestBodyCapturer
{
public const string RESOURCE = "Capture";
}
[Test]
public void Set_Invalid_Proxy_Fails()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var client = new RestClient(server.Url) {Proxy = new WebProxy("non_existent_proxy", false)};
var request = new RestRequest();
const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
request.AddParameter(contentType, bodyData, ParameterType.RequestBody);
var response = client.Get(request);
Assert.False(response.IsSuccessful);
Assert.IsInstanceOf<WebException>(response.ErrorException);
}
[Test]
public void Set_Invalid_Proxy_Fails_RAW()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var requestUri = new Uri(new Uri(server.Url), "");
var webRequest = (HttpWebRequest) WebRequest.Create(requestUri);
webRequest.Proxy = new WebProxy("non_existent_proxy", false);
Assert.Throws<WebException>(() => webRequest.GetResponse());
}
}
} | using System;
using System.Net;
using NUnit.Framework;
using RestSharp.Tests.Shared.Fixtures;
namespace RestSharp.IntegrationTests
{
[TestFixture]
public class ProxyTests
{
[Test]
public void Set_Invalid_Proxy_Fails()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var client = new RestClient(server.Url) {Proxy = new WebProxy("non_existent_proxy", false)};
var request = new RestRequest();
var response = client.Get(request);
Assert.False(response.IsSuccessful);
Assert.IsInstanceOf<WebException>(response.ErrorException);
}
[Test]
public void Set_Invalid_Proxy_Fails_RAW()
{
using var server = HttpServerFixture.StartServer((_, __) => { });
var requestUri = new Uri(new Uri(server.Url), "");
var webRequest = (HttpWebRequest) WebRequest.Create(requestUri);
webRequest.Proxy = new WebProxy("non_existent_proxy", false);
Assert.Throws<WebException>(() => webRequest.GetResponse());
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.