commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
0c01045938e794cbf467ebf5821594e2099a661f | fix typo in NextUInt64 | ArsenShnurkov/BitSharp | BitSharp.Data.Test/RandomExtensionMethods.cs | BitSharp.Data.Test/RandomExtensionMethods.cs |
using BitSharp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Data.Test
{
public static class RandomExtensionMethods
{
public static UInt32 NextUInt32(this Random random)
{
// purposefully left unchecked to get full range of UInt32
return (UInt32)random.Next();
}
public static UInt64 NextUInt64(this Random random)
{
return (random.NextUInt32() << 32) + random.NextUInt32();
}
public static UInt256 NextUInt256(this Random random)
{
return new UInt256(
(new BigInteger(random.NextUInt32()) << 96) +
(new BigInteger(random.NextUInt32()) << 64) +
(new BigInteger(random.NextUInt32()) << 32) +
new BigInteger(random.NextUInt32()));
}
}
}
|
using BitSharp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Data.Test
{
public static class RandomExtensionMethods
{
public static UInt32 NextUInt32(this Random random)
{
// purposefully left unchecked to get full range of UInt32
return (UInt32)random.Next();
}
public static UInt64 NextUInt64(this Random random)
{
return (random.NextUInt32() << 32) + random.NextUInt64();
}
public static UInt256 NextUInt256(this Random random)
{
return new UInt256(
(new BigInteger(random.NextUInt32()) << 96) +
(new BigInteger(random.NextUInt32()) << 64) +
(new BigInteger(random.NextUInt32()) << 32) +
new BigInteger(random.NextUInt32()));
}
}
}
| unlicense | C# |
002aab3e76d2e84518fa2f8fa06c85ee068757cc | Fix unit test so it does unprotecting and padding | 0culus/ElectronicCash | ElectronicCash.Tests/SecretSplittingTests.cs | ElectronicCash.Tests/SecretSplittingTests.cs | using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
private const int Padding = 16;
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
Helpers.ToggleMemoryProtection(_splitter);
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
var toPad = Message;
Helpers.PadArrayToMultipleOf(ref toPad, Padding);
Helpers.ToggleMemoryProtection(_splitter);
Assert.AreEqual(Helpers.GetString(toPad), Helpers.GetString(m));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
| using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
| mit | C# |
317da2d01f457db22b5d2cc66729ff73988dbc4e | Fix string comparison for URL history | oda1560/XHRTool,oda1560/XHRTool | XHRTool.UI.WPF/ViewModels/UrlHistoryModel.cs | XHRTool.UI.WPF/ViewModels/UrlHistoryModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url, StringComparison.OrdinalIgnoreCase) && x.Verb.Equals(y.Verb, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XHRTool.XHRLogic.Common;
namespace XHRTool.UI.WPF.ViewModels
{
[Serializable]
public class UrlHistoryModel
{
public UrlHistoryModel(string url, string verb)
{
Url = url;
Verb = verb;
}
public string Url { get; set; }
public string Verb { get; set; }
}
public class UrlHistoryModelEqualityComparer : IEqualityComparer<UrlHistoryModel>
{
public bool Equals(UrlHistoryModel x, UrlHistoryModel y)
{
return x.Url.Equals(y.Url) && x.Verb.Equals(y.Verb);
}
public int GetHashCode(UrlHistoryModel obj)
{
return (obj.Verb.GetHashCode() + obj.Url.GetHashCode()) / 2;
}
}
}
| agpl-3.0 | C# |
1fa06a3a5b724c77aa30833392a43e09dff1a3e9 | Improve logging of AppUpdaterEmptyStrategy | patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity | src/Assets/Scripts/AppUpdater/AppUpdaterEmptyStrategy.cs | src/Assets/Scripts/AppUpdater/AppUpdaterEmptyStrategy.cs | using PatchKit.Unity.Patcher.Cancellation;
using PatchKit.Unity.Patcher.Debug;
namespace PatchKit.Unity.Patcher.AppUpdater
{
public class AppUpdaterEmptyStrategy : IAppUpdaterStrategy
{
private static readonly DebugLogger DebugLogger = new DebugLogger(typeof(AppUpdaterStrategyResolver));
public void Update(CancellationToken cancellationToken)
{
DebugLogger.Log("Updating with empty strategy. Doing nothing. ");
}
}
} | using PatchKit.Unity.Patcher.Cancellation;
namespace PatchKit.Unity.Patcher.AppUpdater
{
public class AppUpdaterEmptyStrategy : IAppUpdaterStrategy
{
public void Update(CancellationToken cancellationToken)
{
}
}
} | mit | C# |
9bf6808c47921d6be32054c62916ba8847f9a03f | Use JSValue.MarshalArray | arfbtwn/banshee,mono-soc-2011/banshee,GNOME/banshee,stsundermann/banshee,dufoli/banshee,ixfalia/banshee,stsundermann/banshee,babycaseny/banshee,mono-soc-2011/banshee,ixfalia/banshee,mono-soc-2011/banshee,Carbenium/banshee,Dynalon/banshee-osx,GNOME/banshee,Carbenium/banshee,dufoli/banshee,mono-soc-2011/banshee,dufoli/banshee,stsundermann/banshee,GNOME/banshee,lamalex/Banshee,babycaseny/banshee,dufoli/banshee,Dynalon/banshee-osx,arfbtwn/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,stsundermann/banshee,Dynalon/banshee-osx,babycaseny/banshee,Carbenium/banshee,arfbtwn/banshee,babycaseny/banshee,stsundermann/banshee,stsundermann/banshee,Carbenium/banshee,ixfalia/banshee,arfbtwn/banshee,babycaseny/banshee,ixfalia/banshee,dufoli/banshee,GNOME/banshee,babycaseny/banshee,Dynalon/banshee-osx,arfbtwn/banshee,GNOME/banshee,Carbenium/banshee,Carbenium/banshee,babycaseny/banshee,Dynalon/banshee-osx,GNOME/banshee,lamalex/Banshee,arfbtwn/banshee,arfbtwn/banshee,lamalex/Banshee,mono-soc-2011/banshee,lamalex/Banshee,babycaseny/banshee,lamalex/Banshee,Dynalon/banshee-osx,Dynalon/banshee-osx,arfbtwn/banshee,GNOME/banshee,ixfalia/banshee,dufoli/banshee,stsundermann/banshee,lamalex/Banshee,stsundermann/banshee,ixfalia/banshee,dufoli/banshee,dufoli/banshee,ixfalia/banshee,GNOME/banshee,mono-soc-2011/banshee,ixfalia/banshee | src/Core/Banshee.WebBrowser/JavaScriptCore/JSFunction.cs | src/Core/Banshee.WebBrowser/JavaScriptCore/JSFunction.cs | //
// JSFunction.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace JavaScriptCore
{
public delegate JSValue JSFunctionHandler (JSObject function, JSObject thisObject, JSValue [] args);
public class JSFunction : JSObject
{
[DllImport (JSContext.NATIVE_IMPORT)]
private static extern IntPtr JSObjectMakeFunctionWithCallback (IntPtr ctx, JSString name,
CallAsFunctionCallback callAsFunction);
#pragma warning disable 0414
private JSObject.CallAsFunctionCallback native_callback;
#pragma warning restore 0414
private JSFunctionHandler handler;
public JSFunction (JSContext context, string name, JSFunctionHandler handler) : base (context, IntPtr.Zero)
{
this.handler = handler;
var native_name = JSString.New (name);
Raw = JSObjectMakeFunctionWithCallback (context.Raw, native_name,
native_callback = new JSObject.CallAsFunctionCallback (JSCallback));
native_name.Release ();
}
private IntPtr JSCallback (IntPtr ctx, IntPtr function, IntPtr thisObject,
IntPtr argumentCount, IntPtr arguments, ref IntPtr exception)
{
var context = new JSContext (ctx);
return handler == null
? JSValue.NewUndefined (context).Raw
: handler (this, new JSObject (context, thisObject),
JSValue.MarshalArray (ctx, arguments, argumentCount)).Raw;
}
}
} | //
// JSFunction.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace JavaScriptCore
{
public delegate JSValue JSFunctionHandler (JSObject function, JSObject thisObject, JSValue [] args);
public class JSFunction : JSObject
{
[DllImport (JSContext.NATIVE_IMPORT)]
private static extern IntPtr JSObjectMakeFunctionWithCallback (IntPtr ctx, JSString name,
CallAsFunctionCallback callAsFunction);
#pragma warning disable 0414
private JSObject.CallAsFunctionCallback native_callback;
#pragma warning restore 0414
private JSFunctionHandler handler;
public JSFunction (JSContext context, string name, JSFunctionHandler handler) : base (context, IntPtr.Zero)
{
this.handler = handler;
var native_name = JSString.New (name);
Raw = JSObjectMakeFunctionWithCallback (context.Raw, native_name,
native_callback = new JSObject.CallAsFunctionCallback (JSCallback));
native_name.Release ();
}
private IntPtr JSCallback (IntPtr ctx, IntPtr function, IntPtr thisObject,
IntPtr argumentCount, IntPtr arguments, ref IntPtr exception)
{
var context = new JSContext (ctx);
if (handler == null) {
return JSValue.NewUndefined (context).Raw;
}
var args = new JSValue[argumentCount.ToInt32 ()];
for (int i = 0; i < args.Length; i++) {
args[i] = new JSValue (context, Marshal.ReadIntPtr (arguments, i * IntPtr.Size));
}
return handler (this, new JSObject (context, thisObject), args).Raw;
}
}
} | mit | C# |
c6a969fe74e18d3f797db9e2f782cc7d30d74384 | update notify bindingresource.create snippet | teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | notifications/rest/bindings/create-binding/create-binding.5.x.cs | notifications/rest/bindings/create-binding/create-binding.5.x.cs | // Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Notify.Service;
public class Example
{
public static void Main(string[] args)
{
// Find your Account SID and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var binding = BindingResource.Create(
servicePathSid: serviceSid,
identity: "00000001",
bindingType: BindingResource.BindingTypeEnum.Apn,
address: "device_token",
tag: new List<string> { "preferred device", "new user" });
Console.WriteLine(binding.Sid);
}
}
| // Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Notify.Service;
public class Example
{
public static void Main(string[] args)
{
// Find your Account SID and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var binding = BindingResource.Create(
serviceSid,
"endpoint",
"00000001",
BindingResource.BindingTypeEnum.Apn,
"device_token",
new List<string> { "preferred device", "new user" });
Console.WriteLine(binding.Sid);
}
}
| mit | C# |
fb06e51eff984b55009127162f984b44a996acd4 | Fix SystemColorOutputSink to print warning and error details | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/OutputSinks/SystemColorOutputSink.cs | source/Nuke.Common/OutputSinks/SystemColorOutputSink.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class SystemColorOutputSink : ConsoleOutputSink
{
public override void WriteNormal(string text)
{
Console.WriteLine(text);
}
public override void WriteTrace(string text)
{
WriteWithColors(text, ConsoleColor.Gray);
}
public override void WriteInformation(string text)
{
WriteWithColors(text, ConsoleColor.Cyan);
}
public override void WriteWarning(string text, string details = null)
{
WriteWithColors(text, ConsoleColor.Yellow);
if (details != null)
WriteWithColors(details, ConsoleColor.Yellow);
}
public override void WriteError(string text, string details = null)
{
WriteWithColors(text, ConsoleColor.Red);
if (details != null)
WriteWithColors(details, ConsoleColor.Red);
}
public override void WriteSuccess(string text)
{
WriteWithColors(text, ConsoleColor.Green);
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void WriteWithColors(string text, ConsoleColor foregroundColor)
{
var previousForegroundColor = Console.ForegroundColor;
// using (DelegateDisposable.CreateBracket(
// () => Console.ForegroundColor = foregroundColor,
// () => Console.ForegroundColor = previousForegroundColor))
{
Console.WriteLine(text);
}
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class SystemColorOutputSink : ConsoleOutputSink
{
public override void WriteNormal(string text)
{
Console.WriteLine(text);
}
public override void WriteTrace(string text)
{
WriteWithColors(text, ConsoleColor.Gray);
}
public override void WriteInformation(string text)
{
WriteWithColors(text, ConsoleColor.Cyan);
}
public override void WriteWarning(string text, string details = null)
{
WriteWithColors(text, ConsoleColor.Yellow);
}
public override void WriteError(string text, string details = null)
{
WriteWithColors(text, ConsoleColor.Red);
}
public override void WriteSuccess(string text)
{
WriteWithColors(text, ConsoleColor.Green);
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void WriteWithColors(string text, ConsoleColor foregroundColor)
{
var previousForegroundColor = Console.ForegroundColor;
// using (DelegateDisposable.CreateBracket(
// () => Console.ForegroundColor = foregroundColor,
// () => Console.ForegroundColor = previousForegroundColor))
{
Console.WriteLine(text);
}
}
}
}
| mit | C# |
07edfe20719df382129d27a3171b6acf91587f11 | Fix scopes | danbarua/Cedar.EventStore,damianh/Cedar.EventStore,damianh/SqlStreamStore,SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore | src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.cs | src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.cs | namespace Cedar.EventStore
{
using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
public abstract partial class EventStoreAcceptanceTests
{
private readonly ITestOutputHelper _testOutputHelper;
protected abstract EventStoreAcceptanceTestFixture GetFixture();
protected EventStoreAcceptanceTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public async Task When_dispose_and_read_then_should_throw()
{
using(var fixture = GetFixture())
{
var store = await fixture.GetEventStore();
store.Dispose();
Func<Task> act = () => store.ReadAll(Checkpoint.Start, 10);
act.ShouldThrow<ObjectDisposedException>();
}
}
[Fact]
public async Task Can_dispose_more_than_once()
{
using (var fixture = GetFixture())
{
var store = await fixture.GetEventStore();
store.Dispose();
Action act = store.Dispose;
act.ShouldNotThrow();
}
}
protected static NewStreamEvent[] CreateNewStreamEvents(params int[] eventNumbers)
{
return eventNumbers
.Select(eventNumber =>
{
var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0'));
return new NewStreamEvent(eventId, "type", "\"data\"", "\"metadata\"");
})
.ToArray();
}
private static StreamEvent ExpectedStreamEvent(
string streamId,
int eventNumber,
int sequenceNumber,
DateTime created)
{
var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0'));
return new StreamEvent(streamId, eventId, sequenceNumber, null, created, "type", "\"data\"", "\"metadata\"");
}
}
} | namespace Cedar.EventStore
{
using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
public abstract partial class EventStoreAcceptanceTests
{
private readonly ITestOutputHelper _testOutputHelper;
protected abstract EventStoreAcceptanceTestFixture GetFixture();
protected EventStoreAcceptanceTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public async Task When_dispose_and_read_then_should_throw()
{
using(var fixture = GetFixture())
{
var store = await fixture.GetEventStore();
store.Dispose();
Func<Task> act = () => store.ReadAll(Checkpoint.Start, 10);
act.ShouldThrow<ObjectDisposedException>();
}
}
[Fact]
public async Task Can_dispose_more_than_once()
{
using (var fixture = GetFixture())
{
var store = await fixture.GetEventStore();
store.Dispose();
Action act = store.Dispose;
act.ShouldNotThrow();
}
}
public static NewStreamEvent[] CreateNewStreamEvents(params int[] eventNumbers)
{
return eventNumbers
.Select(eventNumber =>
{
var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0'));
return new NewStreamEvent(eventId, "type", "\"data\"", "\"metadata\"");
})
.ToArray();
}
public static StreamEvent ExpectedStreamEvent(
string streamId,
int eventNumber,
int sequenceNumber,
DateTime created)
{
var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0'));
return new StreamEvent(streamId, eventId, sequenceNumber, null, created, "type", "\"data\"", "\"metadata\"");
}
}
} | mit | C# |
545fc0d5726f4740296808ec8c9f5c1ba712a9bc | Fix BillingDetails on PaymentMethod creation to have the right params | stripe/stripe-dotnet,richardlawley/stripe.net | src/Stripe.net/Services/PaymentMethods/BillingDetailsOptions.cs | src/Stripe.net/Services/PaymentMethods/BillingDetailsOptions.cs | namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("phone")]
public string Phone { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class BillingDetailsOptions : INestedOptions
{
[JsonProperty("address")]
public AddressOptions Address { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("line1")]
public string Line1 { get; set; }
[JsonProperty("line2")]
public string Line2 { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
}
| apache-2.0 | C# |
6422b902a5fb40f3a805e1b259d6bd6f1496f454 | Increment version. | jyuch/ReflectionToStringBuilder | src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs | src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("ReflectionToStringBuilder")]
[assembly: AssemblyDescription("ReflectionでToStringするアレ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReflectionToStringBuilder")]
[assembly: AssemblyCopyright("Copyright © 2015 jyuch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("ReflectionToStringBuilder")]
[assembly: AssemblyDescription("ReflectionでToStringするアレ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReflectionToStringBuilder")]
[assembly: AssemblyCopyright("Copyright © 2015 jyuch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| mit | C# |
40f0531e5ff7b7e2b079e51813b509413e643a3d | Update ArgbColorTypeConverter.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Serializer.Xaml/Converters/ArgbColorTypeConverter.cs | src/Serializer.Xaml/Converters/ArgbColorTypeConverter.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
#if NETSTANDARD1_3
using System.ComponentModel;
#endif
using Core2D.Style;
using Portable.Xaml.ComponentModel;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ArgbColor"/> type converter.
/// </summary>
internal class ArgbColorTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ArgbColor.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var color = value as ArgbColor;
if (color != null)
{
return ArgbColor.ToHtml(color);
}
throw new NotSupportedException();
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
#if NETSTANDARD1_3
using System.ComponentModel;
#else
using Portable.Xaml.ComponentModel;
#endif
using Core2D.Style;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ArgbColor"/> type converter.
/// </summary>
internal class ArgbColorTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ArgbColor.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var color = value as ArgbColor;
if (color != null)
{
return ArgbColor.ToHtml(color);
}
throw new NotSupportedException();
}
}
}
| mit | C# |
820e0164bddea985ccc2a9d8ad3ba01bf519e125 | Fix formatting | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Graphics/Effects/EffectParameter.cs | src/OpenSage.Game/Graphics/Effects/EffectParameter.cs | using OpenSage.Graphics.Shaders;
using Veldrid;
namespace OpenSage.Graphics.Effects
{
internal sealed class EffectParameter : DisposableBase
{
private readonly uint _slot;
private ResourceSet _data;
private bool _dirty;
public string Name => ResourceBinding.Name;
public ResourceBinding ResourceBinding { get; }
public ResourceLayout ResourceLayout { get; }
public EffectParameter(
GraphicsDevice graphicsDevice,
ResourceBinding resourceBinding,
in ResourceLayoutElementDescription layoutDescription,
uint slot)
{
_slot = slot;
ResourceBinding = resourceBinding;
var description = new ResourceLayoutDescription(layoutDescription);
ResourceLayout = AddDisposable(graphicsDevice.ResourceFactory.CreateResourceLayout(
ref description));
}
public void SetData(ResourceSet resourceSet)
{
if (ReferenceEquals(_data, resourceSet))
{
return;
}
_data = resourceSet;
_dirty = true;
}
internal void SetDirty()
{
_dirty = true;
}
public void ApplyChanges(CommandList commandEncoder)
{
if (!_dirty)
{
return;
}
if (_data != null)
{
commandEncoder.SetGraphicsResourceSet(_slot, _data);
}
_dirty = false;
}
}
}
| using OpenSage.Graphics.Shaders;
using Veldrid;
namespace OpenSage.Graphics.Effects
{
internal sealed class EffectParameter : DisposableBase
{
private readonly uint _slot;
private ResourceSet _data;
private bool _dirty;
public string Name => ResourceBinding.Name;
public ResourceBinding ResourceBinding { get; }
public ResourceLayout ResourceLayout { get; }
public EffectParameter(
GraphicsDevice graphicsDevice,
ResourceBinding resourceBinding,
in ResourceLayoutElementDescription layoutDescription,
uint slot)
{
_slot = slot;
ResourceBinding = resourceBinding;
var description = new ResourceLayoutDescription(layoutDescription);
ResourceLayout = AddDisposable(graphicsDevice.ResourceFactory.CreateResourceLayout(
ref description));
}
public void SetData(ResourceSet resourceSet)
{
if (ReferenceEquals(_data, resourceSet))
{
return;
}
_data = resourceSet;
_dirty = true;
}
internal void SetDirty()
{
_dirty = true;
}
public void ApplyChanges(CommandList commandEncoder)
{
if (!_dirty)
{
return;
}
if (_data!=null)
{
commandEncoder.SetGraphicsResourceSet(_slot, _data);
}
_dirty = false;
}
}
}
| mit | C# |
1dee9daafb587a8ba7dea1b3a1e9a834486cfc57 | increment patch version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.21.1")]
[assembly: AssemblyInformationalVersion("0.21.1")]
/*
* Version 0.21.1
*
* - [FIX] Renames ExamAttribute to TestAttribute and FirstClassExamAttribute to
* FirstClassTestAttribute. (BREAKING-CHANGE)
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.21.0")]
[assembly: AssemblyInformationalVersion("0.21.0")]
/*
* Version 0.21.1
*
* - [FIX] Renames ExamAttribute to TestAttribute and FirstClassExamAttribute to
* FirstClassTestAttribute. (BREAKING-CHANGE)
*/ | mit | C# |
7d145a74704d61a1a44360cac41cd20be0180495 | Add test for loading spinner with box | ppy/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,UselessToucan/osu | osu.Game.Tests/Visual/UserInterface/TestSceneLoadingSpinner.cs | osu.Game.Tests/Visual/UserInterface/TestSceneLoadingSpinner.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner(true)
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneLoadingSpinner : OsuGridTestScene
{
public TestSceneLoadingSpinner()
: base(2, 2)
{
LoadingSpinner loading;
Cell(0).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(1).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.White,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(2).AddRange(new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both
},
loading = new LoadingSpinner()
});
loading.Show();
Cell(3).AddRange(new Drawable[]
{
loading = new LoadingSpinner()
});
Scheduler.AddDelayed(() => loading.ToggleVisibility(), 200, true);
}
}
}
| mit | C# |
6908a69c63811e536407bc1216a2d1a79a5a2bff | Add some missing RegionInformation doc | OpensourceScape/RsCacheLibrary | src/Runescape.Cache.Structures/Map/RegionInformation.cs | src/Runescape.Cache.Structures/Map/RegionInformation.cs | using System;
using System.Collections.Generic;
using System.Text;
using FreecraftCore.Serializer;
namespace Runescape.Cache
{
[WireDataContract]
public sealed class RegionInformation
{
/// <summary>
/// Location hash for the region.
/// </summary>
[WireMember(1)]
public ushort RegionHash { get; }
//TODO: What is this?
/// <summary>
/// The tile-map index this region uses.
/// </summary>
[WireMember(2)]
public ushort RegionLandscapeIndex { get; }
//TODO: What is this?
/// <summary>
/// The object-map index this region uses.
/// </summary>
[WireMember(3)]
public ushort RegionObjectMapIndex { get; }
//TODO: What is this?
/// <summary>
/// ?
/// </summary>
[WireMember(4)]
public byte RegionPreload { get; }
/// <summary>
/// Protected serializer ctor
/// </summary>
protected RegionInformation()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using FreecraftCore.Serializer;
namespace Runescape.Cache
{
[WireDataContract]
public sealed class RegionInformation
{
/*regionHash[reg] = b.getShortUnsigned();
regionLandscapeIndex[reg] = b.getShortUnsigned();
regionObjectMapIndex[reg] = b.getShortUnsigned();
regionPreload[reg] = b.getUnsigned();*/
/// <summary>
/// Location hash for the region.
/// </summary>
[WireMember(1)]
public ushort RegionHash { get; }
//TODO: What is this?
/// <summary>
/// ?
/// </summary>
[WireMember(2)]
public ushort RegionLandscapeIndex { get; }
//TODO: What is this?
/// <summary>
/// ?
/// </summary>
[WireMember(3)]
public ushort RegionObjectMapIndex { get; }
//TODO: What is this?
/// <summary>
/// ?
/// </summary>
[WireMember(4)]
public byte RegionPreload { get; }
/// <summary>
/// Protected serializer ctor
/// </summary>
protected RegionInformation()
{
}
}
}
| mit | C# |
7d7946ac27fee6f3a67d91f8ac09030d8551845f | Fix vessel state handling | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Systems/VesselFlightStateSys/VesselFlightStateMessageHandler.cs | Client/Systems/VesselFlightStateSys/VesselFlightStateMessageHandler.cs | using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
{
public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();
public void HandleMessage(IMessageData messageData)
{
var msgData = messageData as VesselFlightStateMsgData;
if (msgData == null) return;
if (System.FlightStatesDictionary.ContainsKey(msgData.VesselId))
{
var flightState = new FlightCtrlState
{
mainThrottle = msgData.MainThrottle,
wheelThrottleTrim = msgData.WheelThrottleTrim,
X = msgData.X,
Y = msgData.Y,
Z = msgData.Z,
killRot = msgData.KillRot,
gearUp = msgData.GearUp,
gearDown = msgData.GearDown,
headlight = msgData.Headlight,
wheelThrottle = msgData.WheelThrottle,
roll = msgData.Roll,
yaw = msgData.Yaw,
pitch = msgData.Pitch,
rollTrim = msgData.RollTrim,
yawTrim = msgData.YawTrim,
pitchTrim = msgData.PitchTrim,
wheelSteer = msgData.WheelSteer,
wheelSteerTrim = msgData.WheelSteerTrim
};
System.FlightStatesDictionary[msgData.VesselId] = flightState;
}
}
}
}
| using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
{
public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();
public void HandleMessage(IMessageData messageData)
{
var msgData = messageData as VesselFlightStateMsgData;
if (msgData == null) return;
var flightState = new FlightCtrlState
{
mainThrottle = msgData.MainThrottle,
wheelThrottleTrim = msgData.WheelThrottleTrim,
X = msgData.X,
Y = msgData.Y,
Z = msgData.Z,
killRot = msgData.KillRot,
gearUp = msgData.GearUp,
gearDown = msgData.GearDown,
headlight = msgData.Headlight,
wheelThrottle = msgData.WheelThrottle,
roll = msgData.Roll,
yaw = msgData.Yaw,
pitch = msgData.Pitch,
rollTrim = msgData.RollTrim,
yawTrim = msgData.YawTrim,
pitchTrim = msgData.PitchTrim,
wheelSteer = msgData.WheelSteer,
wheelSteerTrim = msgData.WheelSteerTrim
};
System.FlightState = flightState;
}
}
}
| mit | C# |
8f75aea912dcca6605f691107cba2074e1f37a95 | Add VVAccess to SignalTransmitterComponent (#8400) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/MachineLinking/Components/SignalTransmitterComponent.cs | Content.Server/MachineLinking/Components/SignalTransmitterComponent.cs | using Content.Server.MachineLinking.System;
namespace Content.Server.MachineLinking.Components
{
[DataDefinition]
public struct PortIdentifier
{
[DataField("uid")]
public EntityUid Uid;
[DataField("port")]
public string Port;
public PortIdentifier(EntityUid uid, string port)
{
Uid = uid;
Port = port;
}
}
[RegisterComponent]
[Friend(typeof(SignalLinkerSystem))]
public sealed class SignalTransmitterComponent : Component
{
/// <summary>
/// How far the device can transmit a signal wirelessly.
/// Devices farther than this range can still transmit if they are
/// on the same powernet.
/// </summary>
[DataField("transmissionRange")]
[ViewVariables(VVAccess.ReadWrite)]
public float TransmissionRange = 30f;
[DataField("outputs")]
public Dictionary<string, List<PortIdentifier>> Outputs = new();
}
}
| using Content.Server.MachineLinking.System;
namespace Content.Server.MachineLinking.Components
{
[DataDefinition]
public struct PortIdentifier
{
[DataField("uid")]
public EntityUid Uid;
[DataField("port")]
public string Port;
public PortIdentifier(EntityUid uid, string port)
{
Uid = uid;
Port = port;
}
}
[RegisterComponent]
[Friend(typeof(SignalLinkerSystem))]
public sealed class SignalTransmitterComponent : Component
{
/// <summary>
/// How far the device can transmit a signal wirelessly.
/// Devices farther than this range can still transmit if they are
/// on the same powernet.
/// </summary>
[DataField("transmissionRange")]
public float TransmissionRange = 30f;
[DataField("outputs")]
public Dictionary<string, List<PortIdentifier>> Outputs = new();
}
}
| mit | C# |
8809a068541bcad32483283a51f321f5b6709bbc | Add breadcrumb caption example to basic directory selector | ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework/Graphics/UserInterface/BasicDirectorySelectorBreadcrumbDisplay.cs | osu.Framework/Graphics/UserInterface/BasicDirectorySelectorBreadcrumbDisplay.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace osu.Framework.Graphics.UserInterface
{
public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay
{
protected override Drawable CreateCaption() => new SpriteText
{
Text = "Current Directory:",
Font = FrameworkFont.Condensed.With(size: 20),
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft
};
protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new BreadcrumbDisplayComputer();
protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new BreadcrumbDisplayDirectory(directory, displayName);
public BasicDirectorySelectorBreadcrumbDisplay()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
protected class BreadcrumbDisplayComputer : BreadcrumbDisplayDirectory
{
protected override IconUsage? Icon => null;
public BreadcrumbDisplayComputer()
: base(null, "Computer")
{
}
}
protected class BreadcrumbDisplayDirectory : BasicDirectorySelectorDirectory
{
protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null;
public BreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null)
: base(directory, displayName)
{
}
[BackgroundDependencyLoader]
private void load()
{
Flow.Add(new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = FontAwesome.Solid.ChevronRight,
Size = new Vector2(FONT_SIZE / 2)
});
}
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace osu.Framework.Graphics.UserInterface
{
public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay
{
protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new BreadcrumbDisplayComputer();
protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new BreadcrumbDisplayDirectory(directory, displayName);
public BasicDirectorySelectorBreadcrumbDisplay()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
protected class BreadcrumbDisplayComputer : BreadcrumbDisplayDirectory
{
protected override IconUsage? Icon => null;
public BreadcrumbDisplayComputer()
: base(null, "Computer")
{
}
}
protected class BreadcrumbDisplayDirectory : BasicDirectorySelectorDirectory
{
protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null;
public BreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null)
: base(directory, displayName)
{
}
[BackgroundDependencyLoader]
private void load()
{
Flow.Add(new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = FontAwesome.Solid.ChevronRight,
Size = new Vector2(FONT_SIZE / 2)
});
}
}
}
}
| mit | C# |
15414c85594e33f6cea5055723a653d3f8daa623 | Fix for Lens3D merge conflict | netonjm/CocosSharp,mono/cocos2d-xna,haithemaraissia/CocosSharp,mono/CocosSharp,haithemaraissia/CocosSharp,zmaruo/CocosSharp,hig-ag/CocosSharp,mono/cocos2d-xna,hig-ag/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,MSylvia/CocosSharp,netonjm/CocosSharp | tests/tests/classes/tests/EffectsAdvancedTest/Effect1.cs | tests/tests/classes/tests/EffectsAdvancedTest/Effect1.cs | using cocos2d;
namespace tests
{
public class Effect1 : EffectAdvanceTextLayer
{
public override void OnEnter()
{
base.OnEnter();
CCNode target = GetChildByTag(EffectAdvanceScene.kTagBackground);
// To reuse a grid the grid size and the grid type must be the same.
// in this case:
// Lens3D is Grid3D and it's size is (15,10)
// Waves3D is Grid3D and it's size is (15,10)
CCSize size = CCDirector.SharedDirector.WinSize;
CCActionInterval lens = new CCLens3D(new CCPoint(size.Width / 2, size.Height / 2), 240, new CCGridSize(15, 10), 0.0f);
CCActionInterval waves = new CCWaves3D(18, 15, new CCGridSize(15, 10), 10);
CCFiniteTimeAction reuse = new CCReuseGrid(1);
CCActionInterval delay = new CCDelayTime (8);
CCActionInterval orbit = new CCOrbitCamera(5, 1, 2, 0, 180, 0, -90);
CCFiniteTimeAction orbit_back = orbit.Reverse();
target.RunAction(new CCRepeatForever ((CCSequence.FromActions(orbit, orbit_back))));
target.RunAction(CCSequence.FromActions(lens, delay, reuse, waves));
}
public override string title()
{
return "Lens + Waves3d and OrbitCamera";
}
}
} | using cocos2d;
namespace tests
{
public class Effect1 : EffectAdvanceTextLayer
{
public override void OnEnter()
{
base.OnEnter();
CCNode target = GetChildByTag(EffectAdvanceScene.kTagBackground);
// To reuse a grid the grid size and the grid type must be the same.
// in this case:
// Lens3D is Grid3D and it's size is (15,10)
// Waves3D is Grid3D and it's size is (15,10)
CCSize size = CCDirector.SharedDirector.WinSize;
CCActionInterval lens = CCLens3D.Create(new CCPoint(size.Width / 2, size.Height / 2), 240, new CCGridSize(15, 10), 0.0f);
CCActionInterval waves = new CCWaves3D(18, 15, new CCGridSize(15, 10), 10);
CCFiniteTimeAction reuse = new CCReuseGrid(1);
CCActionInterval delay = new CCDelayTime (8);
CCActionInterval orbit = new CCOrbitCamera(5, 1, 2, 0, 180, 0, -90);
CCFiniteTimeAction orbit_back = orbit.Reverse();
target.RunAction(new CCRepeatForever ((CCSequence.FromActions(orbit, orbit_back))));
target.RunAction(CCSequence.FromActions(lens, delay, reuse, waves));
}
public override string title()
{
return "Lens + Waves3d and OrbitCamera";
}
}
} | mit | C# |
561ba66fbda06ef9eed5ebc38b231cebd72a52ab | Change error controller range to start at 400 | ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate | Source/MVC6/Boilerplate.Web.Mvc6.Sample/Controllers/ErrorController.cs | Source/MVC6/Boilerplate.Web.Mvc6.Sample/Controllers/ErrorController.cs | namespace MvcBoilerplate.Controllers
{
using Boilerplate.Web.Mvc;
using Microsoft.AspNet.Mvc;
using MvcBoilerplate.Constants;
/// <summary>
/// Provides methods that respond to HTTP requests with HTTP errors.
/// </summary>
[Route("[controller]")]
public sealed class ErrorController : Controller
{
#region Public Methods
/// <summary>
/// Gets the error view for the specified HTTP error status code. Returns a <see cref="PartialViewResult"/> if
/// the request is an Ajax request, otherwise returns a full <see cref="ViewResult"/>.
/// </summary>
/// <param name="statusCode">The HTTP error status code.</param>
/// <param name="status">The name of the HTTP error status code e.g. 'notfound'. This is not used but is here
/// for aesthetic purposes.</param>
/// <returns>A <see cref="PartialViewResult"/> if the request is an Ajax request, otherwise returns a full
/// <see cref="ViewResult"/> containing the error view.</returns>
[ResponseCache(CacheProfileName = CacheProfileName.Error)]
[HttpGet("{statusCode:int:range(400, 599)}/{status?}", Name = ErrorControllerRoute.GetError)]
public IActionResult Error(int statusCode, string status)
{
this.Response.StatusCode = statusCode;
ActionResult result;
if (this.Request.IsAjaxRequest())
{
// This allows us to show errors even in partial views.
result = this.PartialView(ErrorControllerAction.Error, statusCode);
}
else
{
result = this.View(ErrorControllerAction.Error, statusCode);
}
return result;
}
#endregion
}
} | namespace MvcBoilerplate.Controllers
{
using Boilerplate.Web.Mvc;
using Microsoft.AspNet.Mvc;
using MvcBoilerplate.Constants;
/// <summary>
/// Provides methods that respond to HTTP requests with HTTP errors.
/// </summary>
[Route("[controller]")]
public sealed class ErrorController : Controller
{
#region Public Methods
/// <summary>
/// Gets the error view for the specified HTTP error status code. Returns a <see cref="PartialViewResult"/> if
/// the request is an Ajax request, otherwise returns a full <see cref="ViewResult"/>.
/// </summary>
/// <param name="statusCode">The HTTP error status code.</param>
/// <param name="status">The name of the HTTP error status code e.g. 'notfound'. This is not used but is here
/// for aesthetic purposes.</param>
/// <returns>A <see cref="PartialViewResult"/> if the request is an Ajax request, otherwise returns a full
/// <see cref="ViewResult"/> containing the error view.</returns>
[ResponseCache(CacheProfileName = CacheProfileName.Error)]
[HttpGet("{statusCode:int:range(200, 599)}/{status?}", Name = ErrorControllerRoute.GetError)]
public IActionResult Error(int statusCode, string status)
{
this.Response.StatusCode = statusCode;
ActionResult result;
if (this.Request.IsAjaxRequest())
{
// This allows us to show errors even in partial views.
result = this.PartialView(ErrorControllerAction.Error, statusCode);
}
else
{
result = this.View(ErrorControllerAction.Error, statusCode);
}
return result;
}
#endregion
}
} | mit | C# |
13b9a7bf6e3709ca7be1c23de8b243e55cd3b3a1 | fix typo in monero | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Shared/Monero/MoneroSyncSummary.cshtml | BTCPayServer/Views/Shared/Monero/MoneroSyncSummary.cshtml | @using BTCPayServer.Services.Altcoins.Monero.Services
@inject MoneroRPCProvider MoneroRpcProvider
@inject SignInManager<ApplicationUser> SignInManager;
@if (SignInManager.IsSignedIn(User) && User.IsInRole(Roles.ServerAdmin) && MoneroRpcProvider.Summaries.Any())
{
@foreach (var summary in MoneroRpcProvider.Summaries)
{
@if (summary.Value != null)
{
<h4>@summary.Key</h4>
<ul >
<li >Node available: @summary.Value.DaemonAvailable</li>
<li >Wallet available: @summary.Value.WalletAvailable</li>
<li >Last updated: @summary.Value.UpdatedAt</li>
<li >Synced: @summary.Value.Synced (@summary.Value.CurrentHeight / @summary.Value.TargetHeight)</li>
</ul>
}
}
}
| @using BTCPayServer.Services.Altcoins.Monero.Services
@inject MoneroRPCProvider MoneroRpcProvider
@inject SignInManager<ApplicationUser> SignInManager;
@if (SignInManager.IsSignedIn(User) && User.IsInRole(Roles.ServerAdmin) && MoneroRpcProvider.Summaries.Any())
{
@foreach (var summary in MoneroRpcProvider.Summaries)
{
@if (summary.Value != null)
{
<h4>@summary.Key</h4>
<ul >
<li >Node available: @summary.Value.DaemonAvailable</li>
<li >Wallet available: @summary.Value.WalletAvailable</li>
<li >Last updated: @summary.Value.UpdatedAt</li>
<li >Synced: @summary.Value.Synced (@summary.Value..CurrentHeight / @summary.Value.TargetHeight)</li>
</ul>
}
}
}
| mit | C# |
614dc8f4d19e6a0c618fa1ba42ff1e6b6979883e | Fix U4-2711 add Null Check to ToXMl method | mittonp/Umbraco-CMS,AndyButland/Umbraco-CMS,VDBBjorn/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,engern/Umbraco-CMS,aaronpowell/Umbraco-CMS,m0wo/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,rajendra1809/Umbraco-CMS,gavinfaux/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,m0wo/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mattbrailsford/Umbraco-CMS,iahdevelop/Umbraco-CMS,rustyswayne/Umbraco-CMS,TimoPerplex/Umbraco-CMS,aadfPT/Umbraco-CMS,kgiszewski/Umbraco-CMS,nvisage-gf/Umbraco-CMS,DaveGreasley/Umbraco-CMS,madsoulswe/Umbraco-CMS,gavinfaux/Umbraco-CMS,Pyuuma/Umbraco-CMS,kgiszewski/Umbraco-CMS,neilgaietto/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,mittonp/Umbraco-CMS,gkonings/Umbraco-CMS,Door3Dev/HRI-Umbraco,AndyButland/Umbraco-CMS,Door3Dev/HRI-Umbraco,countrywide/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,romanlytvyn/Umbraco-CMS,gregoriusxu/Umbraco-CMS,ordepdev/Umbraco-CMS,wtct/Umbraco-CMS,KevinJump/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,Phosworks/Umbraco-CMS,Door3Dev/HRI-Umbraco,markoliver288/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,base33/Umbraco-CMS,Tronhus/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,qizhiyu/Umbraco-CMS,gkonings/Umbraco-CMS,timothyleerussell/Umbraco-CMS,lingxyd/Umbraco-CMS,ordepdev/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,VDBBjorn/Umbraco-CMS,Khamull/Umbraco-CMS,yannisgu/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,qizhiyu/Umbraco-CMS,rasmusfjord/Umbraco-CMS,AndyButland/Umbraco-CMS,VDBBjorn/Umbraco-CMS,Door3Dev/HRI-Umbraco,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,aaronpowell/Umbraco-CMS,KevinJump/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,arknu/Umbraco-CMS,TimoPerplex/Umbraco-CMS,timothyleerussell/Umbraco-CMS,madsoulswe/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,nvisage-gf/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,WebCentrum/Umbraco-CMS,jchurchley/Umbraco-CMS,Phosworks/Umbraco-CMS,marcemarc/Umbraco-CMS,gregoriusxu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arvaris/HRI-Umbraco,ordepdev/Umbraco-CMS,AzarinSergey/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,corsjune/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,TimoPerplex/Umbraco-CMS,arvaris/HRI-Umbraco,PeteDuncanson/Umbraco-CMS,corsjune/Umbraco-CMS,gkonings/Umbraco-CMS,christopherbauer/Umbraco-CMS,kasperhhk/Umbraco-CMS,tompipe/Umbraco-CMS,wtct/Umbraco-CMS,sargin48/Umbraco-CMS,yannisgu/Umbraco-CMS,DaveGreasley/Umbraco-CMS,countrywide/Umbraco-CMS,neilgaietto/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,gregoriusxu/Umbraco-CMS,engern/Umbraco-CMS,sargin48/Umbraco-CMS,tcmorris/Umbraco-CMS,lingxyd/Umbraco-CMS,zidad/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,christopherbauer/Umbraco-CMS,rasmusfjord/Umbraco-CMS,lars-erik/Umbraco-CMS,Tronhus/Umbraco-CMS,corsjune/Umbraco-CMS,base33/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,neilgaietto/Umbraco-CMS,Phosworks/Umbraco-CMS,romanlytvyn/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,markoliver288/Umbraco-CMS,kasperhhk/Umbraco-CMS,marcemarc/Umbraco-CMS,engern/Umbraco-CMS,rasmusfjord/Umbraco-CMS,KevinJump/Umbraco-CMS,DaveGreasley/Umbraco-CMS,NikRimington/Umbraco-CMS,m0wo/Umbraco-CMS,lingxyd/Umbraco-CMS,yannisgu/Umbraco-CMS,Tronhus/Umbraco-CMS,dawoe/Umbraco-CMS,engern/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,rajendra1809/Umbraco-CMS,neilgaietto/Umbraco-CMS,umbraco/Umbraco-CMS,AndyButland/Umbraco-CMS,neilgaietto/Umbraco-CMS,jchurchley/Umbraco-CMS,hfloyd/Umbraco-CMS,zidad/Umbraco-CMS,kasperhhk/Umbraco-CMS,zidad/Umbraco-CMS,markoliver288/Umbraco-CMS,leekelleher/Umbraco-CMS,AzarinSergey/Umbraco-CMS,lingxyd/Umbraco-CMS,countrywide/Umbraco-CMS,AzarinSergey/Umbraco-CMS,wtct/Umbraco-CMS,Khamull/Umbraco-CMS,rajendra1809/Umbraco-CMS,Phosworks/Umbraco-CMS,Tronhus/Umbraco-CMS,mittonp/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,corsjune/Umbraco-CMS,Phosworks/Umbraco-CMS,kasperhhk/Umbraco-CMS,tompipe/Umbraco-CMS,AzarinSergey/Umbraco-CMS,Pyuuma/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,sargin48/Umbraco-CMS,leekelleher/Umbraco-CMS,rustyswayne/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,Khamull/Umbraco-CMS,aadfPT/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,rustyswayne/Umbraco-CMS,mstodd/Umbraco-CMS,christopherbauer/Umbraco-CMS,yannisgu/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,nul800sebastiaan/Umbraco-CMS,bjarnef/Umbraco-CMS,jchurchley/Umbraco-CMS,qizhiyu/Umbraco-CMS,gkonings/Umbraco-CMS,romanlytvyn/Umbraco-CMS,markoliver288/Umbraco-CMS,VDBBjorn/Umbraco-CMS,iahdevelop/Umbraco-CMS,countrywide/Umbraco-CMS,rasmuseeg/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,arvaris/HRI-Umbraco,VDBBjorn/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,kgiszewski/Umbraco-CMS,ehornbostel/Umbraco-CMS,Spijkerboer/Umbraco-CMS,NikRimington/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,christopherbauer/Umbraco-CMS,qizhiyu/Umbraco-CMS,hfloyd/Umbraco-CMS,arvaris/HRI-Umbraco,mstodd/Umbraco-CMS,mstodd/Umbraco-CMS,markoliver288/Umbraco-CMS,ehornbostel/Umbraco-CMS,markoliver288/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,tcmorris/Umbraco-CMS,aaronpowell/Umbraco-CMS,tcmorris/Umbraco-CMS,nvisage-gf/Umbraco-CMS,countrywide/Umbraco-CMS,rajendra1809/Umbraco-CMS,Pyuuma/Umbraco-CMS,tcmorris/Umbraco-CMS,zidad/Umbraco-CMS,m0wo/Umbraco-CMS,DaveGreasley/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,Spijkerboer/Umbraco-CMS,robertjf/Umbraco-CMS,Door3Dev/HRI-Umbraco,mittonp/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,nvisage-gf/Umbraco-CMS,christopherbauer/Umbraco-CMS,rustyswayne/Umbraco-CMS,zidad/Umbraco-CMS,wtct/Umbraco-CMS,rasmusfjord/Umbraco-CMS,leekelleher/Umbraco-CMS,rustyswayne/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mittonp/Umbraco-CMS,base33/Umbraco-CMS,TimoPerplex/Umbraco-CMS,ehornbostel/Umbraco-CMS,AzarinSergey/Umbraco-CMS,mattbrailsford/Umbraco-CMS,iahdevelop/Umbraco-CMS,abjerner/Umbraco-CMS,ordepdev/Umbraco-CMS,abryukhov/Umbraco-CMS,mstodd/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,romanlytvyn/Umbraco-CMS,Spijkerboer/Umbraco-CMS,romanlytvyn/Umbraco-CMS,engern/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,timothyleerussell/Umbraco-CMS,robertjf/Umbraco-CMS,AndyButland/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,m0wo/Umbraco-CMS,TimoPerplex/Umbraco-CMS,sargin48/Umbraco-CMS,ehornbostel/Umbraco-CMS,gavinfaux/Umbraco-CMS,iahdevelop/Umbraco-CMS,robertjf/Umbraco-CMS,ordepdev/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,gavinfaux/Umbraco-CMS,rasmusfjord/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,nvisage-gf/Umbraco-CMS,gkonings/Umbraco-CMS,mattbrailsford/Umbraco-CMS,DaveGreasley/Umbraco-CMS,lingxyd/Umbraco-CMS,Pyuuma/Umbraco-CMS,sargin48/Umbraco-CMS,timothyleerussell/Umbraco-CMS,aadfPT/Umbraco-CMS,corsjune/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,kasperhhk/Umbraco-CMS,Khamull/Umbraco-CMS,WebCentrum/Umbraco-CMS,qizhiyu/Umbraco-CMS,Tronhus/Umbraco-CMS,Khamull/Umbraco-CMS,wtct/Umbraco-CMS,iahdevelop/Umbraco-CMS,robertjf/Umbraco-CMS,gavinfaux/Umbraco-CMS,bjarnef/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,Pyuuma/Umbraco-CMS,mstodd/Umbraco-CMS,gregoriusxu/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,gregoriusxu/Umbraco-CMS,timothyleerussell/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,rajendra1809/Umbraco-CMS,yannisgu/Umbraco-CMS,ehornbostel/Umbraco-CMS,dawoe/Umbraco-CMS | src/umbraco.editorControls/imagecropper/DataTypeData.cs | src/umbraco.editorControls/imagecropper/DataTypeData.cs | using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value!=null && Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
} | using System.Xml;
namespace umbraco.editorControls.imagecropper
{
public class DataTypeData : umbraco.cms.businesslogic.datatype.DefaultData
{
public DataTypeData(umbraco.cms.businesslogic.datatype.BaseDataType DataType) : base(DataType) { }
public override XmlNode ToXMl(XmlDocument data)
{
if (Value.ToString() != "") {
XmlDocument xd = new XmlDocument();
xd.LoadXml(Value.ToString());
return data.ImportNode(xd.DocumentElement, true);
} else {
return base.ToXMl(data);
}
}
}
} | mit | C# |
f65191f308b43dab8a70f3c702c36047fab3a364 | Handle console app exception | marcosnz/SmallestDotNet,shanselman/SmallestDotNet,shanselman/SmallestDotNet,marcosnz/SmallestDotNet | CheckForDotNet45/Program.cs | CheckForDotNet45/Program.cs | using Microsoft.Win32;
namespace CheckForDotNet45
{
using System;
using System.Diagnostics;
class Program
{
const string site = "http://smallestdotnet.com/?realversion={0}";
static void Main(string[] args)
{
Console.Write("Checking .NET version...");
string version = IsNet45OrNewer() ? Get45or451FromRegistry() : Environment.Version.ToString();
try
{
Process.Start(String.Format(site, version));
}
catch (Exception)
{
Console.WriteLine("\nApplication was unable to launch browser");
Console.WriteLine("Your current .NET version is: " + version);
Console.ReadLine(); //Pause
}
}
public static bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists in .NET 4.5 .
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
//Improved but based on http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx#net_d
private static string Get45or451FromRegistry()
{
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
{
var releaseKey = (int)ndpKey.GetValue("Release");
{
if (releaseKey == 378389)
return "4.5";
if (releaseKey == 378758 || releaseKey == 378675)
return "4.5.1";
if (releaseKey == 379893)
return "4.5.2";
}
}
return "4.5";
}
}
}
| using Microsoft.Win32;
namespace CheckForDotNet45
{
using System;
using System.Diagnostics;
class Program
{
const string site = "http://smallestdotnet.com/?realversion={0}";
static void Main(string[] args)
{
Console.Write("Checking .NET version...");
if (IsNet45OrNewer())
{
Process.Start(String.Format(site, Get45or451FromRegistry()));
}
else
Process.Start(String.Format(site, Environment.Version.ToString()));
}
public static bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists in .NET 4.5 .
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
//Improved but based on http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx#net_d
private static string Get45or451FromRegistry()
{
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
{
var releaseKey = (int)ndpKey.GetValue("Release");
{
if (releaseKey == 378389)
return "4.5";
if (releaseKey == 378758 || releaseKey == 378675)
return "4.5.1";
if (releaseKey == 379893)
return "4.5.2";
}
}
return "4.5";
}
}
}
| mit | C# |
4afc150f1e2fd431a2d69e38bd010e18db011474 | make sure we are on the UIThread before calling GetPythonToolsServer() (#6228) | int19h/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,int19h/PTVS | Python/Product/PythonTools/PythonTools/Environments/UserSpecifiedCondaLocator.cs | Python/Product/PythonTools/PythonTools/Environments/UserSpecifiedCondaLocator.cs | // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel.Composition;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Environments {
/// <summary>
/// Conda locator that returns the path to the conda executable
/// specified by the user in tools/options/python/conda page.
/// This is the highest priority locator because it respects
/// the user's choice.
/// </summary>
[Export(typeof(ICondaLocator))]
[ExportMetadata("Priority", 100)]
sealed class UserSpecifiedCondaLocator : ICondaLocator {
private readonly IServiceProvider _site;
[ImportingConstructor]
public UserSpecifiedCondaLocator(
[Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null
) {
_site = site;
}
public string CondaExecutablePath {
get {
return _site?.GetUIThread().Invoke(() =>
_site?.GetPythonToolsService()?.CondaOptions.CustomCondaExecutablePath
);
}
}
}
}
| // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel.Composition;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.Environments {
/// <summary>
/// Conda locator that returns the path to the conda executable
/// specified by the user in tools/options/python/conda page.
/// This is the highest priority locator because it respects
/// the user's choice.
/// </summary>
[Export(typeof(ICondaLocator))]
[ExportMetadata("Priority", 100)]
sealed class UserSpecifiedCondaLocator : ICondaLocator {
private readonly IServiceProvider _site;
[ImportingConstructor]
public UserSpecifiedCondaLocator(
[Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null
) {
_site = site;
}
public string CondaExecutablePath {
get {
return _site?.GetPythonToolsService()?.CondaOptions.CustomCondaExecutablePath;
}
}
}
}
| apache-2.0 | C# |
fcbf5c7585b27fc83b25ab4410e8a1567afeed10 | Make SA0000 hidden but enabled by default | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/SpecialRules/SA0000Roslyn7446Workaround.cs | StyleCop.Analyzers/StyleCop.Analyzers/SpecialRules/SA0000Roslyn7446Workaround.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.SpecialRules
{
using System;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class SA0000Roslyn7446Workaround : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA0000Roslyn7446Workaround"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA0000";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(SpecialResources.SA0000Title), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(SpecialResources.SA0000MessageFormat), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(SpecialResources.SA0000Description), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0000Roslyn7446Workaround.md";
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.SpecialRules, DiagnosticSeverity.Hidden, AnalyzerConstants.EnabledByDefault, Description, HelpLink);
private static readonly Action<CompilationStartAnalysisContext> CompilationStartAction = HandleCompilationStart;
private static readonly bool CallGetDeclarationDiagnostics;
static SA0000Roslyn7446Workaround()
{
// dotnet/roslyn#7446 was fixed for Roslyn 1.2
CallGetDeclarationDiagnostics = typeof(AdditionalText).GetTypeInfo().Assembly.GetName().Version < new Version(1, 2, 0, 0);
}
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
if (!CallGetDeclarationDiagnostics)
{
return;
}
context.RegisterCompilationStartAction(CompilationStartAction);
}
#pragma warning disable RS1012 // Start action has no registered actions.
private static void HandleCompilationStart(CompilationStartAnalysisContext context)
#pragma warning restore RS1012 // Start action has no registered actions.
{
context.Compilation.GetDeclarationDiagnostics(context.CancellationToken);
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.SpecialRules
{
using System;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class SA0000Roslyn7446Workaround : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA0000Roslyn7446Workaround"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA0000";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(SpecialResources.SA0000Title), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(SpecialResources.SA0000MessageFormat), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(SpecialResources.SA0000Description), SpecialResources.ResourceManager, typeof(SpecialResources));
private static readonly string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0000Roslyn7446Workaround.md";
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.SpecialRules, DiagnosticSeverity.Info, AnalyzerConstants.DisabledByDefault, Description, HelpLink);
private static readonly Action<CompilationStartAnalysisContext> CompilationStartAction = HandleCompilationStart;
private static readonly bool CallGetDeclarationDiagnostics;
static SA0000Roslyn7446Workaround()
{
// dotnet/roslyn#7446 was fixed for Roslyn 1.2
CallGetDeclarationDiagnostics = typeof(AdditionalText).GetTypeInfo().Assembly.GetName().Version < new Version(1, 2, 0, 0);
}
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
if (!CallGetDeclarationDiagnostics)
{
return;
}
context.RegisterCompilationStartAction(CompilationStartAction);
}
#pragma warning disable RS1012 // Start action has no registered actions.
private static void HandleCompilationStart(CompilationStartAnalysisContext context)
#pragma warning restore RS1012 // Start action has no registered actions.
{
context.Compilation.GetDeclarationDiagnostics(context.CancellationToken);
}
}
}
| mit | C# |
62b473b87c58720ba744f7d3d9bdf7c7b5c7f2eb | change link to button "comment" | ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth | GalleryMVC_With_Auth/Views/Shared/_GalleryPartial.cshtml | GalleryMVC_With_Auth/Views/Shared/_GalleryPartial.cshtml | @using GalleryMVC_With_Auth.Domain.Entities
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls">
<div class="slides"></div>
<h3 class="title"></h3>
<a class="prev">‹</a>
<a class="next">›</a>
<a class="close">×</a>
<a class="play-pause"></a>
<ol class="indicator"></ol>
</div>
<div class="grid">
<div id="links">
@foreach (Picture picture in Model)
{
<figure class="effect-milo">
<img class="lazy" data-original="@picture.TmbPath" alt="@picture.Description"/>
<figcaption>
<h2>
<span>@picture.Description</span></h2>
<p style="color: red">Автор - @picture.Name.</p>
<p style="color: red">Тэг - @picture.Tag.Name</p>
<p style="color: red">Цена - @picture.Price бел.руб.</p>
<a class="pic" id="links" href="@picture.Path" title="@picture.Name"></a>
</figcaption>
</figure>
<button type="button" class="btn btn-danger" onclick="location.href = '@Url.Action("Comments", "Images", new {@picture.Id})'">Комментарии</button>
@*<a style="margin: 10px" href="@Url.Action("Comments", "Images", new {@picture.Id})" onclick="location.href = '@Url.Action("Comments", "Images", new {@picture.Id})'">Комментарии</a>*@
@*@Html.ActionLink("comments", "Comments", "Images", new {picture.Id}, new {@class = "comment", onclick= "window.open(url)" })*@
}
</div>
</div>
<script>
$(function() {
$("img.lazy").lazyload({
effect: "fadeIn"
});
});
</script> | @using GalleryMVC_With_Auth.Domain.Entities
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls">
<div class="slides"></div>
<h3 class="title"></h3>
<a class="prev">‹</a>
<a class="next">›</a>
<a class="close">×</a>
<a class="play-pause"></a>
<ol class="indicator"></ol>
</div>
<div class="grid">
<div id="links">
@foreach (Picture picture in Model)
{
<figure class="effect-milo">
<img class="lazy" data-original="@picture.TmbPath" alt="@picture.Description"/>
<figcaption>
<h2>
<span>@picture.Description</span></h2>
<p style="color: red">Автор - @picture.Name.</p>
<p style="color: red">Тэг - @picture.Tag.Name</p>
<p style="color: red">Цена - @picture.Price бел.руб.</p>
<a class="pic" id="links" href="@picture.Path" title="@picture.Name"></a>
</figcaption>
</figure>
<a style="margin: 10px" href="@Url.Action("Comments", "Images", new {@picture.Id})" onclick="location.href = '@Url.Action("Comments", "Images", new {@picture.Id})'">Комментарии</a>
@*@Html.ActionLink("comments", "Comments", "Images", new {picture.Id}, new {@class = "comment", onclick= "window.open(url)" })*@
}
</div>
</div>
<script>
$(function() {
$("img.lazy").lazyload({
effect: "fadeIn"
});
});
</script> | apache-2.0 | C# |
e8f6ec469cdf8a617ddb91dd4d30d5bb38ee29ae | Fix warnings. | JohanLarsson/Gu.ChangeTracking | Gu.State.Tests/DiffTests/DiffBuilder/DiffBuilderTests.cs | Gu.State.Tests/DiffTests/DiffBuilder/DiffBuilderTests.cs | // ReSharper disable RedundantArgumentDefaultValue
namespace Gu.State.Tests.DiffTests
{
using NUnit.Framework;
using static DiffTypes;
public class DiffBuilderTests
{
[Test]
public void ReturnsSameWhileAlive()
{
var x = new ComplexType();
var y = new ComplexType();
var structuralSettings = PropertiesSettings.GetOrCreate(ReferenceHandling.Structural);
var t1 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
var t2 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
Assert.AreSame(t1, t2);
#pragma warning disable IDISP016 // Don't use disposed instance
t1.Dispose();
#pragma warning restore IDISP016 // Don't use disposed instance
t2.Dispose();
using var t4 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
Assert.AreNotSame(t1, t4);
}
[Test]
public void ReturnsDifferentForDifferentSettings()
{
var x = new ComplexType();
var y = new ComplexType();
using var t1 = DiffBuilder.GetOrCreate(x, y, PropertiesSettings.GetOrCreate(ReferenceHandling.Structural));
using var t2 = DiffBuilder.GetOrCreate(x, y, PropertiesSettings.GetOrCreate(ReferenceHandling.Throw));
Assert.AreNotSame(t1, t2);
}
[Test]
public void ReturnsDifferentForDifferentPairs()
{
var x = new ComplexType();
var y = new ComplexType();
var structuralSettings = PropertiesSettings.GetOrCreate(ReferenceHandling.Structural);
using var t1 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
using var t2 = DiffBuilder.GetOrCreate(y, x, structuralSettings);
Assert.AreNotSame(t1, t2);
}
}
}
| // ReSharper disable RedundantArgumentDefaultValue
namespace Gu.State.Tests.DiffTests
{
using NUnit.Framework;
using static DiffTypes;
public class DiffBuilderTests
{
[Test]
public void ReturnsSameWhileAlive()
{
var x = new ComplexType();
var y = new ComplexType();
var structuralSettings = PropertiesSettings.GetOrCreate(ReferenceHandling.Structural);
using var t1 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
using (var t2 = DiffBuilder.GetOrCreate(x, y, structuralSettings))
{
Assert.AreSame(t1, t2);
t1.Dispose();
t2.Dispose();
}
using var t4 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
Assert.AreNotSame(t1, t4);
}
[Test]
public void ReturnsDifferentForDifferentSettings()
{
var x = new ComplexType();
var y = new ComplexType();
using var t1 = DiffBuilder.GetOrCreate(x, y, PropertiesSettings.GetOrCreate(ReferenceHandling.Structural));
using var t2 = DiffBuilder.GetOrCreate(x, y, PropertiesSettings.GetOrCreate(ReferenceHandling.Throw));
Assert.AreNotSame(t1, t2);
}
[Test]
public void ReturnsDifferentForDifferentPairs()
{
var x = new ComplexType();
var y = new ComplexType();
var structuralSettings = PropertiesSettings.GetOrCreate(ReferenceHandling.Structural);
using var t1 = DiffBuilder.GetOrCreate(x, y, structuralSettings);
using var t2 = DiffBuilder.GetOrCreate(y, x, structuralSettings);
Assert.AreNotSame(t1, t2);
}
}
}
| mit | C# |
6bce0313170372a1d60cdb90be7b6462990e9901 | Improve unit tests | DaveSenn/Extend | PortableExtensions.Testing/System.DateTime/DateTime.Age.Test.cs | PortableExtensions.Testing/System.DateTime/DateTime.Age.Test.cs | #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class DateTimeExTest
{
[Test]
public void AgeTestCase()
{
var dateTime = new DateTime(1980, 1, 1);
var expected = DateTime.Now.Year - 1980;
var actual = dateTime.Age();
Assert.AreEqual(expected, actual);
dateTime = DateTime.Now.AddYears(-2).Add(1.ToDays());
expected = 1;
actual = dateTime.Age();
Assert.AreEqual(expected, actual);
}
[Test]
public void AgeTestCase1()
{
var dateTime = DateTime.Now.AddYears(-2).Add(1.ToDays());
const Int32 expected = 1;
var actual = dateTime.Age();
Assert.AreEqual(expected, actual);
}
[Test]
public void AgeTestCase2()
{
var dateTime = DateTime.Now.AddYears(-1).AddMonths(-3);
const Int32 expected = 1;
var actual = dateTime.Age();
Assert.AreEqual(expected, actual);
}
[Test]
public void AgeTestCase3()
{
var dateTime = DateTime.Now.AddDays(1);
const Int32 expected = -1;
var actual = dateTime.Age();
Assert.AreEqual(expected, actual);
}
[Test]
public void AgeTestCase4()
{
var dateTime = DateTime.Now.AddYears(3);
const Int32 expected = -3;
var actual = dateTime.Age();
Assert.AreEqual(expected, actual);
}
}
}
| #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class DateTimeExTest
{
[Test]
public void AgeTestCase()
{
var dateTime = new DateTime( 1980, 1, 1 );
var expected = DateTime.Now.Year - 1980;
var actual = dateTime.Age();
Assert.AreEqual( expected, actual );
dateTime = DateTime.Now.AddYears( -2 ).Add( 1.ToDays() );
expected = 1;
actual = dateTime.Age();
Assert.AreEqual( expected, actual );
}
}
} | mit | C# |
567a9b38a37ea4d22f649c62a13cee1445615f48 | Use two shift registers with two bar graphs and an collection | treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk | NET/Libraries/Demos/Displays/LedShiftRegister/Program.cs | NET/Libraries/Demos/Displays/LedShiftRegister/Program.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[9], board.Pwm1, LedShiftRegister.LedChannelCount.SixteenChannel, 0.1);
var driver2 = new LedShiftRegister(driver, LedShiftRegister.LedChannelCount.SixteenChannel);
driver.Brightness = 0.01;
var leds = driver.Leds.Concat(driver2.Leds);
var ledSet1 = leds.Take(8).Concat(leds.Skip(16).Take(8)).ToList();
var ledSet2 = leds.Skip(8).Take(8).Reverse().Concat(leds.Skip(24).Take(8).Reverse()).ToList();
var bar1 = new BarGraph(ledSet1);
var bar2 = new BarGraph(ledSet2);
var collection = new LedDisplayCollection();
collection.Add(bar1);
collection.Add(bar2);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 16; i++)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
for (int i = 16; i >= 0; i--)
{
bar1.Value = i / 16.0;
bar2.Value = i / 16.0;
await collection.Flush();
await Task.Delay(10);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
| using System;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries.Displays;
namespace LedShiftRegisterDemo
{
class Program
{
static void Main(string[] args)
{
App().Wait();
}
static async Task App()
{
var board = await ConnectionService.Instance.GetFirstDeviceAsync();
await board.ConnectAsync();
Console.WriteLine("Connected to " + board);
var driver = new LedShiftRegister(board.Spi, board.Pins[5], board.Pwm1);
driver.Brightness = 0.01;
var bar = new BarGraph(driver.Leds);
while (!Console.KeyAvailable)
{
for (int i = 1; i < 10; i++)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
for (int i = 10; i >= 0; i--)
{
bar.Value = i / 10.0;
await Task.Delay(50);
}
await Task.Delay(100);
}
board.Disconnect();
}
}
}
| mit | C# |
d9abb710fbda11e3be843262f1e72e5acd8ec4af | fix Upgrade_20211112_FixBootstrap for .net 5 | signumsoftware/framework,signumsoftware/framework | Signum.Upgrade/Upgrades/Upgrade_20211112_FixBootstrap.cs | Signum.Upgrade/Upgrades/Upgrade_20211112_FixBootstrap.cs | namespace Signum.Upgrade.Upgrades
{
class Upgrade_20211112_FixBootstrap : CodeUpgradeBase
{
public override string Description => "Set Production mode";
public override void Execute(UpgradeContext uctx)
{
uctx.ChangeCodeFile($@"Southwind.React\Dockerfile", file =>
{
file.Replace("build-development", "build-production");
});
uctx.ChangeCodeFile($@"Southwind.React\App\Layout.tsx", file =>
{
file.Replace("supportIE = true", "supportIE = false");
});
uctx.ChangeCodeFile($@"Southwind.React\App\SCSS\custom.scss", file =>
{
file.InsertAfterFirstLine(a => a.Contains(@"@import ""./_bootswatch"";"), @".btn.input-group-text{
background: $input-group-addon-bg;
border: $input-border-width solid $input-group-addon-border-color
}");
});
uctx.ChangeCodeFile(@$"Southwind.React\package.json", file =>
{
file.Replace(
@"webpack --config webpack.config.polyfills.js webpack --config webpack.config.dll.js --mode=production",
@"webpack --config webpack.config.polyfills.js --mode=production && webpack --config webpack.config.dll.js --mode=production");
});
}
}
}
| namespace Signum.Upgrade.Upgrades;
class Upgrade_20211112_FixBootstrap : CodeUpgradeBase
{
public override string Description => "Set Production mode";
public override void Execute(UpgradeContext uctx)
{
uctx.ChangeCodeFile($@"Southwind.React\Dockerfile", file =>
{
file.Replace("build-development", "build-production");
});
uctx.ChangeCodeFile($@"Southwind.React\App\Layout.tsx", file =>
{
file.Replace("supportIE = true", "supportIE = false");
});
uctx.ChangeCodeFile($@"Southwind.React\App\SCSS\custom.scss", file =>
{
file.InsertAfterFirstLine(a => a.Contains(@"@import ""./_bootswatch"";"), @".btn.input-group-text{
background: $input-group-addon-bg;
border: $input-border-width solid $input-group-addon-border-color
}");
});
uctx.ChangeCodeFile(@$"Southwind.React\package.json", file =>
{
file.Replace(
@"webpack --config webpack.config.polyfills.js webpack --config webpack.config.dll.js --mode=production",
@"webpack --config webpack.config.polyfills.js --mode=production && webpack --config webpack.config.dll.js --mode=production")
});
}
}
| mit | C# |
53c968e137488ba4719f5241d0edb3d32940ece3 | Fix user profile best performance weighting being out of order | NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game/Overlays/Profile/Sections/Ranks/PaginatedScoreContainer.cs | osu.Game/Overlays/Profile/Sections/Ranks/PaginatedScoreContainer.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests;
using osu.Game.Users;
using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Online.API.Requests.Responses;
using System.Collections.Generic;
using osu.Game.Online.API;
using osu.Framework.Allocation;
namespace osu.Game.Overlays.Profile.Sections.Ranks
{
public class PaginatedScoreContainer : PaginatedContainer<APILegacyScoreInfo>
{
private readonly ScoreType type;
public PaginatedScoreContainer(ScoreType type, Bindable<User> user, string headerText, CounterVisibilityState counterVisibilityState, string missingText = "")
: base(user, headerText, missingText, counterVisibilityState)
{
this.type = type;
ItemsPerPage = 5;
}
[BackgroundDependencyLoader]
private void load()
{
ItemsContainer.Direction = FillDirection.Vertical;
}
protected override int GetCount(User user)
{
switch (type)
{
case ScoreType.Firsts:
return user.ScoresFirstCount;
default:
return 0;
}
}
protected override void OnItemsReceived(List<APILegacyScoreInfo> items)
{
if (VisiblePages == 0)
drawableItemIndex = 0;
base.OnItemsReceived(items);
if (type == ScoreType.Recent)
SetCount(items.Count);
}
protected override APIRequest<List<APILegacyScoreInfo>> CreateRequest() =>
new GetUserScoresRequest(User.Value.Id, type, VisiblePages++, ItemsPerPage);
private int drawableItemIndex;
protected override Drawable CreateDrawableItem(APILegacyScoreInfo model)
{
switch (type)
{
default:
return new DrawableProfileScore(model.CreateScoreInfo(Rulesets));
case ScoreType.Best:
return new DrawableProfileWeightedScore(model.CreateScoreInfo(Rulesets), Math.Pow(0.95, drawableItemIndex++));
}
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests;
using osu.Game.Users;
using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Online.API.Requests.Responses;
using System.Collections.Generic;
using osu.Game.Online.API;
using osu.Framework.Allocation;
namespace osu.Game.Overlays.Profile.Sections.Ranks
{
public class PaginatedScoreContainer : PaginatedContainer<APILegacyScoreInfo>
{
private readonly ScoreType type;
public PaginatedScoreContainer(ScoreType type, Bindable<User> user, string headerText, CounterVisibilityState counterVisibilityState, string missingText = "")
: base(user, headerText, missingText, counterVisibilityState)
{
this.type = type;
ItemsPerPage = 5;
}
[BackgroundDependencyLoader]
private void load()
{
ItemsContainer.Direction = FillDirection.Vertical;
}
protected override int GetCount(User user)
{
switch (type)
{
case ScoreType.Firsts:
return user.ScoresFirstCount;
default:
return 0;
}
}
protected override void OnItemsReceived(List<APILegacyScoreInfo> items)
{
base.OnItemsReceived(items);
if (type == ScoreType.Recent)
SetCount(items.Count);
}
protected override APIRequest<List<APILegacyScoreInfo>> CreateRequest() =>
new GetUserScoresRequest(User.Value.Id, type, VisiblePages++, ItemsPerPage);
protected override Drawable CreateDrawableItem(APILegacyScoreInfo model)
{
switch (type)
{
default:
return new DrawableProfileScore(model.CreateScoreInfo(Rulesets));
case ScoreType.Best:
return new DrawableProfileWeightedScore(model.CreateScoreInfo(Rulesets), Math.Pow(0.95, ItemsContainer.Count));
}
}
}
}
| mit | C# |
4e89e752ae2c019290fd17f583b4f34fd83da339 | Update Client project. Add new samples | mikgam/MusicBrainz,avatar29A/MusicBrainz,wo80/MusicBrainz | Hqub.MusicBrainze.API/Hqub.MusicBrainze.Client/Program.cs | Hqub.MusicBrainze.API/Hqub.MusicBrainze.Client/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Hqub.MusicBrainz.API.Entities;
namespace Hqub.MusicBrainz.Client
{
internal class Program
{
private static void Main(string[] args)
{
ShowTracksByAlbum("Король и Шут", "Акустический альбом");
// ShowAlbumsTracksByArtist("Король и Шут");
Console.ReadKey();
}
private static Artist GetArtist(string name)
{
var artists = Artist.Search(name);
var artist = artists.First();
Console.WriteLine(artist.Name);
return artist;
}
private static async void ShowTracksByAlbum(string artistName, string albumName)
{
var artist = GetArtist(artistName);
var albums = await Release.BrowseAsync("artist", artist.Id);
var album = albums.FirstOrDefault(r => r.Title.ToLower() == albumName.ToLower());
if (album == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Album not found.\n");
Console.ResetColor();
Console.WriteLine("Results:\n");
foreach (var al in albums)
{
Console.WriteLine("\t{0}", al.Title);
}
return;
}
Console.WriteLine("\t{0}", albumName);
var tracks = await Recording.BrowseAsync("release", album.Id, 100);
foreach (var track in tracks)
{
Console.WriteLine("\t\t{0}", track.Title);
}
}
private static async void ShowAlbumsTracksByArtist(string name)
{
var artist = GetArtist(name);
var releases = await Release.BrowseAsync("artist", artist.Id, 100, 0, "media");
foreach (var release in releases)
{
Console.WriteLine("\t{0}", release.Title);
var tracks = await Recording.BrowseAsync("release", release.Id, 100);
foreach (var track in tracks)
{
Console.WriteLine("\t\t{0}", track.Title);
}
}
}
private static async void Test()
{
var artists = Artist.Search("The Scorpions");
var artist = artists.First();
Console.WriteLine(artist.Name);
var releases = await Recording.BrowseAsync("artist", artist.Id, 40);
foreach (var release in releases)
{
Console.WriteLine("{0}", release.Title);
}
//
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Hqub.MusicBrainz.API.Entities;
namespace Hqub.MusicBrainz.Client
{
internal class Program
{
private static void Main(string[] args)
{
Test();
Console.WriteLine("OK");
Console.ReadKey();
}
private static async void Test()
{
var artists = Artist.Search("The Scorpions");
var artist = artists.First();
Console.WriteLine(artist.Name);
var releases = await Recording.BrowseAsync("artist", artist.Id, 40);
foreach (var release in releases)
{
Console.WriteLine("{0}", release.Title);
}
//
}
}
}
| mit | C# |
2fef9efd50817e0460b965b6594ad0c6b6c646c1 | Add test for authorization requirement in TraktUserListLikeRequest | henrikfroehling/TraktApiSharp | Source/Tests/TraktApiSharp.Tests/Experimental/Requests/Users/OAuth/TraktUserListLikeRequestTests.cs | Source/Tests/TraktApiSharp.Tests/Experimental/Requests/Users/OAuth/TraktUserListLikeRequestTests.cs | namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestHasAuthorizationRequired()
{
var request = new TraktUserListLikeRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
| namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
[TestClass]
public class TraktUserListLikeRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsNotAbstract()
{
typeof(TraktUserListLikeRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSealed()
{
typeof(TraktUserListLikeRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserListLikeRequestIsSubclassOfATraktNoContentBodylessPostByIdRequest()
{
typeof(TraktUserListLikeRequest).IsSubclassOf(typeof(ATraktNoContentBodylessPostByIdRequest)).Should().BeTrue();
}
}
}
| mit | C# |
64489f329d3362946db5261a69a168dd3c87ab30 | Refresh interface list on change | tewarid/net-tools,tewarid/NetTools | Common/InterfaceSelector.cs | Common/InterfaceSelector.cs | using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
Initalize();
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
private void Initalize()
{
if (InvokeRequired)
{
BeginInvoke((MethodInvoker)Initalize);
return;
}
Items.Clear();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Initalize();
}
private void NetworkChange_NetworkAddressChanged(object sender, System.EventArgs e)
{
Initalize();
}
}
}
| using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Common
{
public partial class InterfaceSelectorComboBox : ComboBox
{
public InterfaceSelectorComboBox()
{
InitializeComponent();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
UnicastIPAddressInformationCollection addresses = iface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation address in addresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
Items.Add(address.Address.ToString());
}
}
}
}
}
| mit | C# |
231b4097fcd3923b27a0fdfa51779affe5db7032 | Remove failing test. | jquintus/TeamCitySpike | AmazingApp/AmazingTests/ProgramTests.cs | AmazingApp/AmazingTests/ProgramTests.cs | using AmazingApp;
using NUnit.Framework;
namespace AmazingTests
{
[TestFixture]
public class ProgramTests
{
[Test]
public void Msg_IsHelloWorld()
{
Assert.AreEqual("Hello World", Program.Msg);
}
[Test]
public void Pass()
{
Assert.Pass();
}
}
} | using AmazingApp;
using NUnit.Framework;
namespace AmazingTests
{
[TestFixture]
public class ProgramTests
{
[Test]
public void Msg_IsHelloWorld()
{
Assert.AreEqual("Hello World", Program.Msg);
}
[Test]
public void Pass()
{
Assert.Pass();
}
[Test]
[Ignore]
public void Fail()
{
Assert.Fail();
}
}
} | mit | C# |
ee6e1a9d8bfe505fc9c73f09cf20f1b31f7e1e2c | Disable extra templates tree | Phosworks/Umbraco-CMS,lars-erik/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,leekelleher/Umbraco-CMS,Pyuuma/Umbraco-CMS,kasperhhk/Umbraco-CMS,leekelleher/Umbraco-CMS,TimoPerplex/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,qizhiyu/Umbraco-CMS,yannisgu/Umbraco-CMS,hfloyd/Umbraco-CMS,rajendra1809/Umbraco-CMS,lingxyd/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,gavinfaux/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,sargin48/Umbraco-CMS,markoliver288/Umbraco-CMS,hfloyd/Umbraco-CMS,christopherbauer/Umbraco-CMS,christopherbauer/Umbraco-CMS,mstodd/Umbraco-CMS,engern/Umbraco-CMS,aadfPT/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,Khamull/Umbraco-CMS,leekelleher/Umbraco-CMS,neilgaietto/Umbraco-CMS,ordepdev/Umbraco-CMS,bjarnef/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,jchurchley/Umbraco-CMS,yannisgu/Umbraco-CMS,dawoe/Umbraco-CMS,VDBBjorn/Umbraco-CMS,hfloyd/Umbraco-CMS,base33/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,yannisgu/Umbraco-CMS,ehornbostel/Umbraco-CMS,christopherbauer/Umbraco-CMS,Phosworks/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,dawoe/Umbraco-CMS,m0wo/Umbraco-CMS,AzarinSergey/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,qizhiyu/Umbraco-CMS,tompipe/Umbraco-CMS,rustyswayne/Umbraco-CMS,rasmusfjord/Umbraco-CMS,Spijkerboer/Umbraco-CMS,NikRimington/Umbraco-CMS,iahdevelop/Umbraco-CMS,romanlytvyn/Umbraco-CMS,Khamull/Umbraco-CMS,DaveGreasley/Umbraco-CMS,engern/Umbraco-CMS,Tronhus/Umbraco-CMS,Pyuuma/Umbraco-CMS,lingxyd/Umbraco-CMS,corsjune/Umbraco-CMS,robertjf/Umbraco-CMS,nvisage-gf/Umbraco-CMS,aadfPT/Umbraco-CMS,rustyswayne/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,jchurchley/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,umbraco/Umbraco-CMS,gavinfaux/Umbraco-CMS,nvisage-gf/Umbraco-CMS,qizhiyu/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,VDBBjorn/Umbraco-CMS,VDBBjorn/Umbraco-CMS,umbraco/Umbraco-CMS,DaveGreasley/Umbraco-CMS,m0wo/Umbraco-CMS,rustyswayne/Umbraco-CMS,kasperhhk/Umbraco-CMS,aaronpowell/Umbraco-CMS,Phosworks/Umbraco-CMS,corsjune/Umbraco-CMS,neilgaietto/Umbraco-CMS,corsjune/Umbraco-CMS,nvisage-gf/Umbraco-CMS,mstodd/Umbraco-CMS,ehornbostel/Umbraco-CMS,marcemarc/Umbraco-CMS,Phosworks/Umbraco-CMS,christopherbauer/Umbraco-CMS,aaronpowell/Umbraco-CMS,Pyuuma/Umbraco-CMS,iahdevelop/Umbraco-CMS,base33/Umbraco-CMS,corsjune/Umbraco-CMS,gkonings/Umbraco-CMS,gkonings/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,yannisgu/Umbraco-CMS,neilgaietto/Umbraco-CMS,arknu/Umbraco-CMS,AzarinSergey/Umbraco-CMS,gkonings/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,TimoPerplex/Umbraco-CMS,aadfPT/Umbraco-CMS,lars-erik/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,m0wo/Umbraco-CMS,TimoPerplex/Umbraco-CMS,ordepdev/Umbraco-CMS,ordepdev/Umbraco-CMS,marcemarc/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,Spijkerboer/Umbraco-CMS,KevinJump/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,kgiszewski/Umbraco-CMS,timothyleerussell/Umbraco-CMS,Tronhus/Umbraco-CMS,WebCentrum/Umbraco-CMS,AzarinSergey/Umbraco-CMS,dawoe/Umbraco-CMS,ehornbostel/Umbraco-CMS,KevinJump/Umbraco-CMS,Khamull/Umbraco-CMS,gavinfaux/Umbraco-CMS,m0wo/Umbraco-CMS,Spijkerboer/Umbraco-CMS,gregoriusxu/Umbraco-CMS,corsjune/Umbraco-CMS,kasperhhk/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,romanlytvyn/Umbraco-CMS,ordepdev/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,bjarnef/Umbraco-CMS,engern/Umbraco-CMS,TimoPerplex/Umbraco-CMS,NikRimington/Umbraco-CMS,Pyuuma/Umbraco-CMS,robertjf/Umbraco-CMS,rustyswayne/Umbraco-CMS,mstodd/Umbraco-CMS,qizhiyu/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,sargin48/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,iahdevelop/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,timothyleerussell/Umbraco-CMS,kgiszewski/Umbraco-CMS,dawoe/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,mstodd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,romanlytvyn/Umbraco-CMS,lingxyd/Umbraco-CMS,DaveGreasley/Umbraco-CMS,WebCentrum/Umbraco-CMS,VDBBjorn/Umbraco-CMS,hfloyd/Umbraco-CMS,mittonp/Umbraco-CMS,Spijkerboer/Umbraco-CMS,mattbrailsford/Umbraco-CMS,gregoriusxu/Umbraco-CMS,kgiszewski/Umbraco-CMS,DaveGreasley/Umbraco-CMS,rasmuseeg/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,engern/Umbraco-CMS,rasmusfjord/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,qizhiyu/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmusfjord/Umbraco-CMS,rajendra1809/Umbraco-CMS,timothyleerussell/Umbraco-CMS,AzarinSergey/Umbraco-CMS,neilgaietto/Umbraco-CMS,rasmusfjord/Umbraco-CMS,mittonp/Umbraco-CMS,Tronhus/Umbraco-CMS,kasperhhk/Umbraco-CMS,christopherbauer/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,lars-erik/Umbraco-CMS,engern/Umbraco-CMS,romanlytvyn/Umbraco-CMS,mittonp/Umbraco-CMS,lingxyd/Umbraco-CMS,nvisage-gf/Umbraco-CMS,neilgaietto/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,ordepdev/Umbraco-CMS,Khamull/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,Tronhus/Umbraco-CMS,m0wo/Umbraco-CMS,rajendra1809/Umbraco-CMS,romanlytvyn/Umbraco-CMS,markoliver288/Umbraco-CMS,Phosworks/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,timothyleerussell/Umbraco-CMS,tcmorris/Umbraco-CMS,markoliver288/Umbraco-CMS,tcmorris/Umbraco-CMS,sargin48/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,iahdevelop/Umbraco-CMS,rajendra1809/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,gregoriusxu/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,iahdevelop/Umbraco-CMS,tompipe/Umbraco-CMS,gavinfaux/Umbraco-CMS,TimoPerplex/Umbraco-CMS,timothyleerussell/Umbraco-CMS,gregoriusxu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,gregoriusxu/Umbraco-CMS,gavinfaux/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,rajendra1809/Umbraco-CMS,AzarinSergey/Umbraco-CMS,mstodd/Umbraco-CMS,Tronhus/Umbraco-CMS,lars-erik/Umbraco-CMS,aaronpowell/Umbraco-CMS,mattbrailsford/Umbraco-CMS,ehornbostel/Umbraco-CMS,yannisgu/Umbraco-CMS,robertjf/Umbraco-CMS,lingxyd/Umbraco-CMS,ehornbostel/Umbraco-CMS,tompipe/Umbraco-CMS,kasperhhk/Umbraco-CMS,rasmusfjord/Umbraco-CMS,jchurchley/Umbraco-CMS,gkonings/Umbraco-CMS,nvisage-gf/Umbraco-CMS,sargin48/Umbraco-CMS,Khamull/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,markoliver288/Umbraco-CMS,WebCentrum/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,gkonings/Umbraco-CMS,base33/Umbraco-CMS,sargin48/Umbraco-CMS,madsoulswe/Umbraco-CMS,VDBBjorn/Umbraco-CMS,markoliver288/Umbraco-CMS,mittonp/Umbraco-CMS,tcmorris/Umbraco-CMS,rustyswayne/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,DaveGreasley/Umbraco-CMS,abjerner/Umbraco-CMS,Pyuuma/Umbraco-CMS,mittonp/Umbraco-CMS,Spijkerboer/Umbraco-CMS,markoliver288/Umbraco-CMS | src/Umbraco.Web/Trees/TemplateTreeController.cs | src/Umbraco.Web/Trees/TemplateTreeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using umbraco.cms.presentation.Trees;
using Constants = Umbraco.Core.Constants;
using Umbraco.Web.WebApi.Filters;
using Umbraco.Web.Mvc;
using umbraco.cms.businesslogic.template;
using Umbraco.Web.Models.Trees;
//namespace Umbraco.Web.Trees
//{
// [UmbracoApplicationAuthorize(Constants.Applications.Settings)]
// [Tree(Constants.Applications.Settings, Constants.Trees.Templates, "Templates")]
// [PluginController("UmbracoTrees")]
// [CoreTree]
// public class TemplateTreeController : TreeController
// {
// protected override Models.Trees.MenuItemCollection GetMenuForNode(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
// {
// return new Models.Trees.MenuItemCollection();
// }
// protected override Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
// {
// IEnumerable<Umbraco.Core.Models.EntityBase.IUmbracoEntity> templates;
// var nodes = new TreeNodeCollection();
// if (id == "-1")
// templates = Services.EntityService.GetRootEntities(Core.Models.UmbracoObjectTypes.Template);
// else
// templates = Services.EntityService.GetChildren(int.Parse(id), Core.Models.UmbracoObjectTypes.Template);
// foreach (var t in templates)
// {
// var node = CreateTreeNode(t.Id.ToString(), t.ParentId.ToString(), queryStrings, t.Name);
// node.Icon = "icon-newspaper-alt";
// node.HasChildren = Services.EntityService.GetChildren(t.Id, Core.Models.UmbracoObjectTypes.Template).Any();
// if (node.HasChildren)
// node.Icon = "icon-newspaper";
// nodes.Add(node);
// }
// return nodes;
// }
// }
//}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using umbraco.cms.presentation.Trees;
using Constants = Umbraco.Core.Constants;
using Umbraco.Web.WebApi.Filters;
using Umbraco.Web.Mvc;
using umbraco.cms.businesslogic.template;
using Umbraco.Web.Models.Trees;
namespace Umbraco.Web.Trees
{
[UmbracoApplicationAuthorize(Constants.Applications.Settings)]
[Tree(Constants.Applications.Settings, Constants.Trees.Templates, "Templates")]
[PluginController("UmbracoTrees")]
[CoreTree]
public class TemplateTreeController : TreeController
{
protected override Models.Trees.MenuItemCollection GetMenuForNode(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
{
return new Models.Trees.MenuItemCollection();
}
protected override Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
{
IEnumerable<Umbraco.Core.Models.EntityBase.IUmbracoEntity> templates;
var nodes = new TreeNodeCollection();
if (id == "-1")
templates = Services.EntityService.GetRootEntities(Core.Models.UmbracoObjectTypes.Template);
else
templates = Services.EntityService.GetChildren(int.Parse(id), Core.Models.UmbracoObjectTypes.Template);
foreach (var t in templates)
{
var node = CreateTreeNode(t.Id.ToString(), t.ParentId.ToString(), queryStrings, t.Name);
node.Icon = "icon-newspaper-alt";
node.HasChildren = Services.EntityService.GetChildren(t.Id, Core.Models.UmbracoObjectTypes.Template).Any();
if (node.HasChildren)
node.Icon = "icon-newspaper";
nodes.Add(node);
}
return nodes;
}
}
}
| mit | C# |
a8d2fafb799f3a8578b446aed00644fc502016da | Fix for wrong items per page calculation for the view | andrelmp/eShopOnContainers,skynode/eShopOnContainers,oferns/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,BillWagner/eShopOnContainers,skynode/eShopOnContainers,oferns/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,oferns/eShopOnContainers,TypeW/eShopOnContainers,BillWagner/eShopOnContainers,productinfo/eShopOnContainers,BillWagner/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,BillWagner/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,BillWagner/eShopOnContainers,andrelmp/eShopOnContainers,oferns/eShopOnContainers,oferns/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers | src/Web/WebMVC/Controllers/CatalogController.cs | src/Web/WebMVC/Controllers/CatalogController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers
{
public class CatalogController : Controller
{
private ICatalogService _catalogSvc;
public CatalogController(ICatalogService catalogSvc)
{
_catalogSvc = catalogSvc;
}
public async Task<IActionResult> Index(int? BrandFilterApplied, int? TypesFilterApplied, int? page)
{
var itemsPage = 10;
var catalog = await _catalogSvc.GetCatalogItems(page ?? 0, itemsPage, BrandFilterApplied, TypesFilterApplied);
var vm = new IndexViewModel()
{
CatalogItems = catalog.Data,
Brands = await _catalogSvc.GetBrands(),
Types = await _catalogSvc.GetTypes(),
BrandFilterApplied = BrandFilterApplied ?? 0,
TypesFilterApplied = TypesFilterApplied ?? 0,
PaginationInfo = new PaginationInfo()
{
ActualPage = page ?? 0,
ItemsPerPage = catalog.Data.Count,
TotalItems = catalog.Count,
TotalPages = int.Parse(Math.Ceiling(((decimal)catalog.Count / itemsPage)).ToString())
}
};
vm.PaginationInfo.Next = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
return View(vm);
}
public IActionResult Error()
{
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers
{
public class CatalogController : Controller
{
private ICatalogService _catalogSvc;
public CatalogController(ICatalogService catalogSvc)
{
_catalogSvc = catalogSvc;
}
public async Task<IActionResult> Index(int? BrandFilterApplied, int? TypesFilterApplied, int? page)
{
var itemsPage = 10;
var catalog = await _catalogSvc.GetCatalogItems(page ?? 0, itemsPage, BrandFilterApplied, TypesFilterApplied);
var vm = new IndexViewModel()
{
CatalogItems = catalog.Data,
Brands = await _catalogSvc.GetBrands(),
Types = await _catalogSvc.GetTypes(),
BrandFilterApplied = BrandFilterApplied ?? 0,
TypesFilterApplied = TypesFilterApplied ?? 0,
PaginationInfo = new PaginationInfo()
{
ActualPage = page ?? 0,
ItemsPerPage = (catalog.Count < itemsPage) ? catalog.Count : itemsPage,
TotalItems = catalog.Count,
TotalPages = int.Parse(Math.Ceiling(((decimal)catalog.Count / itemsPage)).ToString())
}
};
vm.PaginationInfo.Next = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
return View(vm);
}
public IActionResult Error()
{
return View();
}
}
}
| mit | C# |
06f50ac1d523511da52e780a2791316de58cb293 | Fix example code, when I put the recipients numbers | danieleskebby/skebbyAPI,danieleskebby/skebbyAPI,danieleskebby/skebbyAPI,danieleskebby/skebbyAPI,danieleskebby/skebbyAPI,danieleskebby/skebbyAPI,danieleskebby/skebbyAPI | C#.NET/Program.cs | C#.NET/Program.cs | using System;
using System.Collections;
using System.Collections.Generic;
using SkebbyGW;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var sms = new skebbyAPI("username","password");
Dictionary<string,dynamic> input = new Dictionary<string,dynamic>();
input.Add("text","It's easy to send a message :)");
input.Add("recipients", {"391234567890"});
string result = sms.sendSMS( input );
sms.printResult(result);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using SkebbyGW;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var sms = new skebbyAPI("username","password");
Hashtable input = new Hashtable();
input.Add("text","It's easy to send a message :)");
input.Add("recipients", new string[] {"391234567890"});
string result = sms.sendSMS( input );
sms.printResult(result);
}
}
}
| unlicense | C# |
36a325ca1395b3ac7cb3644889c452223763a600 | fix resource path | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/Endpoints/Static/StaticController.cs | Dashen/Endpoints/Static/StaticController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Dashen.Infrastructure;
namespace Dashen.Endpoints.Static
{
public class StaticController : ApiController
{
private readonly List<IStaticContentProvider> _contentProviders;
private readonly Dictionary<string, string> _contentRouteMap;
public StaticController(IStaticContentProvider contentProvider)
{
_contentProviders = new[] { contentProvider }.ToList();
_contentRouteMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_contentRouteMap["css/normalize"] = "css/normalize.css";
_contentRouteMap["css/foundation"] = "css/foundation.min.css";
_contentRouteMap["css/style"] = "css/style.css";
_contentRouteMap["js/jquery"] = "js/jquery-2.1.1.min.js";
_contentRouteMap["js/jquery-flot"] = "js/jquery.flot.min.js";
}
public HttpResponseMessage GetDispatch(string url = "")
{
var path = _contentRouteMap.Get(url);
if (string.IsNullOrWhiteSpace(path))
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var content = _contentProviders.Select(cp => cp.GetContent(path)).FirstOrDefault(c => c != null);
if (content == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var streamContent = new StreamContent(content.Stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue(content.MimeType);
return new HttpResponseMessage { Content = streamContent };
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Dashen.Infrastructure;
namespace Dashen.Endpoints.Static
{
public class StaticController : ApiController
{
private readonly List<IStaticContentProvider> _contentProviders;
private readonly Dictionary<string, string> _contentRouteMap;
public StaticController(IStaticContentProvider contentProvider)
{
_contentProviders = new[] { contentProvider }.ToList();
_contentRouteMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_contentRouteMap["css/normalize"] = "css/normalize.css";
_contentRouteMap["css/foundation"] = "foundation.min.css";
_contentRouteMap["css/style"] = "css/style.css";
_contentRouteMap["js/jquery"] = "js/jquery-2.1.1.min.js";
_contentRouteMap["js/jquery-flot"] = "js/jquery.flot.min.js";
}
public HttpResponseMessage GetDispatch(string url = "")
{
var path = _contentRouteMap.Get(url);
if (string.IsNullOrWhiteSpace(path))
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var content = _contentProviders.Select(cp => cp.GetContent(path)).FirstOrDefault(c => c != null);
if (content == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var streamContent = new StreamContent(content.Stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue(content.MimeType);
return new HttpResponseMessage { Content = streamContent };
}
}
}
| lgpl-2.1 | C# |
53f6b5c7e496238cfef4ecd8b1ce3237ac8cd9ac | Correct layout | CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction,CollActionteam/CollAction | CollAction/Views/Donation/Donate.cshtml | CollAction/Views/Donation/Donate.cshtml | @using Stripe
@using Microsoft.Extensions.Options
@inject IOptions<RequestOptions> StripeOptions
@{
ViewData["Title"] = "Donate";
}
<div class="container-fluid">
<partial name="_DonationBox" />
</div> | @using Stripe
@using Microsoft.Extensions.Options
@inject IOptions<RequestOptions> StripeOptions
@{
ViewData["Title"] = "Donate";
}
<div id="donation-box" /> | agpl-3.0 | C# |
cd4e2c06d3296cedb87aa87ca823a1b5cd1adadb | Remove code to set zendesk widget in individual view as this is done in the base layout. | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web/Views/Home/ServiceStartPage.cshtml | src/SFA.DAS.EmployerAccounts.Web/Views/Home/ServiceStartPage.cshtml | @using SFA.DAS.EmployerAccounts.Web.Helpers
@{ViewBag.PageID = "page-service-start"; }
@{ViewBag.Title = "Create an account to manage apprenticeships"; }
@{ViewBag.MetaDesc = "Manage your funding for apprenticeships in England"; }
@{ViewBag.HideNav = true; }
@{
ViewBag.GaData.Vpv = "/page-service-start";
}
@{Layout = "~/Views/Shared/_Layout_CDN.cshtml"; }
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-xl">
@ViewBag.Title
</h1>
<p class="govuk-body">
You need to create or <a href="@Url.Action("SignIn", "Home")" class="govuk-link">sign in</a> to an apprenticeship account, then you'll be able to get funding to pay for apprenticeship training and assessment costs.
</p>
<p class="govuk-body">
You’ll use your account to:
</p>
<ul class="govuk-list govuk-list--bullet">
<li>get apprenticeship funding</li>
<li>find and save apprenticeships</li>
<li>find, save and manage training providers</li>
<li>recruit apprentices</li>
<li>add and manage apprenticeships</li>
</ul>
<a href="@Url.Action(ControllerConstants.RegisterUserActionName)" id="service-start" role="button" draggable="false" class="govuk-button govuk-button--start" data-module="govuk-button">
Create account
<svg class="govuk-button__start-icon" xmlns="http://www.w3.org/2000/svg" width="17.5" height="19" viewBox="0 0 33 40" role="presentation" focusable="false">
<path fill="currentColor" d="M0 0h13l20 20-20 20H0l20-20z" />
</svg>
</a>
</div>
</div> | @using SFA.DAS.EmployerAccounts.Web.Helpers
@{ViewBag.PageID = "page-service-start"; }
@{ViewBag.Title = "Create an account to manage apprenticeships"; }
@{ViewBag.MetaDesc = "Manage your funding for apprenticeships in England"; }
@{ViewBag.HideNav = true; }
@{
ViewBag.GaData.Vpv = "/page-service-start";
}
@{Layout = "~/Views/Shared/_Layout_CDN.cshtml"; }
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<h1 class="govuk-heading-xl">
@ViewBag.Title
</h1>
<p class="govuk-body">
You need to create or <a href="@Url.Action("SignIn", "Home")" class="govuk-link">sign in</a> to an apprenticeship account, then you'll be able to get funding to pay for apprenticeship training and assessment costs.
</p>
<p class="govuk-body">
You’ll use your account to:
</p>
<ul class="govuk-list govuk-list--bullet">
<li>get apprenticeship funding</li>
<li>find and save apprenticeships</li>
<li>find, save and manage training providers</li>
<li>recruit apprentices</li>
<li>add and manage apprenticeships</li>
</ul>
<a href="@Url.Action(ControllerConstants.RegisterUserActionName)" id="service-start" role="button" draggable="false" class="govuk-button govuk-button--start" data-module="govuk-button">
Create account
<svg class="govuk-button__start-icon" xmlns="http://www.w3.org/2000/svg" width="17.5" height="19" viewBox="0 0 33 40" role="presentation" focusable="false">
<path fill="currentColor" d="M0 0h13l20 20-20 20H0l20-20z" />
</svg>
</a>
</div>
</div>
@Html.SetZenDeskLabels(ZenDeskLabels.RegisterForAnApprenticeshipServiceAccount) | mit | C# |
ca3876f2687fc3a45f3d919a180c7ec168d7b66e | Update Assets/MRTK/Core/Interfaces/SpatialAwareness/Observers/Experimental/IMixedRealityOnDemandObserver.cs | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity | Assets/MRTK/Core/Interfaces/SpatialAwareness/Observers/Experimental/IMixedRealityOnDemandObserver.cs | Assets/MRTK/Core/Interfaces/SpatialAwareness/Observers/Experimental/IMixedRealityOnDemandObserver.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Microsoft.MixedReality.Toolkit.SpatialAwareness
{
/// <summary>
/// The interface for defining an on-demand spatial observer which enables on demand updating
/// </summary>
public interface IMixedRealityOnDemandObserver : IMixedRealitySpatialAwarenessObserver
{
/// <summary>
/// Gets or sets a value indicating whether the observer can autoupdate on interval.
/// </summary>
/// <remarks>
/// When false, calling UpdateOnDemand() is the ONLY way to update an observer.
/// </remarks>
bool AutoUpdate { get; set; }
/// <summary>
/// Observer will update once after initialization then require manual update thereafter. Uses <see cref="FirstUpdateDelay"/> to determine when.
/// </summary>
bool UpdateOnceOnLoad { get; set; }
/// <summary>
/// Delay in seconds before the observer will update automatically, once.
/// </summary>
float FirstUpdateDelay { get; set; }
/// <summary>
/// Tells the observer to run a cycle
/// </summary>
/// <remarks>
/// regardless of AutoUpdate, calling this method will force the observer to update.
/// When AutoUpdate is false, this is the ONLY way to update an observer.
/// </remarks>
void UpdateOnDemand();
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Microsoft.MixedReality.Toolkit.SpatialAwareness
{
/// <summary>
/// The interface for defining an <see cref="IMixedRealityOnDemandObserver"/> which enables on demand updating
/// </summary>
public interface IMixedRealityOnDemandObserver : IMixedRealitySpatialAwarenessObserver
{
/// <summary>
/// Gets or sets a value indicating whether the observer can autoupdate on interval.
/// </summary>
/// <remarks>
/// When false, calling UpdateOnDemand() is the ONLY way to update an observer.
/// </remarks>
bool AutoUpdate { get; set; }
/// <summary>
/// Observer will update once after initialization then require manual update thereafter. Uses <see cref="FirstUpdateDelay"/> to determine when.
/// </summary>
bool UpdateOnceOnLoad { get; set; }
/// <summary>
/// Delay in seconds before the observer will update automatically, once.
/// </summary>
float FirstUpdateDelay { get; set; }
/// <summary>
/// Tells the observer to run a cycle
/// </summary>
/// <remarks>
/// regardless of AutoUpdate, calling this method will force the observer to update.
/// When AutoUpdate is false, this is the ONLY way to update an observer.
/// </remarks>
void UpdateOnDemand();
}
} | mit | C# |
867d23581666bf52bea0371f8c1c14b6e9d04b15 | Correct error message in thread test | am11/MaxMind-DB-Reader-dotnet,am11/MaxMind-DB-Reader-dotnet,maxmind/MaxMind-DB-Reader-dotnet | MaxMind.MaxMindDb.Test/ThreadingTest.cs | MaxMind.MaxMindDb.Test/ThreadingTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching result. Expected {0}, found {1}", expectedString, resultString));
});
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MaxMind.MaxMindDb.Test
{
[TestFixture]
public class ThreadingTest
{
[Test]
public void TestParallelFor()
{
var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
var count = 0;
var ipsAndResults = new Dictionary<IPAddress, string>();
var rand = new Random();
while(count < 10000)
{
var ip = new IPAddress(rand.Next(int.MaxValue));
var resp = reader.Find(ip);
if (resp != null)
{
ipsAndResults.Add(ip, resp.ToString());
count++;
}
}
var ips = ipsAndResults.Keys.ToArray();
Parallel.For(0, ips.Length, (i) =>
{
var ipAddress = ips[i];
var result = reader.Find(ipAddress);
var resultString = result.ToString();
var expectedString = ipsAndResults[ipAddress];
if(resultString != expectedString)
throw new Exception(string.Format("Non-matching zip. Expected {0}, found {1}", expectedString, resultString));
});
}
}
} | apache-2.0 | C# |
8d54bc7ae3a739cb2d1e7bfa57554819085cab39 | Rename ITablature to IAsciiTablature | GetTabster/Tabster.Data | ITablatureFile.cs | ITablatureFile.cs | #region
using Tabster.Core.Types;
#endregion
namespace Tabster.Data
{
public interface ITablatureFile : ITablatureExtendedAttributes, ITablatureAttributes, ITablatureSourceAttributes, IAsciiTablature, ITabsterFile
{
}
} | #region
using Tabster.Core.Types;
#endregion
namespace Tabster.Data
{
public interface ITablatureFile : ITablatureExtendedAttributes, ITablatureAttributes, ITablatureSourceAttributes, ITablature, ITabsterFile
{
}
} | apache-2.0 | C# |
96bc9961f75613a90e9f02c958184851beab3629 | Set locations panel initial size | SonarSource-VisualStudio/sonarlint-visualstudio | src/IssueViz/IssueVizPackage.cs | src/IssueViz/IssueVizPackage.cs | /*
* SonarLint for Visual Studio
* Copyright (C) 2016-2020 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using SonarLint.VisualStudio.IssueVisualization.Commands;
using SonarLint.VisualStudio.IssueVisualization.IssueVisualizationControl;
using Task = System.Threading.Tasks.Task;
namespace SonarLint.VisualStudio.IssueVisualization
{
[ExcludeFromCodeCoverage]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid("4F3D7D24-648B-4F3B-ACB0-B83AFE239210")]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideToolWindow(typeof(IssueVisualizationToolWindow), MultiInstances = false, Style = VsDockStyle.Float, Width = 325, Height = 400)]
[ProvideToolWindowVisibility(typeof(IssueVisualizationToolWindow), Constants.UIContextGuid)]
public sealed class IssueVizPackage : AsyncPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
await IssueVisualizationToolWindowCommand.InitializeAsync(this);
await NavigationCommands.InitializeAsync(this);
}
protected override WindowPane InstantiateToolWindow(Type toolWindowType)
{
if (toolWindowType == typeof(IssueVisualizationToolWindow))
{
return new IssueVisualizationToolWindow(this);
}
return base.InstantiateToolWindow(toolWindowType);
}
}
}
| /*
* SonarLint for Visual Studio
* Copyright (C) 2016-2020 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using SonarLint.VisualStudio.IssueVisualization.Commands;
using SonarLint.VisualStudio.IssueVisualization.IssueVisualizationControl;
using Task = System.Threading.Tasks.Task;
namespace SonarLint.VisualStudio.IssueVisualization
{
[ExcludeFromCodeCoverage]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid("4F3D7D24-648B-4F3B-ACB0-B83AFE239210")]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideToolWindow(typeof(IssueVisualizationToolWindow), MultiInstances = false, Style = VsDockStyle.Float)]
[ProvideToolWindowVisibility(typeof(IssueVisualizationToolWindow), Constants.UIContextGuid)]
public sealed class IssueVizPackage : AsyncPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
await IssueVisualizationToolWindowCommand.InitializeAsync(this);
await NavigationCommands.InitializeAsync(this);
}
protected override WindowPane InstantiateToolWindow(Type toolWindowType)
{
if (toolWindowType == typeof(IssueVisualizationToolWindow))
{
return new IssueVisualizationToolWindow(this);
}
return base.InstantiateToolWindow(toolWindowType);
}
}
}
| mit | C# |
e583be3cf23fab957f124ebdd6e95bd5c086bf0a | fix build error | ObjectivityBSS/Test.Automation,ObjectivityLtd/Test.Automation | Objectivity.Test.Automation.Tests.NUnit/Tests/jraczek.cs | Objectivity.Test.Automation.Tests.NUnit/Tests/jraczek.cs | /*
The MIT License (MIT)
Copyright (c) 2015 Objectivity Bespoke Software Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
namespace Objectivity.Test.Automation.Tests.NUnit.Tests
{
using global::NUnit.Framework;
using Objectivity.Test.Automation.Common;
using Objectivity.Test.Automation.Tests.PageObjects.PageObjects.TheInternet;
/// <summary>
/// Tests to test framework
/// </summary>
[TestFixture, Category("herokuapp")]
public class jraczek : ProjectTestBase
{
[Test]
public void BasicAuthTest()
{
var basicAuthPage = new InternetPage(this.DriverContext)
.OpenHomePageWithUserCredentials()
.GoToBasicAuthPage();
Verify.That(this.DriverContext,
() => Assert.AreEqual("Congratulations! You must have the proper credentials.", basicAuthPage.GetCongratulationsInfo));
}
}
}
| /*
The MIT License (MIT)
Copyright (c) 2015 Objectivity Bespoke Software Specialists
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
namespace Objectivity.Test.Automation.Tests.NUnit.Tests
{
using global::NUnit.Framework;
using Objectivity.Test.Automation.Common;
using Objectivity.Test.Automation.Tests.PageObjects.PageObjects.TheInternet;
/// <summary>
/// Tests to test framework
/// </summary>
[TestFixture, Category("herokuapp")]
public class jraczek : ProjectTestBase
{
[Test]
public void BasicAuthTest()
{
var basicAuthPage = new InternetPage(this.DriverContext)
.OpenHomePageWithUserCredentials()
.GoToBasicAuthPage();
Verify.That(this.DriverContext,
() => Assert.AreEqual("Congratulations! You must have the proper credentials.", basicAuthPage.GetcongratulationsInfo));
}
}
}
| mit | C# |
af8d41836261a8fa24e1b7d3bb68cd8e76e9902c | Disable same site policy. | gyrosworkshop/Wukong,gyrosworkshop/Wukong | Wukong/Options/AuthenticationOptions.cs | Wukong/Options/AuthenticationOptions.cs | using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Wukong.Store;
namespace Wukong.Options
{
public class AuthenticationOptions
{
public static Action<CookieAuthenticationOptions> CookieAuthenticationOptions(string redisConnection)
=> options =>
{
ITicketStore ticketStore;
if (!string.IsNullOrEmpty(redisConnection))
{
ticketStore = new RedisCacheTicketStore(redisConnection);
}
else
{
ticketStore = new MemoryCacheStore();
}
options.SessionStore = ticketStore;
options.LoginPath = "/oauth/login";
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
};
}
} | using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Wukong.Store;
namespace Wukong.Options
{
public class AuthenticationOptions
{
public static Action<CookieAuthenticationOptions> CookieAuthenticationOptions(string redisConnection)
=> options =>
{
ITicketStore ticketStore;
if (!string.IsNullOrEmpty(redisConnection))
{
ticketStore = new RedisCacheTicketStore(redisConnection);
}
else
{
ticketStore = new MemoryCacheStore();
}
options.SessionStore = ticketStore;
options.LoginPath = "/oauth/login";
options.ExpireTimeSpan = TimeSpan.FromDays(30);
};
}
} | mit | C# |
723410c0577a581b2530477b0f54c3e35fed532e | Fix conversion from Xamarin Forms color to native color | Esri/arcgis-toolkit-dotnet | src/Esri.ArcGISRuntime.Toolkit/XamarinForms/Shared/ExtensionMethods.cs | src/Esri.ArcGISRuntime.Toolkit/XamarinForms/Shared/ExtensionMethods.cs | using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
var a = (byte)(255 * color.A);
var r = (byte)(255 * color.R);
var g = (byte)(255 * color.G);
var b = (byte)(255 * color.B);
#if NETFX_CORE
return NativeColor.FromArgb(a, r, g, b);
#elif __ANDROID__
return NativeColor.Argb(a, r, g, b);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
| using Xamarin.Forms;
#if __ANDROID__
using NativePoint = Android.Graphics.PointF;
using NativeColor = Android.Graphics.Color;
#elif __IOS__
using NativePoint = CoreGraphics.CGPoint;
#elif NETFX_CORE
using NativePoint = Windows.Foundation.Point;
#endif
#if NETFX_CORE
using NativeColor = Windows.UI.Color;
#endif
namespace Esri.ArcGISRuntime.Toolkit.Xamarin.Forms.Internal
{
internal static class ExtensionMethods
{
internal static NativeColor ToNativeColor(this Color color)
{
#if NETFX_CORE
return NativeColor.FromArgb((byte)color.A, (byte)color.R, (byte)color.G, (byte)color.B);
#elif __ANDROID__
return NativeColor.Argb((int)color.A, (int)color.R, (int)color.G, (int)color.B);
#endif
}
internal static Color ToXamarinFormsColor(this NativeColor color)
{
return Color.FromRgba(color.R, color.G, color.B, color.A);
}
}
}
| apache-2.0 | C# |
0b8ac1c8f4c1e19fae0a38f59d5bcd0f723e4790 | Improve code | sakapon/KLibrary-Labs | ObservableModelLab/ObservableModel/ObservableModel/ObservableMask.cs | ObservableModelLab/ObservableModel/ObservableModel/ObservableMask.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace KLibrary.Labs.ObservableModel
{
class ObservableMask<T> : IObservable<T>
{
IObservable<T> _source;
public ObservableMask(IObservable<T> source)
{
_source = source;
}
public IDisposable Subscribe(IObserver<T> observer)
{
return _source.Subscribe(observer);
}
}
class GetOnlyPropertyMask<T> : IGetOnlyProperty<T>
{
ISettableProperty<T> _source;
Dictionary<PropertyChangedEventHandler, PropertyChangedEventHandler> _propertyChangedMasks = new Dictionary<PropertyChangedEventHandler, PropertyChangedEventHandler>();
public bool HasObservers
{
get { return _source.HasObservers; }
}
public T Value
{
get { return _source.Value; }
}
public bool NotifiesUnchanged
{
get { return _source.NotifiesUnchanged; }
}
public event PropertyChangedEventHandler PropertyChanged
{
add
{
if (_propertyChangedMasks.ContainsKey(value)) return;
_propertyChangedMasks[value] = (o, e) => value(this, e);
_source.PropertyChanged += _propertyChangedMasks[value];
}
remove
{
if (!_propertyChangedMasks.ContainsKey(value)) return;
_source.PropertyChanged -= _propertyChangedMasks[value];
_propertyChangedMasks.Remove(value);
}
// データ バインディングでは sender が一致しなければならないため、以下のコードでは不可です。
//add { _source.PropertyChanged += value; }
//remove { _source.PropertyChanged -= value; }
}
public GetOnlyPropertyMask(ISettableProperty<T> source)
{
_source = source;
}
public IDisposable Subscribe(IObserver<T> observer)
{
return _source.Subscribe(observer);
}
public void OnNext()
{
throw new NotSupportedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace KLibrary.Labs.ObservableModel
{
class ObservableMask<T> : IObservable<T>
{
IObservable<T> _source;
public ObservableMask(IObservable<T> source)
{
_source = source;
}
public IDisposable Subscribe(IObserver<T> observer)
{
return _source.Subscribe(observer);
}
}
class GetOnlyPropertyMask<T> : IGetOnlyProperty<T>
{
ISettableProperty<T> _source;
public bool HasObservers
{
get { return _source.HasObservers; }
}
public T Value
{
get { return _source.Value; }
}
public bool NotifiesUnchanged
{
get { return _source.NotifiesUnchanged; }
}
public event PropertyChangedEventHandler PropertyChanged
{
add { _source.PropertyChanged += (o, e) => value(this, e); }
remove { }
}
public GetOnlyPropertyMask(ISettableProperty<T> source)
{
_source = source;
}
public IDisposable Subscribe(IObserver<T> observer)
{
return _source.Subscribe(observer);
}
public void OnNext()
{
throw new NotSupportedException();
}
}
}
| mit | C# |
d03a642ad0a00fd680c12564aaa4afbd26a44ebf | Refactor tests | Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife | PhotoLife/PhotoLife.Web.Tests/Controllers/Account/Register_Should.cs | PhotoLife/PhotoLife.Web.Tests/Controllers/Account/Register_Should.cs | using System.Web.Mvc;
using Moq;
using NUnit.Framework;
using PhotoLife.Authentication.Providers;
using PhotoLife.Controllers;
using PhotoLife.Factories;
namespace PhotoLife.Web.Tests.Controllers.Account
{
[TestFixture]
public class Register_Should
{
[Test]
public void _Return_NotNull()
{
//Arrange
var mockedProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IUserFactory>();
var controller = new AccountController(mockedProvider.Object, mockedFactory.Object);
//Act
var result = controller.Register();
//Assert
Assert.IsNotNull(result);
}
[Test]
public void _Return_View()
{
//Arrange
var mockedProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IUserFactory>();
var controller = new AccountController(mockedProvider.Object, mockedFactory.Object);
//Act
var result = controller.Register();
//Assert
Assert.IsInstanceOf<ViewResult>(result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Moq;
using NUnit.Framework;
using PhotoLife.Authentication.Providers;
using PhotoLife.Controllers;
using PhotoLife.Factories;
namespace PhotoLife.Web.Tests.Controllers.Account
{
[TestFixture]
public class Register_Should
{
[Test]
public void _Return_NotNull()
{
//Arrange
var mockedProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IUserFactory>();
var controller = new AccountController(mockedProvider.Object, mockedFactory.Object);
//Act
var result = controller.Register();
//Assert
Assert.IsNotNull(result);
}
[Test]
public void _Return_View()
{
//Arrange
var mockedProvider = new Mock<IAuthenticationProvider>();
var mockedFactory = new Mock<IUserFactory>();
var controller = new AccountController(mockedProvider.Object, mockedFactory.Object);
//Act
var result = controller.Register();
//Assert
Assert.IsInstanceOf<ViewResult>(result);
}
}
}
| mit | C# |
12d705332abbeebd51d7e77979fc96cfb7123731 | Disable analyzer tests. | yevhen/orleans,dotnet/orleans,ElanHasson/orleans,hoopsomuah/orleans,galvesribeiro/orleans,waynemunro/orleans,hoopsomuah/orleans,ibondy/orleans,ElanHasson/orleans,veikkoeeva/orleans,yevhen/orleans,jthelin/orleans,ibondy/orleans,dotnet/orleans,amccool/orleans,amccool/orleans,waynemunro/orleans,ReubenBond/orleans,amccool/orleans,jason-bragg/orleans,benjaminpetit/orleans,galvesribeiro/orleans | test/Analyzers.Tests/AlwaysInterleaveDiagnosticAnalyzerTests.cs | test/Analyzers.Tests/AlwaysInterleaveDiagnosticAnalyzerTests.cs | using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Orleans.Analyzers;
using Xunit;
namespace Analyzers.Tests
{
//[TestCategory("BVT"), TestCategory("Analyzer")]
public class AlwaysInterleaveDiagnosticAnalyzerTest : DiagnosticAnalyzerTestBase<AlwaysInterleaveDiagnosticAnalyzer>
{
protected override Task<(Diagnostic[], string)> GetDiagnosticsAsync(string source, params string[] extraUsings)
=> base.GetDiagnosticsAsync(source, extraUsings.Concat(new[] { "Orleans.Concurrency" }).ToArray());
[Fact]
public async Task AlwaysInterleave_Analyzer_NoWarningsIfAttributeIsNotUsed() => await this.AssertNoDiagnostics(@"
class C
{
Task M() => Task.CompletedTask;
}
");
[Fact]
public async Task AlwaysInterleave_Analyzer_NoWarningsIfAttributeIsUsedOnInterface() => await this.AssertNoDiagnostics(@"
public interface I : IGrain
{
[AlwaysInterleave]
Task<string> M();
}
");
[Fact]
public async Task AlwaysInterleave_Analyzer_WarningIfAttributeisUsedOnGrainClass()
{
var (diagnostics, source) = await this.GetDiagnosticsAsync(@"
public interface I : IGrain
{
Task<int> Method();
}
public class C : I
{
[AlwaysInterleave]
public Task<int> Method() => Task.FromResult(0);
}
");
var diagnostic = diagnostics.Single();
Assert.Equal(AlwaysInterleaveDiagnosticAnalyzer.DiagnosticId, diagnostic.Id);
Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity);
Assert.Equal(AlwaysInterleaveDiagnosticAnalyzer.MessageFormat, diagnostic.GetMessage());
var span = diagnostic.Location.SourceSpan;
Assert.Equal("AlwaysInterleave", source.Substring(span.Start, span.End - span.Start));
}
}
} | using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Orleans.Analyzers;
using Xunit;
namespace Analyzers.Tests
{
[TestCategory("BVT"), TestCategory("Analyzer")]
public class AlwaysInterleaveDiagnosticAnalyzerTest : DiagnosticAnalyzerTestBase<AlwaysInterleaveDiagnosticAnalyzer>
{
protected override Task<(Diagnostic[], string)> GetDiagnosticsAsync(string source, params string[] extraUsings)
=> base.GetDiagnosticsAsync(source, extraUsings.Concat(new[] { "Orleans.Concurrency" }).ToArray());
[Fact]
public async Task AlwaysInterleave_Analyzer_NoWarningsIfAttributeIsNotUsed() => await this.AssertNoDiagnostics(@"
class C
{
Task M() => Task.CompletedTask;
}
");
[Fact]
public async Task AlwaysInterleave_Analyzer_NoWarningsIfAttributeIsUsedOnInterface() => await this.AssertNoDiagnostics(@"
public interface I : IGrain
{
[AlwaysInterleave]
Task<string> M();
}
");
[Fact]
public async Task AlwaysInterleave_Analyzer_WarningIfAttributeisUsedOnGrainClass()
{
var (diagnostics, source) = await this.GetDiagnosticsAsync(@"
public interface I : IGrain
{
Task<int> Method();
}
public class C : I
{
[AlwaysInterleave]
public Task<int> Method() => Task.FromResult(0);
}
");
var diagnostic = diagnostics.Single();
Assert.Equal(AlwaysInterleaveDiagnosticAnalyzer.DiagnosticId, diagnostic.Id);
Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity);
Assert.Equal(AlwaysInterleaveDiagnosticAnalyzer.MessageFormat, diagnostic.GetMessage());
var span = diagnostic.Location.SourceSpan;
Assert.Equal("AlwaysInterleave", source.Substring(span.Start, span.End - span.Start));
}
}
} | mit | C# |
ad8975dd4b064381e1560536b77e5dcfb3195c84 | Add GC.KeepAlive to keep collectible ALC alive across usage. (#22133) | cshung/coreclr,mmitche/coreclr,poizan42/coreclr,cshung/coreclr,mmitche/coreclr,krk/coreclr,mmitche/coreclr,poizan42/coreclr,wtgodbe/coreclr,poizan42/coreclr,mmitche/coreclr,poizan42/coreclr,krk/coreclr,mmitche/coreclr,cshung/coreclr,mmitche/coreclr,wtgodbe/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr,cshung/coreclr,krk/coreclr,wtgodbe/coreclr,poizan42/coreclr,cshung/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,krk/coreclr,krk/coreclr | tests/src/Interop/ICustomMarshaler/ConflictingNames/RunInALC.cs | tests/src/Interop/ICustomMarshaler/ConflictingNames/RunInALC.cs | // 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;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using TestLibrary;
public class RunInALC
{
public static int Main(string[] args)
{
try
{
ConflictingCustomMarshalerNamesInCollectibleLoadContexts_Succeeds();
ConflictingCustomMarshalerNamesInNoncollectibleLoadContexts_Succeeds();
}
catch (System.Exception e)
{
Console.WriteLine(e.ToString());
return 101;
}
return 100;
}
static void ConflictingCustomMarshalerNamesInCollectibleLoadContexts_Succeeds()
{
Run(new UnloadableLoadContext());
Run(new UnloadableLoadContext());
}
static void ConflictingCustomMarshalerNamesInNoncollectibleLoadContexts_Succeeds()
{
Run(new CustomLoadContext());
Run(new CustomLoadContext());
}
static void Run(AssemblyLoadContext context)
{
string currentAssemblyDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);
Assembly inContextAssembly = context.LoadFromAssemblyPath(Path.Combine(currentAssemblyDirectory, "CustomMarshaler.dll"));
Type inContextType = inContextAssembly.GetType("CustomMarshalers.CustomMarshalerTest");
object instance = Activator.CreateInstance(inContextType);
MethodInfo parseIntMethod = inContextType.GetMethod("ParseInt", BindingFlags.Instance | BindingFlags.Public);
Assert.AreEqual(1234, (int)parseIntMethod.Invoke(instance, new object[]{"1234"}));
GC.KeepAlive(context);
}
}
class UnloadableLoadContext : AssemblyLoadContext
{
public UnloadableLoadContext()
:base(true)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
class CustomLoadContext : AssemblyLoadContext
{
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
| // 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;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using TestLibrary;
public class RunInALC
{
public static int Main(string[] args)
{
try
{
ConflictingCustomMarshalerNamesInCollectibleLoadContexts_Succeeds();
ConflictingCustomMarshalerNamesInNoncollectibleLoadContexts_Succeeds();
}
catch (System.Exception e)
{
Console.WriteLine(e.ToString());
return 101;
}
return 100;
}
static void ConflictingCustomMarshalerNamesInCollectibleLoadContexts_Succeeds()
{
Run(new UnloadableLoadContext());
Run(new UnloadableLoadContext());
}
static void ConflictingCustomMarshalerNamesInNoncollectibleLoadContexts_Succeeds()
{
Run(new CustomLoadContext());
Run(new CustomLoadContext());
}
static void Run(AssemblyLoadContext context)
{
string currentAssemblyDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);
Assembly inContextAssembly = context.LoadFromAssemblyPath(Path.Combine(currentAssemblyDirectory, "CustomMarshaler.dll"));
Type inContextType = inContextAssembly.GetType("CustomMarshalers.CustomMarshalerTest");
object instance = Activator.CreateInstance(inContextType);
MethodInfo parseIntMethod = inContextType.GetMethod("ParseInt", BindingFlags.Instance | BindingFlags.Public);
Assert.AreEqual(1234, (int)parseIntMethod.Invoke(instance, new object[]{"1234"}));
}
}
class UnloadableLoadContext : AssemblyLoadContext
{
public UnloadableLoadContext()
:base(true)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
class CustomLoadContext : AssemblyLoadContext
{
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
| mit | C# |
35c39a4daf4a46ebf4dbd259852373912ef9cc41 | Move whitespace to aid automated tests | SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Shared/ChooseEmployer.cshtml | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Shared/ChooseEmployer.cshtml | @using SFA.DAS.ProviderApprenticeshipsService.Web.Models
@model SFA.DAS.ProviderApprenticeshipsService.Web.Models.ChooseEmployerViewModel
@{
ViewBag.Title = Model.Title;
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Choose an employer</h1>
<p>@Model.Description</p>
<p>@Model.LegalEntities.Count() result@(Model.LegalEntities.Count() != 1 ? "s" : null) found.</p>
<table class="table">
<thead>
<tr>
<th scope="col">Employer</th>
<th scope="col">Account name</th>
<th scope="col">Agreement ID</th>
<th scope="col"><span class="vh">Action</span></th>
</tr>
</thead>
<tbody>
@foreach (var legalEntity in Model.LegalEntities)
{
<tr>
<td>@legalEntity.EmployerAccountLegalEntityName</td>
<td>@legalEntity.EmployerAccountName</td>
<td>@legalEntity.EmployerAccountLegalEntityPublicHashedId</td>
<td class="link-right">
<a href="@Url.Action("ConfirmEmployer", Model.ControllerName, new ConfirmEmployerViewModel(legalEntity, Model.EmployerSelectionAction))">Select<span class="vh"> @legalEntity.EmployerAccountLegalEntityName</span></a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<a href="@Url.Action("Index", "Account")" aria-label="Back to account home" class="back-link">Back</a>
</div>
}
| @using SFA.DAS.ProviderApprenticeshipsService.Web.Models
@model SFA.DAS.ProviderApprenticeshipsService.Web.Models.ChooseEmployerViewModel
@{
ViewBag.Title = Model.Title;
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Choose an employer</h1>
<p>@Model.Description</p>
<p>@Model.LegalEntities.Count() result@(Model.LegalEntities.Count() != 1 ? "s" : null) found.</p>
<table class="table">
<thead>
<tr>
<th scope="col">Employer</th>
<th scope="col">Account name</th>
<th scope="col">Agreement ID</th>
<th scope="col"><span class="vh">Action</span></th>
</tr>
</thead>
<tbody>
@foreach (var legalEntity in Model.LegalEntities)
{
<tr>
<td>@legalEntity.EmployerAccountLegalEntityName</td>
<td>@legalEntity.EmployerAccountName</td>
<td>@legalEntity.EmployerAccountLegalEntityPublicHashedId</td>
<td class="link-right">
<a href="@Url.Action("ConfirmEmployer", Model.ControllerName, new ConfirmEmployerViewModel(legalEntity, Model.EmployerSelectionAction))">Select <span class="vh">@legalEntity.EmployerAccountLegalEntityName</span></a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<a href="@Url.Action("Index", "Account")" aria-label="Back to account home" class="back-link">Back</a>
</div>
}
| mit | C# |
563f1cd2135ed256cf186aee1cce51427a69af0f | Fix the issue | thabart/SimpleIdentityServer,thabart/SimpleIdentityServer | SimpleIdentityServer/SimpleIdentityServer.Core.Jwt/ModuleInit.cs | SimpleIdentityServer/SimpleIdentityServer.Core.Jwt/ModuleInit.cs | using System.ComponentModel.Composition;
using SimpleIdentityServer.Common;
using SimpleIdentityServer.Core.Jwt.Encrypt;
using SimpleIdentityServer.Core.Jwt.Encrypt.Encryption;
using SimpleIdentityServer.Core.Jwt.Mapping;
using SimpleIdentityServer.Core.Jwt.Signature;
namespace SimpleIdentityServer.Core.Jwt
{
[Export(typeof(IModule))]
public class ModuleInit : IModule
{
public void Initialize(IModuleRegister register)
{
register.RegisterType<IJweGenerator, JweGenerator>();
register.RegisterType<IAesEncryptionHelper, AesEncryptionHelper>();
register.RegisterType<IClaimsMapping, ClaimsMapping>();
register.RegisterType<IJwsGenerator, JwsGenerator>();
register.RegisterType<ICreateJwsSignature, CreateJwsSignature>();
register.RegisterType<IJwsParser, JwsParser>();
}
}
}
| using System.ComponentModel.Composition;
using SimpleIdentityServer.Common;
using SimpleIdentityServer.Core.Jwt.Encrypt;
using SimpleIdentityServer.Core.Jwt.Encrypt.Encryption;
using SimpleIdentityServer.Core.Jwt.Mapping;
using SimpleIdentityServer.Core.Jwt.Signature;
namespace SimpleIdentityServer.Core.Jwt
{
[Export(typeof(IModule))]
public class ModuleInit : IModule
{
public void Initialize(IModuleRegister register)
{
register.RegisterType<IJweGenerator, JweGenerator>();
register.RegisterType<IAesEncryptionHelper, AesEncryptionHelper>();
register.RegisterType<IClaimsMapping, ClaimsMapping>();
register.RegisterType<IJwsGenerator, IJwsGenerator>();
register.RegisterType<ICreateJwsSignature, CreateJwsSignature>();
register.RegisterType<IJwsParser, JwsParser>();
}
}
}
| apache-2.0 | C# |
67d57aa74656895203f450343d44714f7e31f894 | Add unit tests for enum user like type read and write. | henrikfroehling/TraktApiSharp | Source/Tests/TraktApiSharp.Tests/Enums/TraktUserLikeTypeTests.cs | Source/Tests/TraktApiSharp.Tests/Enums/TraktUserLikeTypeTests.cs | namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using TraktApiSharp.Enums;
[TestClass]
public class TraktUserLikeTypeTests
{
class TestObject
{
[JsonConverter(typeof(TraktUserLikeTypeConverter))]
public TraktUserLikeType Value { get; set; }
}
[TestMethod]
public void TestTraktUserLikeTypeHasMembers()
{
typeof(TraktUserLikeType).GetEnumNames().Should().HaveCount(3)
.And.Contain("Unspecified", "Comment", "List");
}
[TestMethod]
public void TestTraktUserLikeTypeGetAsString()
{
TraktUserLikeType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
TraktUserLikeType.Comment.AsString().Should().Be("comment");
TraktUserLikeType.List.AsString().Should().Be("list");
}
[TestMethod]
public void TestTraktUserLikeTypeGetAsStringUriParameter()
{
TraktUserLikeType.Unspecified.AsStringUriParameter().Should().NotBeNull().And.BeEmpty();
TraktUserLikeType.Comment.AsStringUriParameter().Should().Be("comments");
TraktUserLikeType.List.AsStringUriParameter().Should().Be("lists");
}
[TestMethod]
public void TestTraktUserLikeTypeWriteAndReadJson_Comment()
{
var obj = new TestObject { Value = TraktUserLikeType.Comment };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktUserLikeType.Comment);
}
[TestMethod]
public void TestTraktUserLikeTypeWriteAndReadJson_List()
{
var obj = new TestObject { Value = TraktUserLikeType.List };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktUserLikeType.List);
}
[TestMethod]
public void TestTraktUserLikeTypeWriteAndReadJson_Unspecified()
{
var obj = new TestObject { Value = TraktUserLikeType.Unspecified };
var objWritten = JsonConvert.SerializeObject(obj);
objWritten.Should().NotBeNullOrEmpty();
var objRead = JsonConvert.DeserializeObject<TestObject>(objWritten);
objRead.Should().NotBeNull();
objRead.Value.Should().Be(TraktUserLikeType.Unspecified);
}
}
}
| namespace TraktApiSharp.Tests.Enums
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Enums;
[TestClass]
public class TraktUserLikeTypeTests
{
[TestMethod]
public void TestTraktUserLikeTypeHasMembers()
{
typeof(TraktUserLikeType).GetEnumNames().Should().HaveCount(3)
.And.Contain("Unspecified", "Comment", "List");
}
[TestMethod]
public void TestTraktUserLikeTypeGetAsString()
{
TraktUserLikeType.Unspecified.AsString().Should().NotBeNull().And.BeEmpty();
TraktUserLikeType.Comment.AsString().Should().Be("comment");
TraktUserLikeType.List.AsString().Should().Be("list");
}
[TestMethod]
public void TestTraktUserLikeTypeGetAsStringUriParameter()
{
TraktUserLikeType.Unspecified.AsStringUriParameter().Should().NotBeNull().And.BeEmpty();
TraktUserLikeType.Comment.AsStringUriParameter().Should().Be("comments");
TraktUserLikeType.List.AsStringUriParameter().Should().Be("lists");
}
}
}
| mit | C# |
de9c5a4b5ce780a17c7f0a5f8e7b3a7ce2fb46e0 | Tweak initialization for email notification | mattgwagner/CertiPay.Common | CertiPay.Common.Notifications/Notifications/EmailNotification.cs | CertiPay.Common.Notifications/Notifications/EmailNotification.cs | using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; } = new List<String>();
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; } = new List<String>();
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
} | using System;
using System.Collections.Generic;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Represents an email notification sent a user, employee, or administrator
/// </summary>
public class EmailNotification : Notification
{
public static String QueueName { get { return "EmailNotifications"; } }
/// <summary>
/// Who the email notification should be FROM
/// </summary>
public String FromAddress { get; set; }
/// <summary>
/// A list of email addresses to CC
/// </summary>
public ICollection<String> CC { get; set; }
/// <summary>
/// A list of email addresses to BCC
/// </summary>
public ICollection<String> BCC { get; set; }
/// <summary>
/// The subject line of the email
/// </summary>
public String Subject { get; set; }
/// <summary>
/// Any attachments to the email in the form of URLs to download
/// </summary>
public ICollection<Attachment> Attachments { get; set; }
public EmailNotification()
{
this.Recipients = new List<String>();
this.Attachments = new List<Attachment>();
this.CC = new List<String>();
this.BCC = new List<String>();
}
/// <summary>
/// A file may be attached to the email notification by providing a URL to download
/// the file (will be downloaded by the sending process) and a filename
/// </summary>
public class Attachment
{
public String Filename { get; set; }
public String Uri { get; set; }
}
}
} | mit | C# |
da92d03f23035217484d5885410297aef15b360c | Update AddingComboBoxControl.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/DrawingObjects/Controls/AddingComboBoxControl.cs | Examples/CSharp/DrawingObjects/Controls/AddingComboBoxControl.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.DrawingObjects.Controls
{
public class AddingComboBoxControl
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Create a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
//Get the worksheet cells collection.
Cells cells = sheet.Cells;
//Input a value.
cells["B3"].PutValue("Employee:");
//Set it bold.
cells["B3"].GetStyle().Font.IsBold = true;
//Input some values that denote the input range
//for the combo box.
cells["A2"].PutValue("Emp001");
cells["A3"].PutValue("Emp002");
cells["A4"].PutValue("Emp003");
cells["A5"].PutValue("Emp004");
cells["A6"].PutValue("Emp005");
cells["A7"].PutValue("Emp006");
//Add a new combo box.
Aspose.Cells.Drawing.ComboBox comboBox = sheet.Shapes.AddComboBox(2, 0, 2, 0, 22, 100);
//ExEnd:1
//Set the linked cell;
comboBox.LinkedCell = "A1";
//Set the input range.
comboBox.InputRange = "A2:A7";
//Set no. of list lines displayed in the combo
//box's list portion.
comboBox.DropDownLines = 5;
//Set the combo box with 3-D shading.
comboBox.Shadow = true;
//AutoFit Columns
sheet.AutoFitColumns();
//Saves the file.
workbook.Save(dataDir + "book1.out.xls");
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.DrawingObjects.Controls
{
public class AddingComboBoxControl
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Create a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
//Get the worksheet cells collection.
Cells cells = sheet.Cells;
//Input a value.
cells["B3"].PutValue("Employee:");
//Set it bold.
cells["B3"].GetStyle().Font.IsBold = true;
//Input some values that denote the input range
//for the combo box.
cells["A2"].PutValue("Emp001");
cells["A3"].PutValue("Emp002");
cells["A4"].PutValue("Emp003");
cells["A5"].PutValue("Emp004");
cells["A6"].PutValue("Emp005");
cells["A7"].PutValue("Emp006");
//Add a new combo box.
Aspose.Cells.Drawing.ComboBox comboBox = sheet.Shapes.AddComboBox(2, 0, 2, 0, 22, 100);
//Set the linked cell;
comboBox.LinkedCell = "A1";
//Set the input range.
comboBox.InputRange = "A2:A7";
//Set no. of list lines displayed in the combo
//box's list portion.
comboBox.DropDownLines = 5;
//Set the combo box with 3-D shading.
comboBox.Shadow = true;
//AutoFit Columns
sheet.AutoFitColumns();
//Saves the file.
workbook.Save(dataDir + "book1.out.xls");
}
}
} | mit | C# |
4e1bc59ccdef38e6bbfcfc7ad5c6583340378cec | Revert last commit | fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem | Source/SuggestionSystem/Web/SuggestionSystem.Web.DataTransferModels/Suggestion/SuggestionResponseModel.cs | Source/SuggestionSystem/Web/SuggestionSystem.Web.DataTransferModels/Suggestion/SuggestionResponseModel.cs | namespace SuggestionSystem.Web.DataTransferModels.Suggestion
{
using System;
using AutoMapper;
using Infrastructure.Mappings;
using Data.Models;
using System.Linq;
public class SuggestionResponseModel : IMapFrom<Suggestion>, IHaveCustomMappings
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int UpVotesCount { get; set; }
public int DownVotesCount { get; set; }
public string Author { get; set; }
public SuggestionStatus Status { get; set; }
public int CommentsCount { get; set; }
public DateTime DateCreated { get; set; }
public void CreateMappings(IConfiguration configuration)
{
configuration.CreateMap<Suggestion, SuggestionResponseModel>()
.ForMember(s => s.Author, opts => opts.MapFrom(s => s.UserId != null ? s.User.UserName : "Anonymous"));
}
}
}
| namespace SuggestionSystem.Web.DataTransferModels.Suggestion
{
using System;
using AutoMapper;
using Infrastructure.Mappings;
using Data.Models;
using System.Linq;
public class SuggestionResponseModel : IMapFrom<Suggestion>, IHaveCustomMappings
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int UpVotesCount { get; set; }
public int DownVotesCount { get; set; }
public string Author { get; set; }
public string SuggestionStatus { get; set; }
public int CommentsCount { get; set; }
public DateTime DateCreated { get; set; }
public void CreateMappings(IConfiguration configuration)
{
configuration.CreateMap<Suggestion, SuggestionResponseModel>()
.ForMember(s => s.Author, opts => opts.MapFrom(s => s.UserId != null ? s.User.UserName : "Anonymous"))
.ForMember(s => s.SuggestionStatus, opts => opts.MapFrom(s => s.Status.ToString()));
}
}
}
| mit | C# |
5aa2ce14c434b3e58e08bd0470507475df55a1c5 | Remove duplicae null check, simplified state check | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Converters/WindowStateAfterSartJsonConverter.cs | WalletWasabi.Gui/Converters/WindowStateAfterSartJsonConverter.cs | using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
var windowStateString = value.Trim();
return windowStateString.StartsWith("norm", StringComparison.OrdinalIgnoreCase)
? WindowState.Normal
: WindowState.Maximized;
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
| using Avalonia.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
public class WindowStateAfterSartJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(WindowState);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
// If minimized, then go with Maximized, because at start it shouldn't run with minimized.
var value = reader.Value as string;
if (string.IsNullOrWhiteSpace(value))
{
return WindowState.Maximized;
}
if (value is null)
{
return WindowState.Maximized;
}
string windowStateString = value.Trim();
if (WindowState.Normal.ToString().Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "normal".Equals(windowStateString, StringComparison.OrdinalIgnoreCase)
|| "norm".Equals(windowStateString, StringComparison.OrdinalIgnoreCase))
{
return WindowState.Normal;
}
else
{
return WindowState.Maximized;
}
}
catch
{
return WindowState.Maximized;
}
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((WindowState)value).ToString());
}
}
}
| mit | C# |
d7b3589ce5f6d57c8bfa588846eb1d316f02a1d2 | Change About page | Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog | SpaceBlog/SpaceBlog/Views/Home/About.cshtml | SpaceBlog/SpaceBlog/Views/Home/About.cshtml | <div class="container">
<div class="col-md-6">
<div align="left">
<h2>@ViewBag.Title</h2>
<h3>Contact info</h3>
<strong><span class="glyphicon glyphicon-map-marker"></span>Address:</strong><br />
Sofia, Bulgaria<br />
<strong><span class="glyphicon glyphicon-phone"></span>Phone number:</strong><br />
+359 899 55 55 92<br>
<strong><span class="glyphicon glyphicon-envelope"></span>Email:</strong><br />
[email protected]
</div>
</div>
<div style="margin-top:20px">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2933.74423974472!2d23.350088315466078!3d42.66677497916745!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x40aa85cca4a719b7%3A0xdf53fcbcd8e758d7!2z0KHQvtGE0YLRg9C10YDQtdC9INGD0L3QuNCy0LXRgNGB0LjRgtC10YIgKNCh0L7RhNGC0KPQvdC4KQ!5e0!3m2!1sbg!2sbg!4v1490790759522"
width="570" height="300" frameborder="1" style="border:0" allowfullscreen></iframe>
</div>
</div> |
<div class="container">
<div class="col-md-6">
<div align="left">
<h2>@ViewBag.Title</h2>
<h3>Contact info</h3>
<strong>Address:</strong><br />
15-17, Tintyava street, Sofia, Bulgaria<br />
<strong>Work days:</strong><br />
09:00 - 18:00 (Monday - Friday)<br />
<strong>Days-off:</strong><br />
Saturday - Sunday <br>
<strong>Phone number:</strong><br />
+359 899 55 55 92<br>
</div>
</div>
<div style="margin-top:10px">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2933.74423974472!2d23.350088315466078!3d42.66677497916745!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x40aa85cca4a719b7%3A0xdf53fcbcd8e758d7!2z0KHQvtGE0YLRg9C10YDQtdC9INGD0L3QuNCy0LXRgNGB0LjRgtC10YIgKNCh0L7RhNGC0KPQvdC4KQ!5e0!3m2!1sbg!2sbg!4v1490790759522"
width="570" height="300" frameborder="1" style="border:0" allowfullscreen></iframe>
</div>
</div>
| mit | C# |
5686267d15569664f6f87e4562b2755743ccb1c2 | Modify EnumShortNameParser<> class to speed up | y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter | ThScoreFileConverter/EnumShortNameParser.cs | ThScoreFileConverter/EnumShortNameParser.cs | //-----------------------------------------------------------------------
// <copyright file="EnumShortNameParser.cs" company="None">
// (c) 2014 IIHOSHI Yoshinori
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Provides a parser for the enumeration type which fields have short names.
/// </summary>
/// <typeparam name="TEnum">The enumeration type which fields have short names.</typeparam>
[CLSCompliant(false)]
public sealed class EnumShortNameParser<TEnum>
where TEnum : struct, IComparable, IFormattable, IConvertible
{
/// <summary>
/// Elements of <typeparamref name="TEnum"/>.
/// </summary>
private static readonly IEnumerable<TEnum> Elements = Utils.GetEnumerator<TEnum>();
/// <summary>
/// A regular expression of the short names of <typeparamref name="TEnum"/>.
/// </summary>
private static readonly string PatternImpl =
string.Join("|", Elements.Select(elem => elem.ToShortName()).ToArray());
/// <summary>
/// Gets a regular expression of the short names of <typeparamref name="TEnum"/>.
/// </summary>
public string Pattern
{
get { return PatternImpl; }
}
/// <summary>
/// Converts from the string matched with the pattern to a value of <typeparamref name="TEnum"/>.
/// </summary>
/// <param name="shortName">The string matched with the pattern.</param>
/// <returns>A value of <typeparamref name="TEnum"/>.</returns>
public TEnum Parse(string shortName)
{
return Elements.First(
elem => elem.ToShortName().Equals(shortName, StringComparison.OrdinalIgnoreCase));
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="EnumShortNameParser.cs" company="None">
// (c) 2014 IIHOSHI Yoshinori
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Provides a parser for the enumeration type which fields have short names.
/// </summary>
/// <typeparam name="TEnum">The enumeration type which fields have short names.</typeparam>
[CLSCompliant(false)]
public class EnumShortNameParser<TEnum>
where TEnum : struct, IComparable, IFormattable, IConvertible
{
/// <summary>
/// Elements of <typeparamref name="TEnum"/>.
/// </summary>
private static IEnumerable<TEnum> elements = Utils.GetEnumerator<TEnum>();
/// <summary>
/// Gets a regular expression of the short names of <typeparamref name="TEnum"/>.
/// </summary>
public string Pattern
{
get { return string.Join("|", elements.Select(elem => elem.ToShortName()).ToArray()); }
}
/// <summary>
/// Converts from the string matched with the pattern to a value of <typeparamref name="TEnum"/>.
/// </summary>
/// <param name="shortName">The string matched with the pattern.</param>
/// <returns>A value of <typeparamref name="TEnum"/>.</returns>
public TEnum Parse(string shortName)
{
return elements.First(
elem => elem.ToShortName().Equals(shortName, StringComparison.OrdinalIgnoreCase));
}
}
}
| bsd-2-clause | C# |
b4f2e88653c6f01d5896bb2ab5b7aacbfbedb522 | add Load from file/stream support | rdio/vernacular,StephaneDelcroix/vernacular,gabornemeth/vernacular,mightea/vernacular,StephaneDelcroix/vernacular,dsuess/vernacular,gabornemeth/vernacular,rdio/vernacular,dsuess/vernacular,benoitjadinon/vernacular,mightea/vernacular,benoitjadinon/vernacular | Vernacular.Potato/Vernacular.PO/Document.cs | Vernacular.Potato/Vernacular.PO/Document.cs | //
// Document.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2012 Rdio, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Vernacular.PO.Internal;
namespace Vernacular.PO
{
public sealed class Document : Container
{
private List<Unit> units = new List<Unit> ();
public void Add (Unit unit)
{
units.Add (unit);
}
public void Add (params Unit [] units)
{
this.units.AddRange (units);
}
public void Load (string path)
{
units.AddRange (new Parser ().Parse (path));
}
public void Load (StreamReader reader, string documentName = null)
{
units.AddRange (new Parser ().Parse (reader, documentName));
}
public override string Generate ()
{
var builder = new StringBuilder ();
foreach (var part in this) {
builder.Append (part.Generate ());
builder.Append ("\n\n");
}
builder.Length--;
return builder.ToString ();
}
public override IEnumerator<IDocumentPart> GetEnumerator ()
{
foreach (var unit in units) {
if (unit.HasValue) {
yield return unit;
}
}
}
}
} | //
// Document.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright 2012 Rdio, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Text;
using System.Collections.Generic;
namespace Vernacular.PO
{
public sealed class Document : Container
{
private List<Unit> units = new List<Unit> ();
public void Add (Unit unit)
{
units.Add (unit);
}
public override string Generate ()
{
var builder = new StringBuilder ();
foreach (var part in this) {
builder.Append (part.Generate ());
builder.Append ("\n\n");
}
builder.Length--;
return builder.ToString ();
}
public override IEnumerator<IDocumentPart> GetEnumerator ()
{
foreach (var unit in units) {
if (unit.HasValue) {
yield return unit;
}
}
}
}
} | mit | C# |
ee3656b746112b5539babefa35210a0a41ac081c | rename sqlserver processor | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP.SqlServer/CAP.SqlServerCapOptionsExtension.cs | src/DotNetCore.CAP.SqlServer/CAP.SqlServerCapOptionsExtension.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.Processor;
using DotNetCore.CAP.SqlServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class SqlServerCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<SqlServerOptions> _configure;
public SqlServerCapOptionsExtension(Action<SqlServerOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, SqlServerStorage>();
services.AddSingleton<IStorageConnection, SqlServerStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<ICollectProcessor, SqlServerCollectProcessor>();
AddSqlServerOptions(services);
}
private void AddSqlServerOptions(IServiceCollection services)
{
var sqlServerOptions = new SqlServerOptions();
_configure(sqlServerOptions);
if (sqlServerOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext)provider.GetService(sqlServerOptions.DbContextType);
sqlServerOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return sqlServerOptions;
}
});
}
else
{
services.AddSingleton(sqlServerOptions);
}
}
}
} | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.Processor;
using DotNetCore.CAP.SqlServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class SqlServerCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<SqlServerOptions> _configure;
public SqlServerCapOptionsExtension(Action<SqlServerOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, SqlServerStorage>();
services.AddSingleton<IStorageConnection, SqlServerStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<IAdditionalProcessor, DefaultAdditionalProcessor>();
AddSqlServerOptions(services);
}
private void AddSqlServerOptions(IServiceCollection services)
{
var sqlServerOptions = new SqlServerOptions();
_configure(sqlServerOptions);
if (sqlServerOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext)provider.GetService(sqlServerOptions.DbContextType);
sqlServerOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return sqlServerOptions;
}
});
}
else
{
services.AddSingleton(sqlServerOptions);
}
}
}
} | mit | C# |
c6b99091d98f77e8c70890d69b665120efbdd92b | Add logging to webjob start and end | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ExpireFundsJob.cs | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ExpireFundsJob.cs | using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
logger.LogInformation($"Starting {nameof(ExpireFundsJob)}");
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
logger.LogInformation($"{nameof(ExpireFundsJob)} completed.");
}
}
} | using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
private readonly ICurrentDateTime _currentDateTime;
private readonly IEmployerAccountRepository _accountRepository;
public ExpireFundsJob(
IMessageSession messageSession,
ICurrentDateTime currentDateTime,
IEmployerAccountRepository accountRepository)
{
_messageSession = messageSession;
_currentDateTime = currentDateTime;
_accountRepository = accountRepository;
}
public async Task Run(
[TimerTrigger("0 0 0 28 * *")] TimerInfo timer,
ILogger logger)
{
var now = _currentDateTime.Now;
var accounts = await _accountRepository.GetAllAccounts();
var commands = accounts.Select(a => new ExpireAccountFundsCommand { AccountId = a.Id });
var tasks = commands.Select(c =>
{
var sendOptions = new SendOptions();
sendOptions.RequireImmediateDispatch();
sendOptions.SetMessageId($"{nameof(ExpireAccountFundsCommand)}-{now.Year}-{now.Month}-{c.AccountId}");
return _messageSession.Send(c, sendOptions);
});
await Task.WhenAll(tasks);
}
}
} | mit | C# |
549db22807c1251ddbd33ab2c523bf0fb50a55d6 | Update assemblyinfo | stevehodgkiss/restful-routing,restful-routing/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing | src/RestfulRouting/Properties/AssemblyInfo.cs | src/RestfulRouting/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RestfulRouting")]
[assembly: AssemblyDescription("RestfulRouting is a routing library for ASP.NET MVC based on the Rails 3 routing DSL.")]
[assembly: AssemblyProduct("RestfulRouting")]
[assembly: AssemblyVersion("1.0.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RestfulRouting is a routing library for ASP.NET MVC based on the Rails 3 routing DSL.")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestfulRouting")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d58bb36a-e28c-49a3-91ca-8516782ed441")]
// 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: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
deea44fffb477abf639158d1325aa56bfcac2611 | Fix service locator version | yfakariya/NLiblet,yfakariya/NLiblet | src/ServiceLocator/Properties/AssemblyInfo.cs | src/ServiceLocator/Properties/AssemblyInfo.cs | #region -- License Terms --
//
// NLiblet
//
// Copyright (C) 2011 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "NLiblet.ServiceLocator" )]
[assembly: AssemblyDescription( "NLiblet simple service locator" )]
[assembly: AssemblyProduct( "NLiblet" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2011" )]
[assembly: CLSCompliant( true )]
[assembly: AssemblyVersion( "0.1.0.0" )]
[assembly: AssemblyFileVersion( "0.1.0.0" )]
[assembly: AssemblyInformationalVersion( "0.1" )]
#if DEBUG
[assembly: InternalsVisibleTo( "NLiblet.ServiceLocator.Test" )]
#endif
| #region -- License Terms --
//
// NLiblet
//
// Copyright (C) 2011 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "NLiblet.ServiceLocator" )]
[assembly: AssemblyDescription( "NLiblet simple service locator" )]
[assembly: AssemblyProduct( "NLiblet" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2011" )]
[assembly: CLSCompliant( true )]
[assembly: AssemblyVersion( "1.0.0.0" )]
[assembly: AssemblyFileVersion( "1.0.0.0" )]
[assembly: AssemblyInformationalVersion( "1.0" )]
#if DEBUG
[assembly: InternalsVisibleTo( "NLiblet.ServiceLocator.Test" )]
#endif
| apache-2.0 | C# |
6082a9ef84a494c2a366fb268d0dade40cc6569a | Change classifier's content type. | GeorgeAlexandria/CoCo | CoCo/EditorClassifierProvider.cs | CoCo/EditorClassifierProvider.cs | //------------------------------------------------------------------------------
// <copyright file="EditorClassifierProvider.cs" company="Company">
// Copyright (c) Company. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace CoCo
{
/// <summary>
/// Classifier provider. It adds the classifier to the set of classifiers.
/// </summary>
[Export(typeof(IClassifierProvider))]
[ContentType("CSharp")]
//[ContentType("text")]
internal class EditorClassifierProvider : IClassifierProvider
{
// Disable "Field is never assigned to..." compiler's warning. The field is assigned by MEF.
#pragma warning disable 649
/// <summary>
/// Classification registry to be used for getting a reference to the custom classification
/// type later.
/// </summary>
[Import]
private IClassificationTypeRegistryService classificationRegistry;
#pragma warning restore 649
/// <summary>
/// Gets a classifier for the given text buffer.
/// </summary>
/// <param name="textBuffer">The <see cref="ITextBuffer"/> to classify.</param>
/// <returns>
/// A classifier for the text buffer, or null if the provider cannot do so in its current state.
/// </returns>
public IClassifier GetClassifier(ITextBuffer textBuffer)
{
return textBuffer.Properties.GetOrCreateSingletonProperty(() => new EditorClassifier(classificationRegistry));
}
}
} | //------------------------------------------------------------------------------
// <copyright file="EditorClassifierProvider.cs" company="Company">
// Copyright (c) Company. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace CoCo
{
/// <summary>
/// Classifier provider. It adds the classifier to the set of classifiers.
/// </summary>
[Export(typeof(IClassifierProvider))]
[ContentType("text")]
internal class EditorClassifierProvider : IClassifierProvider
{
// Disable "Field is never assigned to..." compiler's warning. The field is assigned by MEF.
#pragma warning disable 649
/// <summary>
/// Classification registry to be used for getting a reference to the custom classification
/// type later.
/// </summary>
[Import]
private IClassificationTypeRegistryService classificationRegistry;
#pragma warning restore 649
/// <summary>
/// Gets a classifier for the given text buffer.
/// </summary>
/// <param name="textBuffer">The <see cref="ITextBuffer"/> to classify.</param>
/// <returns>
/// A classifier for the text buffer, or null if the provider cannot do so in its current state.
/// </returns>
public IClassifier GetClassifier(ITextBuffer textBuffer)
{
return textBuffer.Properties.GetOrCreateSingletonProperty(() => new EditorClassifier(classificationRegistry));
}
}
} | mit | C# |
b979fd20a5856f55578a652c92d057753bee549f | return dashboard page on submit click | ProtoTest/ProtoTest.Golem,ProtoTest/ProtoTest.Golem | Golem.PageObjects.Cael/Assessments/ReviewAssessmentConfirmPage.cs | Golem.PageObjects.Cael/Assessments/ReviewAssessmentConfirmPage.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using Golem.Framework;
using OpenQA.Selenium;
namespace Golem.PageObjects.Cael
{
public class ReviewAssessmentConfirmPage : BasePageObject
{
string noCreditText = "Credit Not Recommended";
string creditRecommendedText = "Credit Recommended!";
Element Page_Title = new Element("Page Title", By.XPath("//div[@id='container_content_inner']/div/h1"));
Element GoBackAndEdit_Link = new Element("Go back and edit assessment link", By.Id("p_lt_ctl02_pageplaceholder_p_lt_ctl00_LC_ReviewAssessment_editAssessmentHyperLink"));
Element Submit_Button = new Element("Submit this assessment button", By.Id("p_lt_ctl02_pageplaceholder_p_lt_ctl00_LC_ReviewAssessment_submitAssessmentButton"));
Element CreditRecommendation_Label = new Element("Credit Recommended Label", By.XPath("//div[@class='totals']//div[@class='t-left']/div"));
Element TotalScore_Label = new Element("Total Score Label", By.XPath("//div[@class='totals']//div[@class='t-right']/span[2]"));
public AssessPortfolioPage GoBackAndEditAssessment()
{
GoBackAndEdit_Link.Click();
return new AssessPortfolioPage();
}
public DashBoardAssessmentPage SubmitAssessment()
{
Submit_Button.Click();
return new DashBoardAssessmentPage();
}
public ReviewAssessmentConfirmPage VerifyCreditRecommendation(string score_str, Boolean credit_recommended)
{
TotalScore_Label.VerifyText(score_str);
if (credit_recommended)
{
CreditRecommendation_Label.VerifyText(creditRecommendedText.Trim());
}
else
{
CreditRecommendation_Label.VerifyText(noCreditText);
}
return this;
}
public override void WaitForElements()
{
Page_Title.VerifyVisible(30).VerifyText("Review Assessment");
Submit_Button.VerifyVisible(30).VerifyValue("Submit This Assessment");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using Golem.Framework;
using OpenQA.Selenium;
namespace Golem.PageObjects.Cael
{
public class ReviewAssessmentConfirmPage : BasePageObject
{
string noCreditText = "Credit Not Recommended";
string creditRecommendedText = "Credit Recommended!";
Element Page_Title = new Element("Page Title", By.XPath("//div[@id='container_content_inner']/div/h1"));
Element GoBackAndEdit_Link = new Element("Go back and edit assessment link", By.Id("p_lt_ctl02_pageplaceholder_p_lt_ctl00_LC_ReviewAssessment_editAssessmentHyperLink"));
Element Submit_Button = new Element("Submit this assessment button", By.Id("p_lt_ctl02_pageplaceholder_p_lt_ctl00_LC_ReviewAssessment_submitAssessmentButton"));
Element CreditRecommendation_Label = new Element("Credit Recommended Label", By.XPath("//div[@class='totals']//div[@class='t-left']/div"));
Element TotalScore_Label = new Element("Total Score Label", By.XPath("//div[@class='totals']//div[@class='t-right']/span[2]"));
public AssessPortfolioPage GoBackAndEditAssessment()
{
GoBackAndEdit_Link.Click();
return new AssessPortfolioPage();
}
public void SubmitAssessment()
{
Submit_Button.Click();
}
public ReviewAssessmentConfirmPage VerifyCreditRecommendation(string score_str, Boolean credit_recommended)
{
TotalScore_Label.VerifyText(score_str);
if (credit_recommended)
{
CreditRecommendation_Label.VerifyText(creditRecommendedText.Trim());
}
else
{
CreditRecommendation_Label.VerifyText(noCreditText);
}
return this;
}
public override void WaitForElements()
{
Page_Title.VerifyVisible(30).VerifyText("Review Assessment");
Submit_Button.VerifyVisible(30).VerifyValue("Submit This Assessment");
}
}
} | apache-2.0 | C# |
b16273fa8bfb9ad445dcc829a4582fc95e4e1653 | Build warnings are annoying | MassTransit/MassTransit,phatboyg/MassTransit,phatboyg/MassTransit,MassTransit/MassTransit | src/Containers/MassTransit.ExtensionsDependencyInjectionIntegration/MultiBus/IServiceCollectionBusConfigurator.cs | src/Containers/MassTransit.ExtensionsDependencyInjectionIntegration/MultiBus/IServiceCollectionBusConfigurator.cs | namespace MassTransit.ExtensionsDependencyInjectionIntegration.MultiBus
{
using System;
[Obsolete("Replace with IServiceCollectionBusConfigurator<TBus>. This interface will be removed in next versions.")]
public interface IServiceCollectionConfigurator<in TBus> :
IServiceCollectionBusConfigurator
where TBus : class, IBus
{
}
public interface IServiceCollectionBusConfigurator<in TBus> :
#pragma warning disable 618
IServiceCollectionConfigurator<TBus>
where TBus : class, IBus
{
}
}
| namespace MassTransit.ExtensionsDependencyInjectionIntegration.MultiBus
{
using System;
[Obsolete("Replace with IServiceCollectionBusConfigurator<TBus>. This interface will be removed in next versions.")]
public interface IServiceCollectionConfigurator<in TBus> :
IServiceCollectionBusConfigurator
where TBus : class, IBus
{
}
public interface IServiceCollectionBusConfigurator<in TBus> :
IServiceCollectionConfigurator<TBus>
where TBus : class, IBus
{
}
}
| apache-2.0 | C# |
0fc196501f33bd88d8e8ee352e812b05c73cfaa2 | Fix typo. (#66) | CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork | trunk/CoverageTest/Invoices-CS-DAL-DTO/Invoices.DataAccess/SupplierProductInfoDto.cs | trunk/CoverageTest/Invoices-CS-DAL-DTO/Invoices.DataAccess/SupplierProductInfoDto.cs | namespace Invoices.DataAccess
{
public partial class SupplierProductInfoDto
{
}
}
| namespace Invoices.DataAccess
{
public partial class SupplierProductItnfoDto
{
}
}
| mit | C# |
933f5d0807e33f9215d441b658d3c6c52a525bfb | Switch redth.codes to https (#348) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/JonDick.cs | src/Firehose.Web/Authors/JonDick.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class JonDick : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Jon";
public string LastName => "Dick";
public string ShortBioOrTagLine => "";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "redth";
public string GravatarHash => "ad73e52d7e4d89e904e7c4cfd91fc2b9";
public string StateOrRegion => "Ontario, Canada";
public Uri WebSite => new Uri("https://redth.codes");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://redth.codes/feed/"); }
}
public string GitHubHandle => "redth";
public GeoPosition Position => new GeoPosition(51.2537750, -85.3232140);
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class JonDick : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Jon";
public string LastName => "Dick";
public string ShortBioOrTagLine => "";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "redth";
public string GravatarHash => "ad73e52d7e4d89e904e7c4cfd91fc2b9";
public string StateOrRegion => "Ontario, Canada";
public Uri WebSite => new Uri("http://redth.codes");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://redth.codes/feed/"); }
}
public string GitHubHandle => "redth";
public GeoPosition Position => new GeoPosition(51.2537750, -85.3232140);
}
}
| mit | C# |
78f30e05c0f089f9117f6d88ed3241c783400fbe | Fix off-by-one click error | royd/MvvmCross-Prototype | Common.Droid/Views/HeaderAdapter.cs | Common.Droid/Views/HeaderAdapter.cs | using Android.Content;
using Android.Views;
using MvvmCross.Binding.Droid.BindingContext;
using MvvmCross.Binding.Droid.Views;
namespace Common.Droid.Views
{
public class HeaderAdapter : MvxAdapter
{
public HeaderAdapter(Context context)
: this(context, MvxAndroidBindingContextHelpers.Current())
{
}
public HeaderAdapter(Context context, IMvxAndroidBindingContext bindingContext)
: base(context, bindingContext)
{
m_bindingContext = bindingContext;
}
public int HeaderTemplateId
{
get; set;
}
public override int Count
{
get
{
return HeaderTemplateId == 0 ? base.Count : base.Count + 1;
}
}
public override int GetPosition(object item)
{
int position = base.GetPosition(item);
if (HeaderTemplateId != 0 && position != -1)
position++;
return position;
}
public override object GetRawItem(int position)
{
object item;
if (HeaderTemplateId == 0)
item = base.GetRawItem(position);
else if (position == 0)
item = m_bindingContext;
else
item = base.GetRawItem(position - 1);
return item;
}
protected override View GetView(int position, View convertView, ViewGroup parent, int templateId)
{
if (m_headerView == convertView)
convertView = null;
View view;
if (HeaderTemplateId == 0)
view = base.GetView(position, convertView, parent, templateId);
else if (position == 0)
view = m_headerView ?? (m_headerView = m_bindingContext.BindingInflate(HeaderTemplateId, null));
else
view = base.GetView(position, convertView, parent, templateId);
return view;
}
readonly IMvxAndroidBindingContext m_bindingContext;
View m_headerView;
}
}
| using Android.Content;
using Android.Views;
using MvvmCross.Binding.Droid.BindingContext;
using MvvmCross.Binding.Droid.Views;
namespace Common.Droid.Views
{
public class HeaderAdapter : MvxAdapter
{
public HeaderAdapter(Context context)
: this(context, MvxAndroidBindingContextHelpers.Current())
{
}
public HeaderAdapter(Context context, IMvxAndroidBindingContext bindingContext)
: base(context, bindingContext)
{
m_bindingContext = bindingContext;
}
public int HeaderTemplateId
{
get; set;
}
public override int Count
{
get
{
return HeaderTemplateId == 0 ? base.Count : base.Count + 1;
}
}
protected override View GetView(int position, View convertView, ViewGroup parent, int templateId)
{
if (m_headerView != null && m_headerView == convertView)
convertView = null;
View view;
if (HeaderTemplateId == 0)
view = base.GetView(position, convertView, parent, templateId);
else if (position == 0)
view = m_headerView ?? (m_headerView = m_bindingContext.BindingInflate(HeaderTemplateId, null));
else
view = base.GetView(position - 1, convertView, parent, templateId);
return view;
}
readonly IMvxAndroidBindingContext m_bindingContext;
View m_headerView;
}
}
| mit | C# |
70b75aa6c981ddf50de1025c063cb42472c54647 | Update index.cshtml | reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website | input/contribute/community/index.cshtml | input/contribute/community/index.cshtml | Order: 100
---
@Html.Partial("_ChildPages")
http://olivierlacan.com/posts/ruby-heroes-farewell/
| Order: 100
---
@Html.Partial("_ChildPages") | mit | C# |
391576039c6f7fc6dfaae300d5447a1888a34b6d | Add text to fullscreen test. | eylvisaker/AgateLib | Tests/DisplayTests/FullScreen.cs | Tests/DisplayTests/FullScreen.cs | using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
string text = "Press Esc or Tilde to exit." + Environment.NewLine + "Starting Text";
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
Keyboard.KeyDown += new InputEventHandler(Keyboard_KeyDown);
FontSurface font = FontSurface.AgateSans14;
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false &&
Keyboard.Keys[KeyCode.Tilde] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
font.DrawText(text);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
void Keyboard_KeyDown(InputEventArgs e)
{
text += e.KeyString;
}
}
} | using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
} | mit | C# |
22f67d455b62bf05dd3638a4c4586a40d3e1e7ed | Fix NullReference exception | MrHant/tiver-fowl.Drivers,MrHant/tiver-fowl.Drivers | Tiver.Fowl.Drivers/Extensions.cs | Tiver.Fowl.Drivers/Extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Tiver.Fowl.Drivers
{
public static class Extensions
{
public static IEnumerable<Exception> GetInnerExceptions(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var innerException = ex.InnerException;
do
{
yield return innerException;
innerException = innerException?.InnerException;
} while (innerException != null);
}
public static string GetInnerExceptionMessages(this Exception ex)
{
if (ex == null)
{
return string.Empty;
}
return string.Join(" ", ex.GetInnerExceptions().Select(e => e?.Message ?? string.Empty));
}
public static string GetAllExceptionsMessages(this Exception ex)
{
return ex.Message + " " + ex.GetInnerExceptionMessages();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Tiver.Fowl.Drivers
{
public static class Extensions
{
public static IEnumerable<Exception> GetInnerExceptions(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var innerException = ex.InnerException;
do
{
yield return innerException;
innerException = innerException.InnerException;
} while (innerException != null);
}
public static string GetInnerExceptionMessages(this Exception ex)
{
if (ex == null)
{
return string.Empty;
}
return string.Join(" ", ex.GetInnerExceptions().Select(e => e.Message));
}
public static string GetAllExceptionsMessages(this Exception ex)
{
return ex.Message + " " + ex.GetInnerExceptionMessages();
}
}
} | mit | C# |
bc6ec71cff9deebd34f309420da7ae4238719130 | Add base url | mono0926/xxx-server-proto,mono0926/xxx-server-proto,mono0926/xxx-server-proto,mono0926/xxx-server-proto | JoinProto/App_Start/WebApiConfig.cs | JoinProto/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace JoinProto
{
public static class WebApiConfig
{
#if DEBUG
public const string BaseUrl = "http://joinproto.azurewebsites.net/api/";
#else
public const string BaseUrl = "http://localhost:1235/api/";
#endif
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace JoinProto
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit | C# |
a8e0beda3043084a547ef6382c5776dbbb68bf2c | Include the exception when logging in WebAssemblyErrorBoundaryLogger (#39202) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyErrorBoundaryLogger.cs | src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyErrorBoundaryLogger.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Components.WebAssembly.Services;
internal sealed class WebAssemblyErrorBoundaryLogger : IErrorBoundaryLogger
{
private readonly ILogger<ErrorBoundary> _errorBoundaryLogger;
public WebAssemblyErrorBoundaryLogger(ILogger<ErrorBoundary> errorBoundaryLogger)
{
_errorBoundaryLogger = errorBoundaryLogger ?? throw new ArgumentNullException(nameof(errorBoundaryLogger)); ;
}
public ValueTask LogErrorAsync(Exception exception)
{
// For, client-side code, all internal state is visible to the end user. We can just
// log directly to the console.
_errorBoundaryLogger.LogError(exception.ToString(), exception);
return ValueTask.CompletedTask;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Components.WebAssembly.Services;
internal class WebAssemblyErrorBoundaryLogger : IErrorBoundaryLogger
{
private readonly ILogger<ErrorBoundary> _errorBoundaryLogger;
public WebAssemblyErrorBoundaryLogger(ILogger<ErrorBoundary> errorBoundaryLogger)
{
_errorBoundaryLogger = errorBoundaryLogger ?? throw new ArgumentNullException(nameof(errorBoundaryLogger)); ;
}
public ValueTask LogErrorAsync(Exception exception)
{
// For, client-side code, all internal state is visible to the end user. We can just
// log directly to the console.
_errorBoundaryLogger.LogError(exception.ToString());
return ValueTask.CompletedTask;
}
}
| apache-2.0 | C# |
ad19a7e357dac7f5021c71a406e079596e79b055 | Update EntityUnitOfWork.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityUnitOfWork.cs | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityUnitOfWork.cs | using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityUnitOfWork : UnitOfWorkBase
{
private readonly DbContext[] _dbContexts;
public EntityUnitOfWork(DbContext[] dbContexts)
{
_dbContexts = dbContexts;
}
public override async Task CompleteAsync(CancellationToken cancellationToken)
{
var tasks = _dbContexts.Select(dbContext => dbContext.SaveChangesAsync(cancellationToken)).ToArray();
await Task.WhenAll(tasks);
}
public override Task DiscardAsync(CancellationToken cancellationToken)
{
_dbContexts.Do(dbContext => dbContext.ChangeTracker.Clear());
return Task.CompletedTask;
}
protected override bool IsDirty()
{
return _dbContexts.Any(dbContext => dbContext.ChangeTracker.HasChanges());
}
}
} | using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityUnitOfWork : UnitOfWorkBase
{
private readonly DbContext[] _dbContexts;
public EntityUnitOfWork(DbContext[] dbContexts)
{
_dbContexts = dbContexts;
}
public override async Task CompleteAsync(CancellationToken cancellationToken)
{
var tasks = _dbContexts.Select(dbContext => dbContext.SaveChangesAsync(cancellationToken)).ToArray();
await Task.WhenAll(tasks);
}
protected override bool IsDirty()
{
return _dbContexts.Any(dbContext => dbContext.ChangeTracker.HasChanges());
}
}
} | mit | C# |
52963046d46133b8b7050ab848de3a8b39a76519 | Add namespace | schlos/denver-schedules-api,codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api,schlos/denver-schedules-api | Schedules.API/Modules/SendModule.cs | Schedules.API/Modules/SendModule.cs | using Nancy;
using Schedules.API.Tasks.Sending;
using Simpler;
using Nancy.ModelBinding;
using Schedules.API.Models;
namespace Schedules.API.Modules
{
public class SendModule : NancyModule
{
public SendModule ()
{
Post["/reminders/email/send"] = parameters => {
var postRemindersEmailSend = Task.New<PostRemindersEmailSend>();
postRemindersEmailSend.In.Send = this.Bind<Send>();
postRemindersEmailSend.Execute();
return Response.AsJson(
postRemindersEmailSend.Out.Send,
HttpStatusCode.Created
);
};
}
}
}
| using Nancy;
using Schedules.API.Tasks.Sending;
using Simpler;
using Nancy.ModelBinding;
using Schedules.API.Models;
public class SendModule : NancyModule
{
public SendModule ()
{
Post["/reminders/email/send"] = parameters => {
var postRemindersEmailSend = Task.New<PostRemindersEmailSend>();
postRemindersEmailSend.In.Send = this.Bind<Send>();
postRemindersEmailSend.Execute();
return Response.AsJson(
postRemindersEmailSend.Out.Send,
HttpStatusCode.Created
);
};
}
}
| mit | C# |
2337b07659cd8ecd9de40052a430a5813c0462ea | Fix wrong parameter name | ProgTrade/SharpMath | SharpMath/Trigonometry/Converter.cs | SharpMath/Trigonometry/Converter.cs | using System;
namespace SharpMath.Trigonometry
{
public class Converter
{
public static double DegreesToRadians(double degrees)
{
return degrees * (Math.PI / 180);
}
public static double RadiansToDegrees(double radians)
{
return radians * (180 / Math.PI);
}
}
} | using System;
namespace SharpMath.Trigonometry
{
public class Converter
{
public static double DegreesToRadians(double degrees)
{
return degrees * (Math.PI / 180);
}
public static double RadiansToDegrees(double degrees)
{
return degrees * (180 / Math.PI);
}
}
} | mit | C# |
17edd7f05f0835078437718b7a57be7625cc74e4 | Remove confusing date format in summary messages. | nozzlegear/ShopifySharp,addsb/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Filters/OrderFilter.cs | ShopifySharp/Filters/OrderFilter.cs | using System;
using Newtonsoft.Json;
using ShopifySharp.Enums;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and
/// <see cref="OrderService.ListAsync(OrderFilter)"/> results.
/// </summary>
public class OrderFilter : ListFilter
{
/// <summary>
/// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any".
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided".
/// </summary>
[JsonProperty("financial_status")]
public string FinancialStatus { get; set; }
/// <summary>
/// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status.
/// </summary>
[JsonProperty("fulfillment_status")]
public string FulfillmentStatus { get; set; }
/// <summary>
/// Show orders imported after date.
/// </summary>
[JsonProperty("processed_at_min")]
public DateTime? ProcessedAtMin { get; set; }
/// <summary>
/// Show orders imported before date.
/// </summary>
[JsonProperty("processed_at_max")]
public DateTime? ProcessedAtMax { get; set; }
/// <summary>
/// Show orders attributed to a specific app. Valid values are the app ID to filter on (eg. 123) or a value of "current" to only show orders for the app currently consuming the API.
/// </summary>
[JsonProperty("attribution_app_id")]
public string AttributionAppId { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using ShopifySharp.Enums;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and
/// <see cref="OrderService.ListAsync(OrderFilter)"/> results.
/// </summary>
public class OrderFilter : ListFilter
{
/// <summary>
/// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any".
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided".
/// </summary>
[JsonProperty("financial_status")]
public string FinancialStatus { get; set; }
/// <summary>
/// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status.
/// </summary>
[JsonProperty("fulfillment_status")]
public string FulfillmentStatus { get; set; }
/// <summary>
/// Show orders imported after date (format: 2014-04-25T16:15:47-04:00)
/// </summary>
[JsonProperty("processed_at_min")]
public DateTime? ProcessedAtMin { get; set; }
/// <summary>
/// Show orders imported before date (format: 2014-04-25T16:15:47-04:00)
/// </summary>
[JsonProperty("processed_at_max")]
public DateTime? ProcessedAtMax { get; set; }
/// <summary>
/// Show orders attributed to a specific app. Valid values are the app ID to filter on (eg. 123) or a value of "current" to only show orders for the app currently consuming the API.
/// </summary>
[JsonProperty("attribution_app_id")]
public string AttributionAppId { get; set; }
}
}
| mit | C# |
2ed3975ff80528cd6fe3d21a323918f9d9545784 | Package Update #CHANGE: Pushed AdamsLair.WinForms1.0.6 | windygu/winforms,AdamsLair/winforms | WinForms/Properties/AssemblyInfo.cs | WinForms/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.6")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.5")]
| mit | C# |
6439ed8ba7881c10159c0617644e48dc274409cc | change the title | wli3/yum-sale,wli3/yum-sale,wli3/yum-sale | YumSale/Views/Shared/_Layout.cshtml | YumSale/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Yumsale</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<link href="~/Content/flash-messages.css" rel="stylesheet"/>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new {area = ""}, new {@class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr/>
<footer>
<p>© @DateTime.Now.Year - William Lee</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/metro-bootstrap")
@RenderSection("scripts", false)
</body>
</html> | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<link href="~/Content/flash-messages.css" rel="stylesheet"/>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new {area = ""}, new {@class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr/>
<footer>
<p>© @DateTime.Now.Year - William Lee</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/metro-bootstrap")
@RenderSection("scripts", false)
</body>
</html> | mit | C# |
26e96570d0c78dbbff350e852b7432280756f43e | Update index.cshtml | bolshakovinka/ApmathCloudBolshakov | SITE/index.cshtml | SITE/index.cshtml | @{
var txt = DateTime.Now;
double res = 0;
double[] x;
if (IsPost)
{
string line = Request.Form["Values"];
string[] values=line.Split(new Char[] { ',', ' '});
x = new double[values.Length];
for (int i = 0; i < values.Length; i++)
{
x[i] = Convert.ToDouble(values[i]);
res += x[i];
}
res /= x.Length;
}
}
<html>
<body>
<h2>Mat Ozhidanie</h2><br />
<form method="post">
<input type="text" name="Values" value=""/>
<input type="submit" value="Submit" class="submit" />
</form>
<p>The dateTime is @txt</p>
<text>Мат ожидание</text><br />
<p>@res</p>
</body>
</html>
| @{
var txt = DateTime.Now;
}
<html>
<body>
<p>The dateTime is @txt</p>
</body>
</html> | mit | C# |
d723fcd9d831947286045cc52d6503e0915a66fe | clean up test syntax | msackton/FluentAssertions | Tests/FluentAssertions.Shared.Specs/EnumAssertionSpecs.cs | Tests/FluentAssertions.Shared.Specs/EnumAssertionSpecs.cs | using System;
using System.Collections.Generic;
using System.Text;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System.Reflection.Emit;
using System.Reflection;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
public enum EnumULong : ulong
{
UInt64Max = UInt64.MaxValue,
UInt64LessOne = UInt64.MaxValue-1,
Int64Max = Int64.MaxValue
}
public enum EnumLong : long
{
Int64Max = Int64.MaxValue,
Int64LessOne = Int64.MaxValue-1
}
[TestClass]
public class EnumAssertionSpecs
{
[TestMethod]
public void Should_succeed_when_asserting_large_enum_equals_large_enum()
{
// Arrange
var enumOne = EnumULong.UInt64Max;
var enumTwo = EnumULong.UInt64Max;
// Act
Action act = () => enumOne.ShouldBeEquivalentTo(enumTwo);
// Assert
act.ShouldNotThrow();
}
[TestMethod]
public void Should_succeed_when_asserting_large_enum_equals_large_enum_of_different_underlying_types()
{
// Arrange
var enumOne = EnumLong.Int64Max;
var enumTwo = EnumULong.Int64Max;
// Act
Action act = () => enumOne.ShouldBeEquivalentTo(enumTwo);
// Assert
act.ShouldNotThrow();
}
[TestMethod]
public void Sshould_fail_when_asserting_large_enum_equals_different_large_enum_of_different_underlying_types()
{
// Arrange
var enumOne = EnumLong.Int64LessOne;
var enumTwo = EnumULong.UInt64Max;
// Act
Action act = () => enumOne.ShouldBeEquivalentTo(enumTwo);
// Assert
act.ShouldThrow<AssertFailedException>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System.Reflection.Emit;
using System.Reflection;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
public enum EnumULong : ulong
{
UInt64Max = UInt64.MaxValue,
UInt64LessOne = UInt64.MaxValue-1,
Int64Max = Int64.MaxValue
}
public enum EnumLong : long
{
Int64Max = Int64.MaxValue,
Int64LessOne = Int64.MaxValue-1
}
[TestClass]
public class EnumAssertionSpecs
{
[TestMethod]
public void ShouldBeEquivalentTo_should_succeed_when_asserting_large_enum_equals_large_enum()
{
Action act = () => EnumULong.UInt64Max.ShouldBeEquivalentTo(EnumULong.UInt64Max);
act.ShouldNotThrow();
}
[TestMethod]
public void ShouldBeEquivalentTo_should_succeed_when_asserting_large_enum_equals_large_enum_of_different_underlying_types()
{
Action act = () => EnumLong.Int64Max.ShouldBeEquivalentTo(EnumULong.Int64Max);
act.ShouldNotThrow();
}
[TestMethod]
public void ShouldBeEquivalentTo_should_fail_when_asserting_large_enum_equals_different_large_enum_of_different_underlying_types()
{
Action act = () => EnumLong.Int64LessOne.ShouldBeEquivalentTo(EnumULong.UInt64Max);
act.ShouldThrow<AssertFailedException>();
}
}
}
| apache-2.0 | C# |
09c9c859efef8c5acc1c17a5610b5ea27474b428 | Edit Debug.cs | 60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope | QueueDataGraphic/QueueDataGraphic/CSharpFiles/Debug.cs | QueueDataGraphic/QueueDataGraphic/CSharpFiles/Debug.cs | /********************************************************************
* Develop by Jimmy Hu *
* This program is licensed under the Apache License 2.0. *
* Debug.cs *
* 本檔案用於宣告偵錯相關工具物件 *
********************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{
class Debug
{
/// <summary>
/// DebugMode would be setted "true" during debugging.
/// 在偵錯模式中將DebugMode設為true
/// </summary>
public readonly static bool DebugMode = true;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{
class Debug
{
/// <summary>
/// DebugMode would be setted "true" during debugging.
/// 在偵錯模式中將DebugMode設為true
/// </summary>
public readonly static bool DebugMode = true;
}
}
| apache-2.0 | C# |
e7eac42a14528ad8bd991a9b953c3c856254f346 | add sence | bstaykov/DO-NOT-OPEN-IN-ANY-CIRCUMSTANCES-CLIENT,bstaykov/DO-NOT-OPEN-IN-ANY-CIRCUMSTANCES-CLIENT,bstaykov/DO-NOT-OPEN-IN-ANY-CIRCUMSTANCES-CLIENT | ServicesCORS/TeamsServices/Views/Shared/_Layout.cshtml | ServicesCORS/TeamsServices/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-2283330195766479",
enable_page_level_ads: true
});
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
5094bd4ac1d8d4337f3721f5a93357d36e6cd380 | Extend PlayerTags to accept name or entityID | Morphan1/Voxalia,Morphan1/Voxalia,Morphan1/Voxalia | Voxalia/ServerGame/TagSystem/TagBases/PlayerTagBase.cs | Voxalia/ServerGame/TagSystem/TagBases/PlayerTagBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
long pid;
if (long.TryParse(pname, out pid))
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.EID == pid)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
else
{
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frenetic.TagHandlers;
using Frenetic.TagHandlers.Objects;
using Voxalia.ServerGame.TagSystem.TagObjects;
using Voxalia.ServerGame.ServerMainSystem;
using Voxalia.ServerGame.EntitySystem;
using Voxalia.Shared;
namespace Voxalia.ServerGame.TagSystem.TagBases
{
class PlayerTagBase : TemplateTags
{
Server TheServer;
// <--[tag]
// @Base player[<TextTag>]
// @Group Entities
// @ReturnType PlayerTag
// @Returns the player with the given name.
// -->
public PlayerTagBase(Server tserver)
{
Name = "player";
TheServer = tserver;
}
public override string Handle(TagData data)
{
string pname = data.GetModifier(0).ToLower();
foreach (PlayerEntity player in TheServer.Players)
{
if (player.Name.ToLower() == pname)
{
return new PlayerTag(player).Handle(data.Shrink());
}
}
return new TextTag("{NULL}").Handle(data.Shrink());
}
}
}
| mit | C# |
dd36df76c8a2f8d1ac2a91a14de65a56f42b8d3b | Update IPointShape.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Model/Shapes/IPointShape.cs | src/Core2D/Model/Shapes/IPointShape.cs | using Core2D.Renderer;
namespace Core2D.Shapes
{
/// <summary>
/// Defines point shape contract.
/// </summary>
public interface IPointShape : IBaseShape, IStringExporter
{
/// <summary>
/// Gets or sets X coordinate of point.
/// </summary>
double X { get; set; }
/// <summary>
/// Gets or sets Y coordinate of point.
/// </summary>
double Y { get; set; }
/// <summary>
/// Gets or sets point alignment.
/// </summary>
PointAlignment Alignment { get; set; }
}
}
|
using Core2D.Renderer;
namespace Core2D.Shapes
{
/// <summary>
/// Defines point shape contract.
/// </summary>
public interface IPointShape : IBaseShape
{
/// <summary>
/// Gets or sets X coordinate of point.
/// </summary>
double X { get; set; }
/// <summary>
/// Gets or sets Y coordinate of point.
/// </summary>
double Y { get; set; }
/// <summary>
/// Gets or sets point alignment.
/// </summary>
PointAlignment Alignment { get; set; }
}
}
| mit | C# |
9fec055eaf0078672636b84bd218f75bf53921a2 | Update BinanceRebate.cs (#1131) | JKorf/Binance.Net | Binance.Net/Objects/Models/Spot/BinanceRebate.cs | Binance.Net/Objects/Models/Spot/BinanceRebate.cs | using System;
using System.Collections.Generic;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
namespace Binance.Net.Objects.Models.Spot
{
/// <summary>
/// Rebates page wrapper
/// </summary>
public class BinanceRebateWrapper
{
/// <summary>
/// The current page
/// </summary>
public int Page { get; set; }
/// <summary>
/// Total number of records
/// </summary>
public int TotalRecords { get; set; }
/// <summary>
/// Total number of pages
/// </summary>
public int TotalPages { get; set; }
/// <summary>
/// Rebate data for this page
/// </summary>
public IEnumerable<BinanceRebate> Data { get; set; } = Array.Empty<BinanceRebate>();
}
/// <summary>
/// Rebate info
/// </summary>
public class BinanceRebate
{
/// <summary>
/// The asset
/// </summary>
public string Asset { get; set; } = string.Empty;
/// <summary>
/// Type of rebate
/// </summary>
public RebateType Type { get; set; }
/// <summary>
/// Quantity
/// </summary>
[JsonProperty("amount")]
public decimal Quantity { get; set; }
/// <summary>
/// Last udpate time
/// </summary>
[JsonConverter(typeof(DateTimeConverter))]
public DateTime UpdateTime { get; set; }
}
}
| using System;
using System.Collections.Generic;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
namespace Binance.Net.Objects.Models.Spot
{
/// <summary>
/// Rebates page wrapper
/// </summary>
public class BinanceRebateWrapper
{
/// <summary>
/// The current page
/// </summary>
public int Page { get; set; }
/// <summary>
/// Total number of records
/// </summary>
public int TotalRecords { get; set; }
/// <summary>
/// Total number of pages
/// </summary>
public int TotalPages { get; set; }
/// <summary>
/// Rebate data for this page
/// </summary>
public IEnumerable<BinanceRebate> Data { get; set; } = Array.Empty<BinanceRebate>();
}
/// <summary>
/// Rebate info
/// </summary>
public class BinanceRebate
{
/// <summary>
/// The asset
/// </summary>
public string Asset { get; set; } = string.Empty;
/// <summary>
/// Type of rebate
/// </summary>
public RebateType Type { get; set; }
/// <summary>
/// Quantity
/// </summary>
public decimal Quantity { get; set; }
/// <summary>
/// Last udpate time
/// </summary>
[JsonConverter(typeof(DateTimeConverter))]
public DateTime UpdateTime { get; set; }
}
}
| mit | C# |
3bfff9f080d9ed80f6b0e688e82ecbc6c2edf0a1 | Fix unit tests | burningice2866/CompositeC1Contrib.FormBuilder,burningice2866/CompositeC1Contrib.FormBuilder,burningice2866/CompositeC1Contrib.FormBuilder | FormBuilder.Test/Validation/BaseValidatorTest.cs | FormBuilder.Test/Validation/BaseValidatorTest.cs | using System;
using System.Collections.Generic;
using CompositeC1Contrib.FormBuilder;
using CompositeC1Contrib.FormBuilder.Validation;
using System.Linq;
using NUnit.Framework;
namespace FormBuilder.Test.Validation
{
public abstract class BaseValidatorTest<T>
{
private FormFieldModel _field;
private readonly FormValidationAttribute _validator;
protected BaseValidatorTest(Func<FormValidationAttribute> validatorCreator)
{
_validator = validatorCreator();
}
[TestFixtureSetUp]
public void Init()
{
var model = new FormModel("test.test");
_field = new FormFieldModel(model, "test", typeof(T), new List<Attribute>());
}
protected FormValidationRule CreateRule(T value)
{
var form = new Form(_field.OwningForm);
var field = new FormField(_field, form);
field.Value = value;
return _validator.CreateRule(field);
}
}
}
| using System;
using System.Collections.Generic;
using CompositeC1Contrib.FormBuilder;
using CompositeC1Contrib.FormBuilder.Validation;
using System.Linq;
using NUnit.Framework;
namespace FormBuilder.Test.Validation
{
public abstract class BaseValidatorTest<T>
{
private FormFieldModel _field;
private readonly FormValidationAttribute _validator;
protected BaseValidatorTest(Func<FormValidationAttribute> validatorCreator)
{
_validator = validatorCreator();
}
[TestFixtureSetUp]
public void Init()
{
var model = new FormModel("test.test");
_field = new FormFieldModel(model, "test", typeof(T), new List<Attribute>());
}
protected FormValidationRule CreateRule(T value)
{
var form = new Form(_field.OwningForm);
var field = form.Fields.Single(f => f.Name == _field.Name);
field.Value = value;
return _validator.CreateRule(field);
}
}
}
| mit | C# |
1f3e00ae1e1723c3f7e1057d2edaa2c7a7ae0077 | Update master | mcintyre321/FormFactory,mcintyre321/FormFactory,mcintyre321/FormFactory | FormFactory.Templates/Properties/AssemblyInfo.cs | FormFactory.Templates/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FormFactory.Templates")]
[assembly: AssemblyDescription("Install this project if you want to edit the FormFactory templates, or if you don't want to use the EmbeddedResourceVirutalPathProvider")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FormFactory.Templates")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("078332d1-c8ad-4e13-a0fe-b233c9aea78d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FormFactory.Templates")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FormFactory.Templates")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("078332d1-c8ad-4e13-a0fe-b233c9aea78d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
8d81783d5b62aded21fd1484fe242967a3df53d9 | Fix seekOffset being considered when seeking | Tom94/osu-framework,Tom94/osu-framework,default0/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,default0/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework | osu.Framework/Timing/StopwatchClock.cs | osu.Framework/Timing/StopwatchClock.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Extensions.TypeExtensions;
using System;
using System.Diagnostics;
namespace osu.Framework.Timing
{
public class StopwatchClock : Stopwatch, IAdjustableClock
{
private double seekOffset;
/// <summary>
/// Keep track of how much stopwatch time we have used at previous rates.
/// </summary>
private double rateChangeUsed;
/// <summary>
/// Keep track of the resultant time that was accumulated at previous rates.
/// </summary>
private double rateChangeAccumulated;
public StopwatchClock(bool start = false)
{
if (start)
Start();
}
public double CurrentTime => (stopwatchMilliseconds - rateChangeUsed) * rate + rateChangeAccumulated + seekOffset;
private double stopwatchMilliseconds => (double)ElapsedTicks / Frequency * 1000;
private double rate = 1;
public double Rate
{
get { return rate; }
set
{
if (rate == value) return;
rateChangeAccumulated += (stopwatchMilliseconds - rateChangeUsed) * rate;
rateChangeUsed = stopwatchMilliseconds;
rate = value;
}
}
public void ResetSpeedAdjustments() => Rate = 1;
public bool Seek(double position)
{
seekOffset = position - (CurrentTime - seekOffset);
return true;
}
public override string ToString() => $@"{GetType().ReadableName()} ({Math.Truncate(CurrentTime)}ms)";
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Extensions.TypeExtensions;
using System;
using System.Diagnostics;
namespace osu.Framework.Timing
{
public class StopwatchClock : Stopwatch, IAdjustableClock
{
private double seekOffset;
/// <summary>
/// Keep track of how much stopwatch time we have used at previous rates.
/// </summary>
private double rateChangeUsed;
/// <summary>
/// Keep track of the resultant time that was accumulated at previous rates.
/// </summary>
private double rateChangeAccumulated;
public StopwatchClock(bool start = false)
{
if (start)
Start();
}
public double CurrentTime => (stopwatchMilliseconds - rateChangeUsed) * rate + rateChangeAccumulated + seekOffset;
private double stopwatchMilliseconds => (double)ElapsedTicks / Frequency * 1000;
private double rate = 1;
public double Rate
{
get { return rate; }
set
{
if (rate == value) return;
rateChangeAccumulated += (stopwatchMilliseconds - rateChangeUsed) * rate;
rateChangeUsed = stopwatchMilliseconds;
rate = value;
}
}
public void ResetSpeedAdjustments() => Rate = 1;
public bool Seek(double position)
{
seekOffset = position - CurrentTime;
return true;
}
public override string ToString() => $@"{GetType().ReadableName()} ({Math.Truncate(CurrentTime)}ms)";
}
}
| mit | C# |
8a17b509d91d6924ec79181c4b4c99f264d0694c | Increase SpeedBonus Cap to 600BPM | peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu | osu.Game.Rulesets.Taiko/Difficulty/Evaluators/StaminaEvaluator.cs | osu.Game.Rulesets.Taiko/Difficulty/Evaluators/StaminaEvaluator.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators
{
public class StaminaEvaluator
{
/// <summary>
/// Applies a speed bonus dependent on the time since the last hit performed using this key.
/// </summary>
/// <param name="interval">The interval between the current and previous note hit using the same key.</param>
private static double speedBonus(double interval)
{
// Cap to 600bpm 1/4, 25ms note interval, 50ms key interval
// This is a measure to prevent absurdly high speed maps giving infinity/negative values.
interval = Math.Max(interval, 100);
return 60 / interval;
}
/// <summary>
/// Evaluates the minimum mechanical stamina required to play the current object. This is calculated using the
/// maximum possible interval between two hits using the same key, by alternating 2 keys for each colour.
/// </summary>
public static double EvaluateDifficultyOf(DifficultyHitObject current)
{
if (current.BaseObject is not Hit)
{
return 0.0;
}
// Find the previous hit object hit by the current key, which is two notes of the same colour prior.
TaikoDifficultyHitObject taikoCurrent = (TaikoDifficultyHitObject)current;
TaikoDifficultyHitObject? keyPrevious = taikoCurrent.PreviousMono(1);
if (keyPrevious == null)
{
// There is no previous hit object hit by the current key
return 0.0;
}
double objectStrain = 0.5; // Add a base strain to all objects
objectStrain += speedBonus(taikoCurrent.StartTime - keyPrevious.StartTime);
return objectStrain;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators
{
public class StaminaEvaluator
{
/// <summary>
/// Applies a speed bonus dependent on the time since the last hit performed using this key.
/// </summary>
/// <param name="interval">The interval between the current and previous note hit using the same key.</param>
private static double speedBonus(double interval)
{
// Cap to 300bpm 1/4, 50ms note interval, 100ms key interval
// This is a temporary measure to prevent absurdly high speed mono convert maps being rated too high
// There is a plan to replace this with detecting mono that can be hit by special techniques, and this will
// be removed when that is implemented.
interval = Math.Max(interval, 100);
return 30 / interval;
}
/// <summary>
/// Evaluates the minimum mechanical stamina required to play the current object. This is calculated using the
/// maximum possible interval between two hits using the same key, by alternating 2 keys for each colour.
/// </summary>
public static double EvaluateDifficultyOf(DifficultyHitObject current)
{
if (current.BaseObject is not Hit)
{
return 0.0;
}
// Find the previous hit object hit by the current key, which is two notes of the same colour prior.
TaikoDifficultyHitObject taikoCurrent = (TaikoDifficultyHitObject)current;
TaikoDifficultyHitObject? keyPrevious = taikoCurrent.PreviousMono(1);
if (keyPrevious == null)
{
// There is no previous hit object hit by the current key
return 0.0;
}
double objectStrain = 0.5; // Add a base strain to all objects
objectStrain += speedBonus(taikoCurrent.StartTime - keyPrevious.StartTime);
return objectStrain;
}
}
}
| mit | C# |
7d8601090336f41df99676b0b8fc79e35be20225 | Fix test regression | peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu | osu.Game.Tests/Visual/Settings/TestSceneLatencyCertifierScreen.cs | osu.Game.Tests/Visual/Settings/TestSceneLatencyCertifierScreen.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Utility;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Settings
{
public class TestSceneLatencyCertifierScreen : ScreenTestScene
{
private LatencyCertifierScreen latencyCertifier = null!;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("Load screen", () => LoadScreen(latencyCertifier = new LatencyCertifierScreen()));
AddUntilStep("wait for load", () => latencyCertifier.IsLoaded);
}
[Test]
public void TestCertification()
{
for (int i = 0; i < 4; i++)
{
clickCorrectUntilResults();
AddAssert("check at results", () => !latencyCertifier.ChildrenOfType<LatencyArea>().Any());
AddStep("hit c to continue", () => InputManager.Key(Key.C));
}
AddAssert("check at results", () => !latencyCertifier.ChildrenOfType<LatencyArea>().Any());
AddAssert("check no buttons", () => !latencyCertifier.ChildrenOfType<OsuButton>().Any());
}
private void clickCorrectUntilResults()
{
AddUntilStep("click correct button until results", () =>
{
var latencyArea = latencyCertifier
.ChildrenOfType<LatencyArea>()
.SingleOrDefault(a => a.TargetFrameRate == null);
// reached results
if (latencyArea == null)
return true;
latencyArea.ChildrenOfType<OsuButton>().Single().TriggerClick();
return false;
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Utility;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Settings
{
public class TestSceneLatencyCertifierScreen : ScreenTestScene
{
private LatencyCertifierScreen latencyCertifier = null!;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("Load screen", () => LoadScreen(latencyCertifier = new LatencyCertifierScreen()));
AddUntilStep("wait for load", () => latencyCertifier.IsLoaded);
}
[Test]
public void TestCertification()
{
for (int i = 0; i < 4; i++)
{
clickCorrectUntilResults();
AddAssert("check at results", () => !latencyCertifier.ChildrenOfType<LatencyArea>().Any());
AddStep("hit c to continue", () => InputManager.Key(Key.C));
}
AddAssert("check at results", () => !latencyCertifier.ChildrenOfType<LatencyArea>().Any());
AddAssert("check no buttons", () => !latencyCertifier.ChildrenOfType<OsuButton>().Any());
}
private void clickCorrectUntilResults()
{
AddUntilStep("click correct button until results", () =>
{
var latencyArea = latencyCertifier
.ChildrenOfType<LatencyArea>()
.SingleOrDefault(a => a.TargetFrameRate == 0);
// reached results
if (latencyArea == null)
return true;
latencyArea.ChildrenOfType<OsuButton>().Single().TriggerClick();
return false;
});
}
}
}
| mit | C# |
93a34186cc56ed72320bb86998492ede07445ada | Make the camera kick when hit by a bullet. | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content | Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs | Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs | using System.Collections.Generic;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.Interfaces.GameObjects.Components;
using Content.Server.GameObjects.Components.Mobs;
using Content.Shared.GameObjects;
namespace Content.Server.GameObjects.Components.Projectiles
{
public class ProjectileComponent : Component, ICollideSpecial, ICollideBehavior
{
public override string Name => "Projectile";
public bool IgnoreShooter = true;
private EntityUid Shooter = EntityUid.Invalid;
public Dictionary<DamageType, int> damages = new Dictionary<DamageType, int>();
/// <summary>
/// Function that makes the collision of this object ignore a specific entity so we don't collide with ourselves
/// </summary>
/// <param name="shooter"></param>
public void IgnoreEntity(IEntity shooter)
{
Shooter = shooter.Uid;
}
/// <summary>
/// Special collision override, can be used to give custom behaviors deciding when to collide
/// </summary>
/// <param name="collidedwith"></param>
/// <returns></returns>
bool ICollideSpecial.PreventCollide(ICollidable collidedwith)
{
if (IgnoreShooter && collidedwith.Owner.Uid == Shooter)
return true;
return false;
}
/// <summary>
/// Applys the damage when our projectile collides with its victim
/// </summary>
/// <param name="collidedwith"></param>
void ICollideBehavior.CollideWith(List<IEntity> collidedwith)
{
foreach (var entity in collidedwith)
{
if (entity.TryGetComponent(out DamageableComponent damage))
{
damage.TakeDamage(DamageType.Brute, 10);
}
if (entity.TryGetComponent(out CameraRecoilComponent recoilComponent)
&& Owner.TryGetComponent(out PhysicsComponent physicsComponent))
{
var direction = physicsComponent.LinearVelocity.Normalized;
recoilComponent.Kick(direction);
}
}
if (collidedwith.Count > 0)
{
Owner.Delete();
}
}
}
}
| using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.Interfaces.GameObjects.Components;
using System;
using System.Collections.Generic;
using YamlDotNet.RepresentationModel;
using Robust.Shared.Utility;
using Content.Shared.GameObjects;
namespace Content.Server.GameObjects.Components.Projectiles
{
public class ProjectileComponent : Component, ICollideSpecial, ICollideBehavior
{
public override string Name => "Projectile";
public bool IgnoreShooter = true;
private EntityUid Shooter = EntityUid.Invalid;
public Dictionary<DamageType, int> damages = new Dictionary<DamageType, int>();
/// <summary>
/// Function that makes the collision of this object ignore a specific entity so we don't collide with ourselves
/// </summary>
/// <param name="shooter"></param>
public void IgnoreEntity(IEntity shooter)
{
Shooter = shooter.Uid;
}
/// <summary>
/// Special collision override, can be used to give custom behaviors deciding when to collide
/// </summary>
/// <param name="collidedwith"></param>
/// <returns></returns>
bool ICollideSpecial.PreventCollide(ICollidable collidedwith)
{
if (IgnoreShooter && collidedwith.Owner.Uid == Shooter)
return true;
return false;
}
/// <summary>
/// Applys the damage when our projectile collides with its victim
/// </summary>
/// <param name="collidedwith"></param>
void ICollideBehavior.CollideWith(List<IEntity> collidedwith)
{
foreach(var entity in collidedwith)
{
if(entity.TryGetComponent(out DamageableComponent damage))
{
damage.TakeDamage(DamageType.Brute, 10);
}
}
if (collidedwith.Count > 0)
Owner.Delete();
}
}
}
| mit | C# |
b789b1c386ce68ac55b263e960b1d885156ed163 | Fix for parallel deployments | mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy,mmooney/Sriracha.Deploy | Sriracha.Deploy.Data/ServiceJobs/ServiceJobImpl/RunBatchDeploymentJob.cs | Sriracha.Deploy.Data/ServiceJobs/ServiceJobImpl/RunBatchDeploymentJob.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NLog;
using Sriracha.Deploy.Data.Notifications;
using Sriracha.Deploy.Data.Tasks;
using Sriracha.Deploy.Data.Deployment;
namespace Sriracha.Deploy.Data.ServiceJobs.ServiceJobImpl
{
public class RunBatchDeploymentJob : IRunBatchDeploymentJob
{
private readonly Logger _logger;
private static IDeployBatchRunner _deployBatchRunner;
//private static volatile bool _isRunning = false;
public RunBatchDeploymentJob(Logger logger, IDeployBatchRunner deployBatchRunner)
{
_logger = DIHelper.VerifyParameter(logger);
_deployBatchRunner = DIHelper.VerifyParameter(deployBatchRunner);
}
public void Execute(Quartz.IJobExecutionContext context)
{
//this._logger.Trace("Starting RunDeploymentJob.Execute");
//lock (typeof(RunBatchDeploymentJob))
//{
// if (_isRunning)
// {
// this._logger.Info("RunDeploymentJob already running");
// return;
// }
// else
// {
// _isRunning = true;
// }
//}
try
{
_deployBatchRunner.TryRunNextDeployment();
}
catch (Exception err)
{
this._logger.ErrorException("RunDeploymentJob failed: " + err.ToString(), err);
}
//finally
//{
// _isRunning = false;
//}
this._logger.Trace("Done RunDeploymentJob.Execute");
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NLog;
using Sriracha.Deploy.Data.Notifications;
using Sriracha.Deploy.Data.Tasks;
using Sriracha.Deploy.Data.Deployment;
namespace Sriracha.Deploy.Data.ServiceJobs.ServiceJobImpl
{
public class RunBatchDeploymentJob : IRunBatchDeploymentJob
{
private readonly Logger _logger;
private static IDeployBatchRunner _deployBatchRunner;
private static volatile bool _isRunning = false;
public RunBatchDeploymentJob(Logger logger, IDeployBatchRunner deployBatchRunner)
{
_logger = DIHelper.VerifyParameter(logger);
_deployBatchRunner = DIHelper.VerifyParameter(deployBatchRunner);
}
public void Execute(Quartz.IJobExecutionContext context)
{
this._logger.Trace("Starting RunDeploymentJob.Execute");
lock (typeof(RunBatchDeploymentJob))
{
if (_isRunning)
{
this._logger.Info("RunDeploymentJob already running");
return;
}
else
{
_isRunning = true;
}
}
try
{
_deployBatchRunner.TryRunNextDeployment();
}
catch (Exception err)
{
this._logger.ErrorException("RunDeploymentJob failed: " + err.ToString(), err);
}
finally
{
_isRunning = false;
}
this._logger.Trace("Done RunDeploymentJob.Execute");
}
}
}
| mit | C# |
c3c9a6da3c25cf467e6ba8cb1fb6bb53dbde46b8 | Create server side API for single multiple answer question | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| mit | C# |
b5fbd2b891e0ef510346dae4aa76a67b953c30fd | Fix label antialiasing | abstractspoon/ToDoList_Plugins,abstractspoon/ToDoList_Plugins,abstractspoon/ToDoList_Plugins | UIExension/DayViewUIExtension/DayViewUIExtensionCore/DayViewWeekLabel.cs | UIExension/DayViewUIExtension/DayViewUIExtensionCore/DayViewWeekLabel.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace DayViewUIExtension
{
[System.ComponentModel.DesignerCategory("")]
public class DayViewWeekLabel : System.Windows.Forms.Label
{
public DayViewWeekLabel()
{
}
private DateTime m_StartDate;
public DateTime StartDate
{
set
{
m_StartDate = value;
DateTime endDate = m_StartDate.AddDays(7);
if (endDate.Year == m_StartDate.Year)
{
if (endDate.Month == m_StartDate.Month)
Text = m_StartDate.ToString("MMMM yyyy");
else
Text = String.Format("{0} - {1}",
m_StartDate.ToString("MMMM"),
endDate.ToString("MMMM yyyy"));
}
else
{
Text = String.Format("{0} - {1}",
m_StartDate.ToString("MMMM yyyy"),
endDate.ToString("MMMM yyyy"),
m_StartDate.Year);
}
Invalidate();
}
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
{
pe.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
base.OnPaint(pe);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace DayViewUIExtension
{
[System.ComponentModel.DesignerCategory("")]
public class DayViewWeekLabel : System.Windows.Forms.Label
{
public DayViewWeekLabel()
{
}
private DateTime m_StartDate;
public DateTime StartDate
{
set
{
m_StartDate = value;
DateTime endDate = m_StartDate.AddDays(7);
if (endDate.Year == m_StartDate.Year)
{
if (endDate.Month == m_StartDate.Month)
Text = m_StartDate.ToString("MMMM yyyy");
else
Text = String.Format("{0} - {1}",
m_StartDate.ToString("MMMM"),
endDate.ToString("MMMM yyyy"));
}
else
{
Text = String.Format("{0} - {1}",
m_StartDate.ToString("MMMM yyyy"),
endDate.ToString("MMMM yyyy"),
m_StartDate.Year);
}
Invalidate();
}
}
}
}
| epl-1.0 | C# |
0ac33b2d3c07157cba75887a02348bf8b58dc9d8 | fix null-value in comparison | FrankyBoy/ApiDoc,FrankyBoy/ApiDoc | ApiDoc/Utility/NodeListExtensions.cs | ApiDoc/Utility/NodeListExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using ApiDoc.Models;
namespace ApiDoc.Utility
{
public static class NodeListExtensions
{
private static readonly DiffMatchPatch Dmp = new DiffMatchPatch();
public static Node Compare(this IList<Node> items, int rev1, int rev2)
{
var node1 = items.First(x => x.RevisionNumber == rev1);
var node2 = items.First(x => x.RevisionNumber == rev2);
if (node1.GetType() != node2.GetType())
throw new Exception("Cannot compare two items of different type");
if (node1 is Branch)
return new Branch
{
Name = GetPrettyHtmlDiff(node1.Name, node2.Name),
Description = GetPrettyHtmlDiff(node1.Description, node2.Description),
};
var leaf1 = node1 as Leaf;
if (leaf1 != null){
var leaf2 = (Leaf)node2;
return new Leaf
{
Name = GetPrettyHtmlDiff(leaf1.Name, node2.Name),
Description = GetPrettyHtmlDiff(leaf1.Description, node2.Description),
HttpVerb = GetPrettyHtmlDiff(leaf1.HttpVerb, leaf2.HttpVerb),
SampleRequest = GetPrettyHtmlDiff(leaf1.SampleRequest, leaf2.SampleRequest),
SampleResponse = GetPrettyHtmlDiff(leaf1.SampleResponse, leaf2.SampleResponse)
};
}
throw new Exception("Not any known type");
}
private static string GetPrettyHtmlDiff(string text1, string text2)
{
if (text1 == null)
text1 = "";
if (text2 == null)
text2 = "";
var diffs = Dmp.diff_main(text1, text2);
Dmp.diff_cleanupSemantic(diffs);
return Dmp.diff_prettyHtml(diffs);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using ApiDoc.Models;
namespace ApiDoc.Utility
{
public static class NodeListExtensions
{
private static readonly DiffMatchPatch Dmp = new DiffMatchPatch();
public static Node Compare(this IList<Node> items, int rev1, int rev2)
{
var node1 = items.First(x => x.RevisionNumber == rev1);
var node2 = items.First(x => x.RevisionNumber == rev2);
if (node1.GetType() != node2.GetType())
throw new Exception("Cannot compare two items of different type");
if (node1 is Branch)
return new Branch
{
Name = GetPrettyHtmlDiff(node1.Name, node2.Name),
Description = GetPrettyHtmlDiff(node1.Description, node2.Description),
};
var leaf1 = node1 as Leaf;
if (leaf1 != null){
var leaf2 = (Leaf)node2;
return new Leaf
{
Name = GetPrettyHtmlDiff(leaf1.Name, node2.Name),
Description = GetPrettyHtmlDiff(leaf1.Description, node2.Description),
HttpVerb = GetPrettyHtmlDiff(leaf1.HttpVerb, leaf2.HttpVerb),
SampleRequest = GetPrettyHtmlDiff(leaf1.SampleRequest, leaf2.SampleRequest),
SampleResponse = GetPrettyHtmlDiff(leaf1.SampleResponse, leaf2.SampleResponse)
};
}
throw new Exception("Not any known type");
}
private static string GetPrettyHtmlDiff(string text1, string text2)
{
var diffs = Dmp.diff_main(text1, text2);
Dmp.diff_cleanupSemantic(diffs);
return Dmp.diff_prettyHtml(diffs);
}
}
} | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.