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 |
|---|---|---|---|---|---|---|---|---|
09de28373f328a0b44f3e08190cc88b4fc6c2bb0 | Add missing repository | cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium | Src/VisualAssertions/Screenshots/AssertView.cs | Src/VisualAssertions/Screenshots/AssertView.cs | using System;
using Tellurium.MvcPages.BrowserCamera;
using Tellurium.VisualAssertions.Infrastructure.Persistence;
using Tellurium.VisualAssertions.Screenshots.Domain;
using Tellurium.VisualAssertions.TestRunersAdapters;
namespace Tellurium.VisualAssertions.Screenshots
{
public static class AssertView
{
private static VisualAssertionsService visualAssertionsService;
public static void Init(VisualAssertionsConfig config)
{
var testOutputWriter = config.TestOutputWriter ?? Console.WriteLine;
var testRunnerAdapter = TestRunnerAdapterFactory.CreateForCurrentEnvironment(testOutputWriter);
var sessionContext = PersistanceEngine.GetSessionContext();
var projectRepository = new Repository<Project>(sessionContext);
var browserPatterRepository = new Repository<BrowserPattern>(sessionContext);
visualAssertionsService = new VisualAssertionsService(projectRepository,testRunnerAdapter, browserPatterRepository)
{
ProjectName = config.ProjectName,
ScreenshotCategory = config.ScreenshotCategory,
BrowserName = config.BrowserName
};
}
public static void EqualsToPattern(IBrowserCamera browserCamera, string viewName)
{
visualAssertionsService.CheckViewWithPattern(browserCamera, viewName);
}
}
} | using System;
using Tellurium.MvcPages.BrowserCamera;
using Tellurium.VisualAssertions.Infrastructure.Persistence;
using Tellurium.VisualAssertions.Screenshots.Domain;
using Tellurium.VisualAssertions.TestRunersAdapters;
namespace Tellurium.VisualAssertions.Screenshots
{
public static class AssertView
{
private static VisualAssertionsService visualAssertionsService;
public static void Init(VisualAssertionsConfig config)
{
var testOutputWriter = config.TestOutputWriter ?? Console.WriteLine;
var testRunnerAdapter = TestRunnerAdapterFactory.CreateForCurrentEnvironment(testOutputWriter);
var projectRepository = new Repository<Project>(PersistanceEngine.GetSessionContext());
visualAssertionsService = new VisualAssertionsService(projectRepository,testRunnerAdapter)
{
ProjectName = config.ProjectName,
ScreenshotCategory = config.ScreenshotCategory,
BrowserName = config.BrowserName
};
}
public static void EqualsToPattern(IBrowserCamera browserCamera, string viewName)
{
visualAssertionsService.CheckViewWithPattern(browserCamera, viewName);
}
}
} | mit | C# |
4f05b30f77ecd69980f6a3b39cb6e14c2150e452 | test fix for can_handle_inherited_messages | PKI-InVivo/reactive-domain | src/ReactiveDomain.Messaging.Tests/Subscribers/QueuedSubscriber/can_handle_inherited_messages.cs | src/ReactiveDomain.Messaging.Tests/Subscribers/QueuedSubscriber/can_handle_inherited_messages.cs | using ReactiveDomain.Testing;
using Xunit;
namespace ReactiveDomain.Messaging.Tests.Subscribers.QueuedSubscriber
{
// ReSharper disable once InconsistentNaming
public sealed class can_handle_inherited_messages : IClassFixture<QueuedSubscriberFixture>
{
private readonly QueuedSubscriberFixture _fixture;
public can_handle_inherited_messages(QueuedSubscriberFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void queued_subscriber_honors_subscription_inheritance() {
Assert.IsOrBecomesTrue(() => _fixture.Idle);
_fixture.Clear();
var testEvent = new TestEvent(CorrelatedMessage.NewRoot());
_fixture.Publish(testEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1,msg:$"Expected 1 got {_fixture.TestEventCount}");
var parentTestEvent = new ParentTestEvent(testEvent);
_fixture.Publish(parentTestEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 1);
var childTestEvent = new ChildTestEvent(parentTestEvent);
_fixture.Publish(childTestEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 2);
Assert.IsOrBecomesTrue(() => _fixture.ChildEventCount == 1);
_fixture.Publish(new GrandChildTestEvent(childTestEvent));
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 3);
Assert.IsOrBecomesTrue(() => _fixture.ChildEventCount == 2);
Assert.IsOrBecomesTrue(() => _fixture.GrandChildEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.Idle);
_fixture.Clear();
}
}
}
| using ReactiveDomain.Testing;
using Xunit;
namespace ReactiveDomain.Messaging.Tests.Subscribers.QueuedSubscriber
{
// ReSharper disable once InconsistentNaming
public sealed class can_handle_inherited_messages : IClassFixture<QueuedSubscriberFixture>
{
private readonly QueuedSubscriberFixture _fixture;
public can_handle_inherited_messages(QueuedSubscriberFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void queued_subscriber_honors_subscription_inheritance()
{
var testEvent = new TestEvent(CorrelatedMessage.NewRoot());
_fixture.Publish(testEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1,msg:$"Expected 1 got {_fixture.TestEventCount}");
var parentTestEvent = new ParentTestEvent(testEvent);
_fixture.Publish(parentTestEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 1);
var childTestEvent = new ChildTestEvent(parentTestEvent);
_fixture.Publish(childTestEvent);
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 2);
Assert.IsOrBecomesTrue(() => _fixture.ChildEventCount == 1);
_fixture.Publish(new GrandChildTestEvent(childTestEvent));
Assert.IsOrBecomesTrue(() => _fixture.TestEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.ParentEventCount == 3);
Assert.IsOrBecomesTrue(() => _fixture.ChildEventCount == 2);
Assert.IsOrBecomesTrue(() => _fixture.GrandChildEventCount == 1);
Assert.IsOrBecomesTrue(() => _fixture.Idle);
_fixture.Clear();
}
}
}
| mit | C# |
9783248c9b7d1c840559237385f31479e25d5d25 | fix right click | Avanturik/Ubiquitous2,Avanturik/Ubiquitous2 | Ubiquitous2/Interactivity/DragThumbBehavior.cs | Ubiquitous2/Interactivity/DragThumbBehavior.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace UB.Interactivity
{
public class DragThumb :Behavior<UIElement>
{
protected override void OnAttached()
{
AssociatedObject.MouseDown += AssociatedObject_MouseDown;
}
void AssociatedObject_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left)
return;
if (e.ClickCount > 1)
SwitchWindowSize();
else if (e.ClickCount == 1)
StartDrag();
}
protected override void OnDetaching()
{
AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
}
private void SwitchWindowSize()
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
return;
window.WindowState = window.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
}
private void StartDrag()
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
return;
window.DragMove();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace UB.Interactivity
{
public class DragThumb :Behavior<UIElement>
{
protected override void OnAttached()
{
AssociatedObject.MouseDown += AssociatedObject_MouseDown;
}
void AssociatedObject_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount > 1)
SwitchWindowSize();
else if (e.ClickCount == 1)
StartDrag();
}
protected override void OnDetaching()
{
AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
}
private void SwitchWindowSize()
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
return;
window.WindowState = window.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
}
private void StartDrag()
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
return;
window.DragMove();
}
}
}
| mit | C# |
529c9c5b36eeb50477ba6870c71147b9f3bbc34e | fix update sdk version number | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED 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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "3.2.3"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED 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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "3.2.2"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| apache-2.0 | C# |
b67354c93b579a3029270d59605968796173e1f6 | Support for .p7s extension #412 | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Utilities/UniversityFileHelper.cs | R7.University/Utilities/UniversityFileHelper.cs | using System;
using DotNetNuke.Common;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.FileSystem;
using R7.Dnn.Extensions.Text;
namespace R7.University.Utilities
{
public class UniversityFileHelper
{
private static readonly Lazy<UniversityFileHelper> _instance = new Lazy<UniversityFileHelper> ();
public static UniversityFileHelper Instance => _instance.Value;
public IFileInfo GetFileByUrl (string url)
{
if (Globals.GetURLType (url) != TabType.File) {
return null;
}
var fileId = ParseHelper.ParseToNullable<int> (url.ToLowerInvariant ().Replace ("fileid=", ""));
if (fileId == null) {
return null;
}
var file = FileManager.Instance.GetFile (fileId.Value);
return file;
}
public IFileInfo GetSignatureFile (IFileInfo file)
{
var folder = FolderManager.Instance.GetFolder (file.FolderId);
var sigFile = FileManager.Instance.GetFile (folder, file.FileName + ".sig");
if (sigFile == null) {
sigFile = FileManager.Instance.GetFile (folder, file.FileName + ".p7s");
}
return sigFile;
}
}
}
| using System;
using DotNetNuke.Common;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.FileSystem;
using R7.Dnn.Extensions.Text;
namespace R7.University.Utilities
{
public class UniversityFileHelper
{
private static readonly Lazy<UniversityFileHelper> _instance = new Lazy<UniversityFileHelper> ();
public static UniversityFileHelper Instance => _instance.Value;
public IFileInfo GetFileByUrl (string url)
{
if (Globals.GetURLType (url) != TabType.File) {
return null;
}
var fileId = ParseHelper.ParseToNullable<int> (url.ToLowerInvariant ().Replace ("fileid=", ""));
if (fileId == null) {
return null;
}
var file = FileManager.Instance.GetFile (fileId.Value);
return file;
}
public IFileInfo GetSignatureFile (IFileInfo file)
{
var folder = FolderManager.Instance.GetFolder (file.FolderId);
var sigFile = FileManager.Instance.GetFile (folder, file.FileName + ".sig");
return sigFile;
}
}
}
| agpl-3.0 | C# |
273ea7a82b77069f646912ba0d6566b5b16af081 | Normalise line endings | jameswiseman76/JsGoogleCompile,jameswiseman76/JsGoogleCompile,jameswiseman76/JsGoogleCompile | JsGoogleCompile.Tests/JSGoogleCompile.CLI/ArgumentRules/IsValidWarningSuppressionArgumentTests.cs | JsGoogleCompile.Tests/JSGoogleCompile.CLI/ArgumentRules/IsValidWarningSuppressionArgumentTests.cs | namespace JsGoogleCompile.Tests
{
using System;
using System.Linq;
using JsGoogleCompile.CLI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;
[TestClass]
public class IsValidWarningSuppressionArgumentTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_Guards_Null_commandLineArguments()
{
var rule = new IsValidWarningSuppressionArgument(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void IsSatisfiedBy_Guards_Null_commandLineArguments()
{
var rule = new IsValidWarningSuppressionArgument(Mock.Of<ICommandLineArguments>());
rule.IsSatisfiedBy(null);
}
[TestMethod]
public void Single_Valid_Warning_Argument_Is_Recognised()
{
// Arrange
var expectedWarningsSuppressed = new[] { "Error" };
var expectedSwitch = string.Format("/s{0}", string.Join(";", expectedWarningsSuppressed));
var commandLineArguments = new Mock<ICommandLineArguments>();
var rule = new IsValidWarningSuppressionArgument(Mock.Of<ICommandLineArguments>());
commandLineArguments.SetupAllProperties();
// Act
var isValid = rule.IsSatisfiedBy(new[] { expectedSwitch });
// Assert
Assert.IsTrue(isValid);
// todo: sort these out:
// commandLineArguments.VerifySet(m => m.SuppressedWarnings = It.Is<List<string>>(l => l.SequenceEqual(expectedWarningsSuppressed)));
// commandLineArguments.VerifySet(m => m.SuppressedWarnings = It.IsAny<List<string>>());
}
}
}
| namespace JsGoogleCompile.Tests
{
using System;
using System.Linq;
using JsGoogleCompile.CLI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;
[TestClass]
public class IsValidWarningSuppressionArgumentTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_Guards_Null_commandLineArguments()
{
var rule = new IsValidWarningSuppressionArgument(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void IsSatisfiedBy_Guards_Null_commandLineArguments()
{
var rule = new IsValidWarningSuppressionArgument(Mock.Of<ICommandLineArguments>());
rule.IsSatisfiedBy(null);
}
[TestMethod]
public void Single_Valid_Warning_Argument_Is_Recognised()
{
// Arrange
var expectedWarningsSuppressed = new[] { "Error" };
var expectedSwitch = string.Format("/s{0}", string.Join(";", expectedWarningsSuppressed));
var commandLineArguments = new Mock<ICommandLineArguments>();
var rule = new IsValidWarningSuppressionArgument(Mock.Of<ICommandLineArguments>());
commandLineArguments.SetupAllProperties();
// Act
var isValid = rule.IsSatisfiedBy(new[] { expectedSwitch });
// Assert
Assert.IsTrue(isValid);
// todo: sort these out:
// commandLineArguments.VerifySet(m => m.SuppressedWarnings = It.Is<List<string>>(l => l.SequenceEqual(expectedWarningsSuppressed)));
// commandLineArguments.VerifySet(m => m.SuppressedWarnings = It.IsAny<List<string>>());
}
}
}
| mit | C# |
d8c9a9246b6490bb97bbddbbd07b17c37d9d8270 | Comment tidy. | invertedtomato/integer-compression | InvertedTomato.Common/Utilities/GuidUtility.cs | InvertedTomato.Common/Utilities/GuidUtility.cs | using System;
using System.Security.Cryptography;
using System.Text;
namespace InvertedTomato {
public class GuidUtility {
/// <summary>
/// Create a GUID from a given integer. Useful for legacy interfacing.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(int value) {
var bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
/// <summary>
/// Create a GUID from a given long. Useful for legacy interfacing.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(long value) {
var bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
/// <summary>
/// Create a GUID from a given string. Useful for legacy interfacing. (NOTE: Is lossy)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(string value) {
if (null == value) {
throw new ArgumentNullException("value");
}
using (var sha = SHA256Managed.Create()) {
// Hash string
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(value));
// Squash into GUID
var bytes = new byte[16];
Buffer.BlockCopy(hash, 0, bytes, 0, 16);
return new Guid(bytes);
}
}
/// <summary>
/// Convert a short representation of a GUID back into a GUID.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid FromShort(string value) {
if (null == value) {
throw new ArgumentOutOfRangeException("value");
}
// Un-fix unfriendly base64 characters
var str = value.Replace('-', '+').Replace('_', '=').Replace('~', '/');
// Convert to bytes
var bytes = Convert.FromBase64String(str + "==");
// Convert to GUID
return new Guid(bytes);
}
}
} | using System;
using System.Security.Cryptography;
using System.Text;
namespace InvertedTomato {
public class GuidUtility {
/// <summary>
/// Create a GUID from a given integer. Useful for legacy interfacing.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(int value) {
var bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
/// <summary>
/// Create a GUID from a given long. Useful for legacy interfacing.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(long value) {
var bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
/// <summary>
/// Create a GUID from a given string. Useful for legacy interfacing. (NOTE: Is lossy)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Guid CreateFrom(string value) {
if (null == value) {
throw new ArgumentNullException("value");
}
using (var sha = SHA256Managed.Create()) {
// Hash string
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(value));
// Squash into GUID
var bytes = new byte[16];
Buffer.BlockCopy(hash, 0, bytes, 0, 16);
return new Guid(bytes);
}
}
public static Guid FromShort(string value) {
if (null == value) {
throw new ArgumentOutOfRangeException("value");
}
// Un-fix unfriendly base64 characters
var str = value.Replace('-', '+').Replace('_', '=').Replace('~', '/');
// Convert to bytes
var bytes = Convert.FromBase64String(str + "==");
// Convert to GUID
return new Guid(bytes);
}
}
} | mit | C# |
ddc031768c16ed6d9f33ba3190df003c6f37dc82 | Add to | stripe/stripe-dotnet | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetailsAcssDebit.cs | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetailsAcssDebit.cs | namespace Stripe
{
using Newtonsoft.Json;
public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit>
{
/// <summary>
/// Name of the bank associated with the bank account.
/// </summary>
[JsonProperty("bank_name")]
public string BankName { get; set; }
/// <summary>
/// Uniquely identifies this particular bank account. You can use this attribute to check
/// whether two bank accounts are the same.
/// </summary>
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
/// <summary>
/// Institution number of the bank account.
/// </summary>
[JsonProperty("institution_number")]
public string InstitutionNumber { get; set; }
/// <summary>
/// Last four digits of the bank account number.
/// </summary>
[JsonProperty("last4")]
public string Last4 { get; set; }
/// <summary>
/// ID of the mandate used to make this payment.
/// </summary>
[JsonProperty("mandate")]
public string Mandate { get; set; }
/// <summary>
/// Transit number of the bank account.
/// </summary>
[JsonProperty("transit_number")]
public string TransitNumber { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class ChargePaymentMethodDetailsAcssDebit : StripeEntity<ChargePaymentMethodDetailsAcssDebit>
{
/// <summary>
/// Uniquely identifies this particular bank account. You can use this attribute to check
/// whether two bank accounts are the same.
/// </summary>
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
/// <summary>
/// Institution number of the bank account.
/// </summary>
[JsonProperty("institution_number")]
public string InstitutionNumber { get; set; }
/// <summary>
/// Last four digits of the bank account number.
/// </summary>
[JsonProperty("last4")]
public string Last4 { get; set; }
/// <summary>
/// ID of the mandate used to make this payment.
/// </summary>
[JsonProperty("mandate")]
public string Mandate { get; set; }
/// <summary>
/// Transit number of the bank account.
/// </summary>
[JsonProperty("transit_number")]
public string TransitNumber { get; set; }
}
}
| apache-2.0 | C# |
92f0eb76611bb79b6976ac6d5fba3d9016cfa206 | Update XProperty.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Data/XProperty.cs | src/Core2D/Data/XProperty.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 Core2D.Attributes;
namespace Core2D.Data
{
/// <summary>
/// Data property.
/// </summary>
public class XProperty : ObservableObject
{
private string _name;
private string _value;
private XContext _owner;
/// <summary>
/// Gets or sets property name.
/// </summary>
public string Name
{
get => _name;
set => Update(ref _name, value);
}
/// <summary>
/// Gets or sets property value.
/// </summary>
[Content]
public string Value
{
get => _value;
set => Update(ref _value, value);
}
/// <summary>
/// Gets or sets property owner.
/// </summary>
public XContext Owner
{
get => _owner;
set => Update(ref _owner, value);
}
/// <summary>
/// Creates a new <see cref="XProperty"/> instance.
/// </summary>
/// <param name="owner">The property owner.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <returns>The new instance of the <see cref="XProperty"/> class.</returns>
public static XProperty Create(XContext owner, string name, string value)
{
return new XProperty()
{
Name = name,
Value = value,
Owner = owner
};
}
/// <inheritdoc/>
public override string ToString() => _value.ToString();
}
}
| // 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 Core2D.Attributes;
namespace Core2D.Data
{
/// <summary>
/// Data property.
/// </summary>
public class XProperty : ObservableObject
{
private string _name;
private string _value;
private XContext _owner;
/// <summary>
/// Gets or sets property name.
/// </summary>
public string Name
{
get { return _name; }
set { Update(ref _name, value); }
}
/// <summary>
/// Gets or sets property value.
/// </summary>
[Content]
public string Value
{
get { return _value; }
set { Update(ref _value, value); }
}
/// <summary>
/// Gets or sets property owner.
/// </summary>
public XContext Owner
{
get { return _owner; }
set { Update(ref _owner, value); }
}
/// <summary>
/// Creates a new <see cref="XProperty"/> instance.
/// </summary>
/// <param name="owner">The property owner.</param>
/// <param name="name">The property name.</param>
/// <param name="value">The property value.</param>
/// <returns>The new instance of the <see cref="XProperty"/> class.</returns>
public static XProperty Create(XContext owner, string name, string value)
{
return new XProperty()
{
Name = name,
Value = value,
Owner = owner
};
}
/// <inheritdoc/>
public override string ToString()
{
return _value.ToString();
}
}
}
| mit | C# |
997f9a676c0cb2f2829dbe86804a257f104a4beb | add default | wolfspelz/KataFromRomanNumerals | FromRomanNumerals/Program.cs | FromRomanNumerals/Program.cs | using System;
namespace FromRomanNumerals
{
class Program
{
static void Main()
{
Console.WriteLine("Please enter a roman number (<quit> to exit) [MMXVII]:");
string line;
while ((line = Console.ReadLine()) != "quit")
{
try
{
var roman = line;
if (roman == "")
{
roman = "MMXVII";
}
var latin = RomanNumber.ToDecimal(roman?.ToUpper());
Console.WriteLine($"{roman} is {latin}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
| using System;
namespace FromRomanNumerals
{
class Program
{
static void Main()
{
Console.WriteLine("Please enter a roman number (ENTER to exit):");
string line;
while ((line = Console.ReadLine()) != "")
{
try
{
var roman = line;
var latin = RomanNumber.ToDecimal(roman?.ToUpper());
Console.WriteLine($"{roman} is {latin}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
| bsd-3-clause | C# |
24070f6ac8b815417324e563345bc9f852ad3be3 | Fix whitespace formatting | shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,stephentoub/roslyn,weltkante/roslyn,brettfo/roslyn,sharwell/roslyn,stephentoub/roslyn,tannergooding/roslyn,aelij/roslyn,genlu/roslyn,mavasani/roslyn,aelij/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,eriawan/roslyn,genlu/roslyn,davkean/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,AmadeusW/roslyn,tannergooding/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,gafter/roslyn,wvdd007/roslyn,KevinRansom/roslyn,diryboy/roslyn,sharwell/roslyn,physhi/roslyn,tmat/roslyn,aelij/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,heejaechang/roslyn,eriawan/roslyn,tannergooding/roslyn,davkean/roslyn,tmat/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,eriawan/roslyn,physhi/roslyn,heejaechang/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,gafter/roslyn,brettfo/roslyn,KevinRansom/roslyn,tmat/roslyn,dotnet/roslyn,dotnet/roslyn,mavasani/roslyn,physhi/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,genlu/roslyn,sharwell/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,brettfo/roslyn | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
bool IsSupported(Workspace workspace);
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public virtual bool IsSupported(Workspace workspace) => false;
protected virtual string GetCacheDirectory()
{
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
return Path.Combine(appDataFolder, "Microsoft", "VisualStudio", "Roslyn", "Cache");
}
public string? TryGetStorageLocation(Solution solution)
{
if (!IsSupported(solution.Workspace))
return null;
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var cacheDirectory = GetCacheDirectory();
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(cacheDirectory, kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
bool IsSupported(Workspace workspace);
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public virtual bool IsSupported(Workspace workspace) => false;
protected virtual string GetCacheDirectory()
{
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
return Path.Combine(appDataFolder, "Microsoft", "VisualStudio", "Roslyn", "Cache");
}
public string? TryGetStorageLocation(Solution solution)
{
if (!IsSupported(solution.Workspace))
return null;
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var cacheDirectory = GetCacheDirectory();
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(cacheDirectory, kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| mit | C# |
fcffa8721297f9522227a95f2a0cc787b005635c | Fix bucketSettingsTest compilation issue | aliyun/aliyun-oss-csharp-sdk | test/TestCase/BucketTestCase/BucketSettingsTest.cs | test/TestCase/BucketTestCase/BucketSettingsTest.cs | using Aliyun.OSS;
using Aliyun.OSS.Test.Util;
using NUnit.Framework;
namespace Aliyun.OSS.Test.TestClass.BucketTestClass
{
[TestFixture]
public partial class BucketSettingsTest
{
private static IOss _ossClient;
private static string _className;
private static string _bucketName;
#if NETCOREAPP2_0
[OneTimeSetUp]
#else
[TestFixtureSetUp]
#endif
public static void ClassInitialize()
{
//get a OSS client object
_ossClient = OssClientFactory.CreateOssClient();
//prefix of bucket name used in current test class
_className = TestContext.CurrentContext.Test.FullName;
_className = _className.Substring(_className.LastIndexOf('.') + 1).ToLowerInvariant();
//create the bucket
_bucketName = OssTestUtils.GetBucketName(_className);
_ossClient.CreateBucket(_bucketName);
}
#if NETCOREAPP2_0
[OneTimeTearDown]
#else
[TestFixtureTearDown]
#endif
public static void ClassCleanup()
{
OssTestUtils.CleanBucket(_ossClient, _bucketName);
}
}
}
| using Aliyun.OSS;
using Aliyun.OSS.Test.Util;
using NUnit.Framework;
namespace Aliyun.OSS.Test.TestClass.BucketTestClass
{
[TestFixture]
public partial class BucketSettingsTest
{
private static IOss _ossClient;
private static string _className;
private static string _bucketName;
[OneTimeSetUp]
public static void ClassInitialize()
{
//get a OSS client object
_ossClient = OssClientFactory.CreateOssClient();
//prefix of bucket name used in current test class
_className = TestContext.CurrentContext.Test.FullName;
_className = _className.Substring(_className.LastIndexOf('.') + 1).ToLowerInvariant();
//create the bucket
_bucketName = OssTestUtils.GetBucketName(_className);
_ossClient.CreateBucket(_bucketName);
}
[OneTimeTearDown]
public static void ClassCleanup()
{
OssTestUtils.CleanBucket(_ossClient, _bucketName);
}
}
}
| mit | C# |
e22d3a7045037ad6dab687ab19c0deaf408485f8 | Create directory if needed | ysanghi/Vipr,tonycrider/Vipr,tonycrider/Vipr,MSOpenTech/Vipr,Microsoft/Vipr,v-am/Vipr | src/Core/Vipr/FileWriter.cs | src/Core/Vipr/FileWriter.cs | using System;
using System.Collections.Generic;
using System.IO;
using Vipr.Core;
namespace Vipr
{
internal static class FileWriter
{
public static void Write(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null)
{
if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath))
Directory.CreateDirectory(outputDirectoryPath);
foreach (var file in textFilesToWrite)
{
var filePath = file.RelativePath;
if (!string.IsNullOrWhiteSpace(outputDirectoryPath))
filePath = Path.Combine(outputDirectoryPath, filePath);
if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) &&
!Path.IsPathRooted(filePath))
filePath = Path.Combine(Environment.CurrentDirectory, filePath);
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllText(filePath, file.Contents);
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using Vipr.Core;
namespace Vipr
{
internal static class FileWriter
{
public static void Write(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null)
{
if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath))
Directory.CreateDirectory(outputDirectoryPath);
foreach (var file in textFilesToWrite)
{
var filePath = file.RelativePath;
if (!string.IsNullOrWhiteSpace(outputDirectoryPath))
filePath = Path.Combine(outputDirectoryPath, filePath);
if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) &&
!Path.IsPathRooted(filePath))
filePath = Path.Combine(Environment.CurrentDirectory, filePath);
File.WriteAllText(filePath, file.Contents);
}
}
}
} | mit | C# |
d38db33c6121c3f9beddf7809486354934ad4690 | fix projects view not showing online collaborators | ribombee/mothman-dad-city,ribombee/mothman-dad-city,ribombee/mothman-dad-city,ribombee/mothman-dad-city | VLN2-H27/VLN2-H27/Views/Editor/projects.cshtml | VLN2-H27/VLN2-H27/Views/Editor/projects.cshtml | @{
ViewBag.Title = "projects";
var projects = ViewBag.projects;
var projectIdsJson = ViewBag.projectIdsJson;
}
<!-- Link project page CSS to HTML-->
<link rel="stylesheet" href="../../Content/ProjectStyle.css">
<div id="projects-body">
@Html.Partial("NewProjectPartial")
<hr id="projects-body-hr" />
<div class="flex-grid">
@foreach(VLN2_H27.Models.Project p in ViewBag.projects) {
<a href="@Url.Action("editor", "Editor", new { @Id = p.Id })" class="project-title" id=("project-@p.Id")>
<div class="col" id="col">
<div class="project-info">
<h3 style="text-align: center">@p.ProjectName</h3>
<hr />
<p class="project-info-line"><span class="project-info-title">Created:</span>@p.DateAdded.Day/@p.DateAdded.Month/@p.DateAdded.Year</p>
<p class="project-info-line"><span class="project-info-title">Collaborators:</span>@p.NrOfUsers</p>
<p id="project-@p.Id" class="project-info-line" data-editing="0"><span class="project-info-title">Online Now:</span><div id="users-@p.Id">0</div></p>
</div>
</div>
</a>
}
@for(int i = 0; i < 10; i++) {
<div class="empty-col"></div>
}
</div>
</div>
@section scripts {
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!-- Declaring global variables from viewbag-->
<script>
var projectIds = @(projectIdsJson);
</script>
<!-- JS CODE GOES HERE -->
<script src="../../Scripts/ProjectsScripts.js" type="text/javascript"></script>
}
| @{
ViewBag.Title = "projects";
var projects = ViewBag.projects;
var projectIdsJson = ViewBag.projectIdsJson;
}
<!-- Link project page CSS to HTML-->
<link rel="stylesheet" href="../../Content/ProjectStyle.css">
<div id="projects-body">
@Html.Partial("NewProjectPartial")
<hr id="projects-body-hr" />
<div class="flex-grid">
@foreach(VLN2_H27.Models.Project p in ViewBag.projects) {
<a href="@Url.Action("editor", "Editor", new { @Id = p.Id })" class="project-title" id=("project-@p.Id")>
<div class="col" id="col">
<div class="project-info">
<h3 style="text-align: center">@p.ProjectName</h3>
<hr />
<p class="project-info-line"><span class="project-info-title">Created:</span>@p.DateAdded.Day/@p.DateAdded.Month/@p.DateAdded.Year</p>
<p class="project-info-line"><span class="project-info-title">Collaborators:</span>@p.NrOfUsers</p>
<p class="project-info-line"><span id=("project-@p.Id") class="project-info-title">Online Now:</span>0</p>
</div>
</div>
</a>
}
@for(int i = 0; i < 10; i++) {
<div class="empty-col"></div>
}
</div>
</div>
@section scripts {
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!-- Declaring global variables from viewbag-->
<script>
var projectIds = @(projectIdsJson);
</script>
<!-- JS CODE GOES HERE -->
<script src="../../Scripts/ProjectsScripts.js" type="text/javascript"></script>
}
| mit | C# |
e03a278a080eee17658f04b8f11e0202f2967487 | Hide async warning | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Services/ITestItemPriceService.cs | Anlab.Mvc/Services/ITestItemPriceService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Anlab.Core.Data;
using Anlab.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace AnlabMvc.Services
{
public interface ITestItemPriceService
{
Task<IList<TestItemPrices>> GetPrices();
Task<TestItemPrices> GetPrice(string code);
}
public class FakeTestItemPriceService : ITestItemPriceService
{
private readonly ApplicationDbContext _context;
public FakeTestItemPriceService(ApplicationDbContext context)
{
_context = context;
}
public async Task<IList<TestItemPrices>> GetPrices()
{
var temp = _context.TestItems.AsNoTracking().ToList();
var testItems = new List<TestItemPrices>();
var counter = 1;
foreach (var testItem in temp.OrderBy(a => a.Id))
{
if(testItems.Any(a => a.Code == testItem.Code))
continue;
counter++;
var tip = new TestItemPrices();
tip.Code = testItem.Code;
tip.Cost = counter;
tip.SetupCost = counter % 2 == 0 ? 25 : 30;
tip.Multiplier = 1;
tip.Name = testItem.Analysis;
testItems.Add(tip);
}
return await Task.FromResult(testItems);
}
public async Task<TestItemPrices> GetPrice(string code)
{
var temp = await _context.TestItems.SingleOrDefaultAsync(a => a.Code == code);
if (temp == null)
{
return null;
}
var tip = new TestItemPrices
{
Code = temp.Code,
Cost = temp.Id + 1,
SetupCost = (temp.Id + 1)%2 == 0 ? 25 :30,
Multiplier = 1,
Name = temp.Analysis
};
return tip;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Anlab.Core.Data;
using Anlab.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace AnlabMvc.Services
{
public interface ITestItemPriceService
{
Task<IList<TestItemPrices>> GetPrices();
Task<TestItemPrices> GetPrice(string code);
}
public class FakeTestItemPriceService : ITestItemPriceService
{
private readonly ApplicationDbContext _context;
public FakeTestItemPriceService(ApplicationDbContext context)
{
_context = context;
}
public async Task<IList<TestItemPrices>> GetPrices()
{
var temp = _context.TestItems.AsNoTracking().ToList();
var testItems = new List<TestItemPrices>();
var counter = 1;
foreach (var testItem in temp.OrderBy(a => a.Id))
{
if(testItems.Any(a => a.Code == testItem.Code))
continue;
counter++;
var tip = new TestItemPrices();
tip.Code = testItem.Code;
tip.Cost = counter;
tip.SetupCost = counter % 2 == 0 ? 25 : 30;
tip.Multiplier = 1;
tip.Name = testItem.Analysis;
testItems.Add(tip);
}
return testItems;
}
public async Task<TestItemPrices> GetPrice(string code)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
69f0ed0aa6986b529fb37c39d3038be679ff2f00 | fix filename | darvell/Coremero | Coremero/Coremero.Plugin.Weather/WeatherPlugin.cs | Coremero/Coremero.Plugin.Weather/WeatherPlugin.cs | using System;
using System.IO;
using System.Threading.Tasks;
using Coremero.Utilities;
using Coremero.Commands;
using Coremero.Attachments;
using Coremero.Context;
using Coremero.Messages;
using Coremero.Storage;
namespace Coremero.Plugin.Weather
{
public class WeatherPlugin : IPlugin
{
private string DARK_SKIES_APIKEY = "";
public WeatherPlugin(ICredentialStorage credentialStorage)
{
DARK_SKIES_APIKEY = credentialStorage.GetKey("darkskies", "");
}
[Command("weather")]
public async Task<IMessage> GetWeather(IInvocationContext context, string message)
{
Weather weather = new Weather(DARK_SKIES_APIKEY);
WeatherRendererInfo forecast = await weather.GetForecastAsync(message.TrimCommand());
return Message.Create("", new StreamAttachment(weather.RenderWeatherImage(forecast), "weather.gif"));
}
}
}
| using System;
using System.IO;
using System.Threading.Tasks;
using Coremero.Utilities;
using Coremero.Commands;
using Coremero.Attachments;
using Coremero.Context;
using Coremero.Messages;
using Coremero.Storage;
namespace Coremero.Plugin.Weather
{
public class WeatherPlugin : IPlugin
{
private string DARK_SKIES_APIKEY = "";
public WeatherPlugin(ICredentialStorage credentialStorage)
{
DARK_SKIES_APIKEY = credentialStorage.GetKey("darkskies", "");
}
[Command("weather")]
public async Task<IMessage> GetWeather(IInvocationContext context, string message)
{
Weather weather = new Weather(DARK_SKIES_APIKEY);
WeatherRendererInfo forecast = await weather.GetForecastAsync(message.TrimCommand());
return Message.Create("", new StreamAttachment(weather.RenderWeatherImage(forecast), "weather.png"));
}
}
}
| mit | C# |
33edfb1f1a6ef754a1b9a0fb6edabc06a6a8fd5c | add test for no-arg rounding | mikebridge/Liquid.NET,mikebridge/Liquid.NET,mikebridge/Liquid.NET | Liquid.NET.Tests/Filters/Math/RoundFilterTests.cs | Liquid.NET.Tests/Filters/Math/RoundFilterTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Liquid.NET.Tests.Filters.Math
{
[TestFixture]
public class RoundFilterTests
{
[Test]
[TestCase("123.4", 123)]
[TestCase("123.5", 124)]
[TestCase("124.4", 124)]
[TestCase("124.5", 125)]
[TestCase("-1.3", -1)]
[TestCase("-1.5", -2)]
public void It_Should_Round_To_Nearest_Whole_Number_Away_From_Zero(String input, int expected)
{
// Act
//var result = LiquidHtmlFilters.ToInt(input);
var result = RenderingHelper.RenderTemplate("Result : {{ "+input+" | round }}");
// Assert
Assert.That(result, Is.EqualTo("Result : " + expected));
}
[Test]
[TestCase("123.33333333333", 2, "123.33")]
[TestCase("123.5", 0, "124")]
[TestCase("124.45", 1, "124.5")]
[TestCase("124.499", 1, "124.5")]
[TestCase("-1.3", -1, "-1")]
[TestCase("-1.5", 0, "-2")]
[TestCase("1", null, "1")]
public void It_Should_Round_To_Nearest_Decimal_Number(String input, int digits, String expected)
{
// Act
//var result = LiquidHtmlFilters.ToInt(input);
var result = RenderingHelper.RenderTemplate("Result : {{ " + input + " | round : "+digits+" }}");
// Assert
Assert.That(result, Is.EqualTo("Result : " +expected));
}
[Test]
public void It_Should_Round_To_Int_When_No_Arg()
{
// Act
//var result = LiquidHtmlFilters.ToInt(input);
var result = RenderingHelper.RenderTemplate("Result : {{ 12.5 | round }}");
// Assert
Assert.That(result, Is.EqualTo("Result : 13"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Liquid.NET.Tests.Filters.Math
{
[TestFixture]
public class RoundFilterTests
{
[Test]
[TestCase("123.4", 123)]
[TestCase("123.5", 124)]
[TestCase("124.4", 124)]
[TestCase("124.5", 125)]
[TestCase("-1.3", -1)]
[TestCase("-1.5", -2)]
public void It_Should_Round_To_Nearest_Whole_Number_Away_From_Zero(String input, int expected)
{
// Act
//var result = LiquidHtmlFilters.ToInt(input);
var result = RenderingHelper.RenderTemplate("Result : {{ "+input+" | round }}");
// Assert
Assert.That(result, Is.EqualTo("Result : " + expected));
}
[Test]
[TestCase("123.33333333333", 2, "123.33")]
[TestCase("123.5", 0, "124")]
[TestCase("124.45", 1, "124.5")]
[TestCase("124.499", 1, "124.5")]
[TestCase("-1.3", -1, "-1")]
[TestCase("-1.5", 0, "-2")]
[TestCase("1", null, "1")]
public void It_Should_Round_To_Nearest_Decimal_Number(String input, int digits, String expected)
{
// Act
//var result = LiquidHtmlFilters.ToInt(input);
var result = RenderingHelper.RenderTemplate("Result : {{ " + input + " | round : "+digits+" }}");
// Assert
Assert.That(result, Is.EqualTo("Result : " +expected));
}
}
}
| mit | C# |
fffefb3137b35e5c49d497cb691cd6c2fe961f1b | Fix get messages url. Fix send message syntax error. | Mikuz/Battlezeppelins,Mikuz/Battlezeppelins | Battlezeppelins/Views/Shared/ChatBox.cshtml | Battlezeppelins/Views/Shared/ChatBox.cshtml | <div style="height:436px; overflow: hidden;padding-left: 15px;padding-right: 15px;">
<div class="row well" style="padding:0px;margin-bottom: 3px;">
<ul class="list-inline" style="margin:2px;">
<li>
<small class="text-primary">{{msg.time | chatTime}}</small>
</li>
<li class="text-primary">
<{{msg.name}}>
</li>
<li>
{{msg.message}}
</li>
</ul>
</div>
</div>
<div class="row well" style="margin-top:10px;">
<div class="col-xs-2">
<button class="btn btn-info" onclick="sendMessages()"><b>Send</b></button>
<button class="btn btn-info" onclick="askMessages()"><b>Ask messages</b></button>
</div>
<div class="form-group col-xs-10">
<input class="form-control" id="message" type="text" maxlength="240">
</div>
</div>
<script>
var lastTime = $.now();
function askMessages() {
$.ajax({
type: "POST",
url: "Chat/GetMessages",
data: { fromTime: lastTime },
success: function (data) {
lastTime = $.now();
alert(data);
}
});
};
function sendMessages() {
$.ajax({
type: "POST",
url: "Chat/SendMessage",
data: { message: $("#message").val()},
success: function (data) {
$("#message").val = "";
alert(data);
}
});
};
</script> | <div style="height:436px; overflow: hidden;padding-left: 15px;padding-right: 15px;">
<div class="row well" style="padding:0px;margin-bottom: 3px;">
<ul class="list-inline" style="margin:2px;">
<li>
<small class="text-primary">{{msg.time | chatTime}}</small>
</li>
<li class="text-primary">
<{{msg.name}}>
</li>
<li>
{{msg.message}}
</li>
</ul>
</div>
</div>
<div class="row well" style="margin-top:10px;">
<div class="col-xs-2">
<button class="btn btn-info" onclick="sendMessages()"><b>Send</b></button>
<button class="btn btn-info" onclick="askMessages()"><b>Ask messages</b></button>
</div>
<div class="form-group col-xs-10">
<input class="form-control" id="message" type="text" maxlength="240">
</div>
</div>
<script>
var lastTime;
function askMessages() {
$.ajax({
type: "POST",
url: "Chat/GetMessage",
data: { fromTime: lastTime },
success: function (data) {
lastTime = $.now();
alert(data);
}
});
};
function sendMessages() {
$.ajax({
type: "POST",
url: "Chat/SendMessage",
data: { message: $("#message").val()},
success: function (data) {
$("#message").val() = "";
alert(data);
}
});
};
</script> | apache-2.0 | C# |
ce17e9b02b5f4d97a33dbd214893b1d835dcd03e | update GameManager CRLF | GROWrepo/Santa_Inc | Assets/script/monoBehavior/GameManager.cs | Assets/script/monoBehavior/GameManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
STATUS_GAME SG;
dialog current;
// Use this for initialization
void Start () {
SG = STATUS_GAME.MENU;
current = null;
}
// Update is called once per frame
void Update () {
}
private void OnGUI()
{
if(this.SG == STATUS_GAME.DIALOGING)
{
if (this.current == null)
this.SG = STATUS_GAME.PAUSE;
else
{
}
}
}
private void setCurrent(dialog dialogs)
{
this.current = dialogs;
}
public STATUS_GAME getSG()
{
return this.SG;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
STATUS_GAME SG;
dialog current;
// Use this for initialization
void Start () {
SG = STATUS_GAME.MENU;
current = null;
}
// Update is called once per frame
void Update () {
}
private void OnGUI()
{
if(this.SG == STATUS_GAME.DIALOGING)
{
if (this.current == null)
this.SG = STATUS_GAME.PAUSE;
else
{
}
}
}
private void setCurrent(dialog dialogs)
{
this.current = dialogs;
}
public STATUS_GAME getSG()
{
return this.SG;
}
}
| mit | C# |
094d8f30ccfe9aec0148d302cec55e6a2f6636a5 | Update TitleCapitalization.cs | michaeljwebb/Algorithm-Practice | Other/TitleCapitalization.cs | Other/TitleCapitalization.cs | //Capitalize(first letter) the first word in a title.
//Capitalize(first letter) the last word in a title.
//Lowercase the following words unless they are first or last word of the title: "a", "the", "to", "at", "in", "with", "and", "but", "or"
//Capitalize(first letter) any words not in the list above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TitleCapitalization
{
private static List<string> lowerList = new List<string>
{
"a","the","to","at","in","with","and","but","or"
};
public static void Main(){
string testTitle = "These are the days of our lives";
TitleCase(testTitle);
Console.WriteLine(TitleCase(testTitle));
}
public static string TitleCase(string title){
//Lowercase title
title = title.ToLower();
//Split title by spaces
var words = title.Split(' ');
//Loop through words
for(int i = 0; i < words.Length; i++)
{
//If words are first or last word or are not in lowerList then capitalize word.
if(i == 0 || i == words.Length - 1 || !lowerList.Contains(words[i])){
words[i] = Capitalize(words[i]);
}
}
//Combine words
return string.Join(" ", words);
}
public static string Capitalize(string word)
{
word = char.ToUpper(word[0]) + word.Substring(1);
return word;
}
}
| //Capitalize(first letter) the first word in a title.
//Capitalize(first letter) the last word in a title.
//Lowercase the following words unless they are first or last word of the title: "a", "the", "to", "at", "in", "with", "and", "but", "or"
//Capitalize(first letter) any words not in the list above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TitleCapitalization
{
private List<string> lowerList = new List<string>
{
"a","the","to","at","in","with","and","but","or"
};
public void Main(){
string testTitle = "These are the days of our lives";
TitleCase(testTitle);
Console.WriteLine(TitleCase(testTitle));
}
public string TitleCase(string title){
//Lowercase title
title = title.ToLower();
//Split title by spaces
var words = title.Split(' ');
//Loop through words
for(int i = 0; i < words.Length; i++)
{
//If words are first or last word or are not in lowerList then capitalize word.
if(i == 0 || i == words.Length - 1 || !lowerList.Contains(words[i])){
words[i] = Capitalize(words[i]);
}
}
//Combine words
return string.Join(" ", words);
}
public string Capitalize(string word)
{
word = char.ToUpper(word[0]) + word.Substring(1);
return word;
}
}
| mit | C# |
af2316e48c3b0f066374886a301ee0026c22f5f2 | Use Enum.Parse overload available in PCL | cureos/Evil-DICOM | EvilDICOM.Core/EvilDICOM.Core/Helpers/EnumHelper.cs | EvilDICOM.Core/EvilDICOM.Core/Helpers/EnumHelper.cs | using System;
namespace EvilDICOM.Core.Helpers
{
public class EnumHelper
{
public static T StringToEnum<T>(string name)
{
return (T) Enum.Parse(typeof (T), name, false);
}
}
} | using System;
namespace EvilDICOM.Core.Helpers
{
public class EnumHelper
{
public static T StringToEnum<T>(string name)
{
return (T) Enum.Parse(typeof (T), name);
}
}
} | mit | C# |
d2c77c07f5bbe98326aea552ce09fa217318c911 | add producer. | ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP | src/Cap.Consistency/Producer/IProducerClient.cs | src/Cap.Consistency/Producer/IProducerClient.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Cap.Consistency.Producer
{
public interface IProducerClient
{
Task SendAsync(string topic, string content);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Cap.Consistency.Producer
{
public interface IProducerClient
{
}
}
| mit | C# |
7a838a64be05d2cd87a0dc437c8a342c3fcabcdb | Include compilation messages to exception message | toddams/RazorLight,toddams/RazorLight | src/RazorLight/Compilation/CompilationResult.cs | src/RazorLight/Compilation/CompilationResult.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace RazorLight.Compilation
{
/// <summary>
/// Represents the result of compilation.
/// </summary>
public struct CompilationResult
{
/// <summary>
/// Initializes a new instance of <see cref="CompilationResult"/> for a successful compilation.
/// </summary>
/// <param name="type">The compiled type.</param>
public CompilationResult(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
CompiledType = type;
CompilationFailures = null;
}
/// <summary>
/// Initializes a new instance of <see cref="CompilationResult"/> for a failed compilation.
/// </summary>
/// <param name="compilationFailures"><see cref="CompilationFailure"/>s produced from parsing or
/// compiling the Razor file.</param>
public CompilationResult(IEnumerable<string> compilationFailures)
{
if (compilationFailures == null)
{
throw new ArgumentNullException(nameof(compilationFailures));
}
CompiledType = null;
CompilationFailures = compilationFailures;
}
/// <summary>
/// Gets the type produced as a result of compilation.
/// </summary>
/// <remarks>This property is <c>null</c> when compilation failed.</remarks>
public Type CompiledType { get; }
/// <summary>
/// Gets the <see cref="CompilationFailure"/>s produced from parsing or compiling the Razor file.
/// </summary>
/// <remarks>This property is <c>null</c> when compilation succeeded. An empty sequence
/// indicates a failed compilation.</remarks>
public IEnumerable<string> CompilationFailures { get; }
/// <summary>
/// Gets the <see cref="CompilationResult"/>.
/// </summary>
/// <returns>The current <see cref="CompilationResult"/> instance.</returns>
/// <exception cref="TemplateCompilationException">Thrown if compilation failed.</exception>
public void EnsureSuccessful()
{
if (CompilationFailures != null)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("Failed to compile generated Razor template:");
foreach(var error in CompilationFailures)
{
builder.AppendLine($"- {error}");
}
builder.AppendLine("\nSee CompilationErrors for detailed information");
throw new TemplateCompilationException(builder.ToString(), CompilationFailures);
}
}
}
}
| using System;
using System.Collections.Generic;
namespace RazorLight.Compilation
{
/// <summary>
/// Represents the result of compilation.
/// </summary>
public struct CompilationResult
{
/// <summary>
/// Initializes a new instance of <see cref="CompilationResult"/> for a successful compilation.
/// </summary>
/// <param name="type">The compiled type.</param>
public CompilationResult(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
CompiledType = type;
CompilationFailures = null;
}
/// <summary>
/// Initializes a new instance of <see cref="CompilationResult"/> for a failed compilation.
/// </summary>
/// <param name="compilationFailures"><see cref="CompilationFailure"/>s produced from parsing or
/// compiling the Razor file.</param>
public CompilationResult(IEnumerable<string> compilationFailures)
{
if (compilationFailures == null)
{
throw new ArgumentNullException(nameof(compilationFailures));
}
CompiledType = null;
CompilationFailures = compilationFailures;
}
/// <summary>
/// Gets the type produced as a result of compilation.
/// </summary>
/// <remarks>This property is <c>null</c> when compilation failed.</remarks>
public Type CompiledType { get; }
/// <summary>
/// Gets the <see cref="CompilationFailure"/>s produced from parsing or compiling the Razor file.
/// </summary>
/// <remarks>This property is <c>null</c> when compilation succeeded. An empty sequence
/// indicates a failed compilation.</remarks>
public IEnumerable<string> CompilationFailures { get; }
/// <summary>
/// Gets the <see cref="CompilationResult"/>.
/// </summary>
/// <returns>The current <see cref="CompilationResult"/> instance.</returns>
/// <exception cref="TemplateCompilationException">Thrown if compilation failed.</exception>
public void EnsureSuccessful()
{
if (CompilationFailures != null)
{
throw new TemplateCompilationException("Failed to compile generated razor view. See CompilationErrors for detailed information", CompilationFailures);
}
}
}
}
| apache-2.0 | C# |
b3cd9de55367da7da037e779cb4c195d71613547 | use development connection | corker/estuite | Estuite/Estuite.Example/ProgramConfiguration.cs | Estuite/Estuite.Example/ProgramConfiguration.cs | using Estuite.AzureEventStore;
using Estuite.Example.Configuration;
namespace Estuite.Example
{
public class ProgramConfiguration : IEventStoreConfiguration, ICloudStorageAccountConfiguration
{
public string ConnectionString => "UseDevelopmentStorage=true";
public string StreamTableName => "esStreams";
public string EventTableName => "esEvents";
}
} | using Estuite.AzureEventStore;
using Estuite.Example.Configuration;
namespace Estuite.Example
{
public class ProgramConfiguration : IEventStoreConfiguration, ICloudStorageAccountConfiguration
{
//public string ConnectionString => "UseDevelopmentStorage=true";
public string ConnectionString => "DefaultEndpointsProtocol=https;AccountName=estuite;AccountKey=WqombaM2u/Tx41EJnT1LDuholL7Y2JbB2DoYzrdlUVYJSaX1ilLt+9r2I06YOtw+GdLqNuBsNdB+873kdKFItg==;TableEndpoint=https://estuite.table.core.windows.net/;";
public string StreamTableName => "esStreams";
public string EventTableName => "esEvents";
}
} | mit | C# |
a420af67b72e470b9481d6b2eca29f7c7c2254d2 | Fix French translation | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/MvcSample.Web/Views/Shared/fr/_Layout.cshtml | samples/MvcSample.Web/Views/Shared/fr/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Ma Requête ASP.NET</title>
<link rel="stylesheet" href="~/content/bootstrap.min.css" />
<style>
body {
padding-top: 60px;
}
@@media screen and (max-width: 768px) {
body {
padding-top: 0px;
}
}
</style>
@await RenderSectionAsync("header", required: false)
</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>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Accueil</a></li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Mon Application ASP.NET</p>
</footer>
</div>
@await RenderSectionAsync("footer", required: 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 - Ma Demande ASP.NET</title>
<link rel="stylesheet" href="~/content/bootstrap.min.css" />
<style>
body {
padding-top: 60px;
}
@@media screen and (max-width: 768px) {
body {
padding-top: 0px;
}
}
</style>
@await RenderSectionAsync("header", required: false)
</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>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Accueil</a></li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Mon Application ASP.NET</p>
</footer>
</div>
@await RenderSectionAsync("footer", required: false)
</body>
</html>
| apache-2.0 | C# |
cc92fc77fdbcdba17b01131d20a11f882d90f733 | Add test | sakapon/Samples-2016,sakapon/Samples-2016 | MathSample/PropositionsConsole/Program.cs | MathSample/PropositionsConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Blaze.Propositions;
using static Blaze.Propositions.Formula;
namespace PropositionsConsole
{
class Program
{
static void Main(string[] args)
{
var p = Variable("P");
var q = Variable("Q");
var r = Variable("R");
TestContradiction(p & !p);
TestTautology(p | !p);
TestTautology(Imply(p, !p));
TestContradiction(Imply(p, !p));
TestContradiction(Equivalent(p, !p));
Console.WriteLine();
TestTautology(Equivalent(!(p & q), !p | !q));
TestTautology(Equivalent(!(p | q), !p & !q));
Console.WriteLine();
TestTautology(Imply(Imply(p, q), Imply(q, p)));
TestContradiction(Imply(Imply(p, q), Imply(q, p)));
TestTautology(Imply(p & Imply(p, q), q));
Console.WriteLine();
Console.WriteLine("三段論法:");
TestTautology(Imply(Imply(p, q) & Imply(q, r), Imply(p, r)));
Console.WriteLine("背理法:");
TestTautology(Imply(Imply(p, q) & Imply(p, !q), !p));
Console.WriteLine("対偶:");
TestTautology(Equivalent(Imply(p, q), Imply(!q, !p)));
Console.WriteLine();
}
static void TestTautology(Formula f)
{
Console.WriteLine($"{f} is{(f.IsTautology() ? "" : " not")} a tautology.");
}
static void TestContradiction(Formula f)
{
Console.WriteLine($"{f} is{(f.IsContradiction() ? "" : " not")} a contradiction.");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Blaze.Propositions;
using static Blaze.Propositions.Formula;
namespace PropositionsConsole
{
class Program
{
static void Main(string[] args)
{
var p = Variable("P");
var q = Variable("Q");
var r = Variable("R");
TestContradiction(p & !p);
TestTautology(p | !p);
TestTautology(Imply(p, !p));
TestContradiction(Imply(p, !p));
TestContradiction(Equivalent(p, !p));
}
static void TestTautology(Formula f)
{
Console.WriteLine($"{f} is{(f.IsTautology() ? "" : " not")} a tautology.");
}
static void TestContradiction(Formula f)
{
Console.WriteLine($"{f} is{(f.IsContradiction() ? "" : " not")} a contradiction.");
}
}
}
| mit | C# |
8f57fd4495433a4b3d7a608fac00f4dfed1bbc05 | Tag release with updated version number. | dneelyep/MonoGameUtils | MonoGameUtils/UI/GameComponents/Button.cs | MonoGameUtils/UI/GameComponents/Button.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.UI.GameComponents
{
/// <summary>
/// Represents a rectangular button that can be clicked in a game.
/// </summary>
public class Button : DrawableGameComponent
{
public SpriteFont Font { get; set; }
public Color TextColor { get; set; }
public string Text { get; set; }
public Rectangle Bounds { get; set; }
public Color BackgroundColor { get; set; }
private Texture2D ButtonTexture;
private readonly SpriteBatch spriteBatch;
public Button(Game game, SpriteFont font, Color textColor, string text,
Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game)
{
this.Font = font;
this.TextColor = textColor;
this.Text = text;
this.Bounds = bounds;
this.BackgroundColor = backgroundColor;
this.spriteBatch = spriteBatch;
}
protected override void LoadContent()
{
this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1);
this.ButtonTexture.SetData<Color>(new Color[] { Color.White });
}
public override void Draw(GameTime gameTime)
{
// Draw the button background.
spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor);
// Draw the button text.
spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor);
base.Draw(gameTime);
}
}
}
| using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.UI.GameComponents
{
/// <summary>
/// Represents a rectangular button that can be clicked in a game.
/// </summary>
public class Button : DrawableGameComponent
{
public SpriteFont Font { get; set; }
public Color TextColor { get; set; }
public string Text { get; set; }
public Rectangle Bounds { get; set; }
public Color BackgroundColor { get; set; }
private Texture2D ButtonTexture;
private readonly SpriteBatch spriteBatch;
public Button(Game game, SpriteFont font, Color textColor, string text,
Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game)
{
this.Font = font;
this.TextColor = textColor;
this.Text = text;
this.Bounds = bounds;
this.BackgroundColor = backgroundColor;
this.spriteBatch = spriteBatch;
}
protected override void LoadContent()
{
this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1);
this.ButtonTexture.SetData<Color>(new Color[] { Color.White });
}
public override void Draw(GameTime gameTime)
{
// Draw the button background.
spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor);
// Draw the button text.
spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor);
base.Draw(gameTime);
}
}
}
| mit | C# |
7ecc15a79a85bf10222e2dc092d5d1a13eb769ee | Disable Serilog004 warnings in ILoggerExtensions | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.Logging/Logging/ILoggerExtensions.cs | src/GitHub.Logging/Logging/ILoggerExtensions.cs | using System;
using Serilog;
namespace GitHub.Logging
{
public static class ILoggerExtensions
{
public static void Assert(this ILogger logger, bool condition, string messageTemplate)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate);
#pragma warning restore Serilog004
}
}
public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
#pragma warning disable Serilog004 // propertyValues might not be strings
logger.Warning(messageTemplate, propertyValues);
#pragma warning restore Serilog004
}
}
}
} | using System;
using Serilog;
namespace GitHub.Logging
{
public static class ILoggerExtensions
{
public static void Assert(this ILogger logger, bool condition, string messageTemplate)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
logger.Warning(messageTemplate);
}
}
public static void Assert(this ILogger logger, bool condition, string messageTemplate, params object[] propertyValues)
{
if (!condition)
{
messageTemplate = "Assertion Failed: " + messageTemplate;
logger.Warning(messageTemplate, propertyValues);
}
}
}
} | mit | C# |
31ecba29ad965be7b5d5db5bdef7df15c8a6dcc1 | Make properties a params array | x335/WootzJs,x335/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs | WootzJs.Models/Validation.cs | WootzJs.Models/Validation.cs | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System.Collections.Generic;
namespace WootzJs.Models
{
public class Validation
{
public bool IsValid { get; set; }
public string Message { get; set; }
public IReadOnlyList<Property> Properties { get; set; }
public Validation(bool isValid, params Property[] properties)
{
IsValid = isValid;
Properties = properties;
}
public Validation(bool isValid, string message = null, params Property[] properties)
{
IsValid = isValid;
Message = message;
Properties = properties;
}
}
} | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System.Collections.Generic;
namespace WootzJs.Models
{
public class Validation
{
public bool IsValid { get; set; }
public string Message { get; set; }
public IReadOnlyList<Property> Properties { get; set; }
public Validation(bool isValid, Property[] properties)
{
IsValid = isValid;
Properties = properties;
}
public Validation(bool isValid, string message = null, params Property[] properties)
{
IsValid = isValid;
Message = message;
Properties = properties;
}
}
} | mit | C# |
05c40a518471f98dc43909783fdcdce75291aa73 | fix File.Create leaving the file open | Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache | NuCache.Tests/FileSystemTests/FileExistsTests.cs | NuCache.Tests/FileSystemTests/FileExistsTests.cs | using System;
using System.IO;
using Should;
using Should.Core.Assertions;
namespace NuCache.Tests.FileSystemTests
{
public class FileExistsTests : IDisposable
{
private readonly string _filename;
private readonly FileSystem _fileSystem;
public FileExistsTests()
{
_fileSystem = new FileSystem();
_filename = Guid.NewGuid().ToString() + ".tmp";
File.Create(_filename).Close();
}
public void When_passed_a_relative_path_and_the_file_exists()
{
_fileSystem.FileExists(_filename).ShouldBeTrue();
}
public void When_passed_a_relative_path_and_the_file_does_not_exist()
{
_fileSystem.FileExists("del"+_filename).ShouldBeFalse();
}
public void When_passed_an_absolute_path_and_the_file_exists()
{
var absolute = Path.GetFullPath(_filename);
_fileSystem.FileExists(absolute).ShouldBeTrue();
}
public void When_passed_an_absolute_path_and_the_file_does_not_exist()
{
var absolute = Path.GetFullPath("del" + _filename);
_fileSystem.FileExists(absolute).ShouldBeFalse();
}
public void When_passed_a_blank_filepath()
{
_fileSystem.FileExists(string.Empty).ShouldBeFalse();
}
public void Dispose()
{
try
{
if (File.Exists(_filename))
{
File.Delete(_filename);
}
}
catch (Exception ex)
{
Console.WriteLine("Enable to delete '{0}'", _filename);
}
}
}
}
| using System;
using System.IO;
using Should;
using Should.Core.Assertions;
namespace NuCache.Tests.FileSystemTests
{
public class FileExistsTests : IDisposable
{
private readonly string _filename;
private readonly FileSystem _fileSystem;
public FileExistsTests()
{
_fileSystem = new FileSystem();
_filename = Guid.NewGuid().ToString() + ".tmp";
File.Create(_filename);
}
public void When_passed_a_relative_path_and_the_file_exists()
{
_fileSystem.FileExists(_filename).ShouldBeTrue();
}
public void When_passed_a_relative_path_and_the_file_does_not_exist()
{
_fileSystem.FileExists("del"+_filename).ShouldBeFalse();
}
public void When_passed_an_absolute_path_and_the_file_exists()
{
var absolute = Path.GetFullPath(_filename);
_fileSystem.FileExists(absolute).ShouldBeTrue();
}
public void When_passed_an_absolute_path_and_the_file_does_not_exist()
{
var absolute = Path.GetFullPath("del" + _filename);
_fileSystem.FileExists(absolute).ShouldBeFalse();
}
public void When_passed_a_blank_filepath()
{
_fileSystem.FileExists(string.Empty).ShouldBeFalse();
}
public void Dispose()
{
try
{
if (File.Exists(_filename))
{
File.Delete(_filename);
}
}
catch (Exception ex)
{
Console.WriteLine("Enable to delete '{0}'", _filename);
}
}
}
}
| lgpl-2.1 | C# |
94e75e84f91a39c696e39c8eb6a6d03978768c8b | Handle dir separator better for Mono | maxpiva/CloudFileSystem | NutzCode.CloudFileSystem/AuthorizationFactory.cs | NutzCode.CloudFileSystem/AuthorizationFactory.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NutzCode.Libraries.Web.StreamProvider;
namespace NutzCode.CloudFileSystem
{
public class AuthorizationFactory
{
private static AuthorizationFactory _instance;
public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory());
[Import(typeof(IAppAuthorization))]
public IAppAuthorization AuthorizationProvider { get; set; }
public AuthorizationFactory(string dll=null)
{
Assembly assembly = Assembly.GetEntryAssembly();
string codebase = assembly.CodeBase;
UriBuilder uri = new UriBuilder(codebase);
string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path)
.Replace("/", $"{System.IO.Path.DirectorySeparatorChar}"));
if (dirname != null)
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(assembly));
if (dll!=null)
catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NutzCode.Libraries.Web.StreamProvider;
namespace NutzCode.CloudFileSystem
{
public class AuthorizationFactory
{
private static AuthorizationFactory _instance;
public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory());
[Import(typeof(IAppAuthorization))]
public IAppAuthorization AuthorizationProvider { get; set; }
public AuthorizationFactory(string dll=null)
{
Assembly assembly = Assembly.GetEntryAssembly();
string codebase = assembly.CodeBase;
UriBuilder uri = new UriBuilder(codebase);
string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path).Replace("/", "\\"));
if (dirname != null)
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(assembly));
if (dll!=null)
catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
}
| apache-2.0 | C# |
a33625f4bed1bc074a2d062b7bcd619887c5c94b | Update ICustomDeserializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/ICustomDeserializer.cs | TIKSN.Core/Serialization/ICustomDeserializer.cs | namespace TIKSN.Serialization
{
/// <summary>
/// Custom (specialized or typed) deserializer interface
/// </summary>
/// <typeparam name="TSerial">Type to deserialize from, usually string or byte array</typeparam>
public interface ICustomDeserializer<TSerial, TModel>
{
/// <summary>
/// Deserialize from <typeparamref name="TSerial" /> type to <typeparamref name="TModel" />
/// </summary>
/// <param name="serial"></param>
/// <returns></returns>
TModel Deserialize(TSerial serial);
}
}
| namespace TIKSN.Serialization
{
/// <summary>
/// Custom (specialized or typed) deserializer interface
/// </summary>
/// <typeparam name="TSerial">Type to deserialize from, usually string or byte array</typeparam>
public interface ICustomDeserializer<TSerial, TModel>
{
/// <summary>
/// Deserialize from <typeparamref name="TSerial"/> type to <typeparamref name="TModel"/>
/// </summary>
/// <param name="serial"></param>
/// <returns></returns>
TModel Deserialize(TSerial serial);
}
} | mit | C# |
2579ca1f37b500fb6ddc0385afd44dfffc087e18 | Add EF extension method for unique index with column order | TheOtherTimDuncan/TOTD | TOTD.EntityFramework/ConfigurationExtensions.cs | TOTD.EntityFramework/ConfigurationExtensions.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
| mit | C# |
4626f9425fbef4ce01296c9e4e8b4fa530a046c0 | Update UI/ConferencesIO.UI.Web/Views/Home/Index.cshtml | tekconf/tekconf,tekconf/tekconf | UI/ConferencesIO.UI.Web/Views/Home/Index.cshtml | UI/ConferencesIO.UI.Web/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<h3>We suggest the following steps:</h3>
<ul>
<li>Install CI server</li>
<li>Install OctopusDeploy</li>
<li>????</li>
<li>Profit</li>
</ul>
| @{
ViewBag.Title = "Home Page";
}
<h3>We suggest the following steps:</h3>
| mit | C# |
e596f8d7d76bd5a1e16e58cc1b006f394e4a85be | Throw error when trying to generate indexed tiles without palettes. | Prof9/PixelPet | PixelPet/CLI/Commands/GenerateTilemapCmd.cs | PixelPet/CLI/Commands/GenerateTilemapCmd.cs | using LibPixelPet;
using System;
using System.Drawing;
namespace PixelPet.CLI.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap",
new Parameter(true, new ParameterValue("format")),
new Parameter("no-reduce", "nr", false),
new Parameter("x", "x", false, new ParameterValue("pixels", "0")),
new Parameter("y", "y", false, new ParameterValue("pixels", "0")),
new Parameter("width", "w", false, new ParameterValue("pixels", "-1")),
new Parameter("height", "h", false, new ParameterValue("pixels", "-1"))
) { }
protected override void Run(Workbench workbench, ILogger logger) {
string fmtName = FindUnnamedParameter(0).Values[0].Value;
bool noReduce = FindNamedParameter("--no-reduce").IsPresent;
int x = FindNamedParameter("--x").Values[0].ToInt32();
int y = FindNamedParameter("--y").Values[0].ToInt32();
int w = FindNamedParameter("--width").Values[0].ToInt32();
int h = FindNamedParameter("--height").Values[0].ToInt32();
if (!(TilemapFormat.GetFormat(fmtName) is TilemapFormat fmt)) {
logger?.Log("Unknown tilemap format \"" + fmtName + "\".", LogLevel.Error);
return;
}
int beforeCount = workbench.Tilemap.Count;
using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, logger)) {
if (fmt.IsIndexed) {
if (workbench.PaletteSet.Count <= 0) {
logger?.Log("Cannot generate indexed tiles: no palettes loaded.", LogLevel.Error);
return;
}
workbench.Tilemap.AddBitmapIndexed(bmp, workbench.Tileset, workbench.PaletteSet, fmt, !noReduce);
} else {
workbench.Tilemap.AddBitmap(bmp, workbench.Tileset, fmt, !noReduce);
}
}
workbench.TilemapFormat = fmt;
int addedCount = workbench.Tilemap.Count - beforeCount;
logger?.Log("Generated " + addedCount + " tilemap entries.");
}
}
}
| using LibPixelPet;
using System;
using System.Drawing;
namespace PixelPet.CLI.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap",
new Parameter(true, new ParameterValue("format")),
new Parameter("no-reduce", "nr", false),
new Parameter("x", "x", false, new ParameterValue("pixels", "0")),
new Parameter("y", "y", false, new ParameterValue("pixels", "0")),
new Parameter("width", "w", false, new ParameterValue("pixels", "-1")),
new Parameter("height", "h", false, new ParameterValue("pixels", "-1"))
) { }
protected override void Run(Workbench workbench, ILogger logger) {
string fmtName = FindUnnamedParameter(0).Values[0].Value;
bool noReduce = FindNamedParameter("--no-reduce").IsPresent;
int x = FindNamedParameter("--x").Values[0].ToInt32();
int y = FindNamedParameter("--y").Values[0].ToInt32();
int w = FindNamedParameter("--width").Values[0].ToInt32();
int h = FindNamedParameter("--height").Values[0].ToInt32();
if (!(TilemapFormat.GetFormat(fmtName) is TilemapFormat fmt)) {
logger?.Log("Unknown tilemap format \"" + fmtName + "\".", LogLevel.Error);
return;
}
int beforeCount = workbench.Tilemap.Count;
using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, logger)) {
if (fmt.IsIndexed) {
workbench.Tilemap.AddBitmapIndexed(bmp, workbench.Tileset, workbench.PaletteSet, fmt, !noReduce);
} else {
workbench.Tilemap.AddBitmap(bmp, workbench.Tileset, fmt, !noReduce);
}
}
workbench.TilemapFormat = fmt;
int addedCount = workbench.Tilemap.Count - beforeCount;
logger?.Log("Generated " + addedCount + " tilemap entries.");
}
}
}
| mit | C# |
5e37d2f6c01909ad636a549e6877328aa87ec388 | Implement Super ZZT #lock properly. | SaxxonPike/roton,SaxxonPike/roton | Roton/Emulation/SuperZZT/SuperZztGrammar.cs | Roton/Emulation/SuperZZT/SuperZztGrammar.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roton.Core;
using Roton.Emulation.Execution;
namespace Roton.Emulation.SuperZZT
{
internal sealed class SuperZztGrammar : Grammar
{
public SuperZztGrammar(IColorList colors, IElementList elements) : base(colors, elements)
{
}
protected override IDictionary<string, Func<IOopContext, IOopItem>> GetItems()
{
return new Dictionary<string, Func<IOopContext, IOopItem>>
{
{"AMMO", Item_Ammo},
{"GEMS", Item_Gems},
{"HEALTH", Item_Health},
{"SCORE", Item_Score},
{"TIME", Item_Time},
{"Z", Item_Stones}
};
}
protected override void Command_Lock(IOopContext context)
{
context.Actor.P3 = 1;
}
protected override void Command_Unlock(IOopContext context)
{
context.Actor.P3 = 0;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Roton.Core;
using Roton.Emulation.Execution;
namespace Roton.Emulation.SuperZZT
{
internal sealed class SuperZztGrammar : Grammar
{
public SuperZztGrammar(IColorList colors, IElementList elements) : base(colors, elements)
{
}
protected override IDictionary<string, Func<IOopContext, IOopItem>> GetItems()
{
return new Dictionary<string, Func<IOopContext, IOopItem>>
{
{"AMMO", Item_Ammo},
{"GEMS", Item_Gems},
{"HEALTH", Item_Health},
{"SCORE", Item_Score},
{"TIME", Item_Time},
{"Z", Item_Stones}
};
}
}
}
| isc | C# |
6fc1da8f526c7f2c5b24eb81425c1792b8fac302 | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.86.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.85.*")]
| mit | C# |
78324bb08e378c25fde367ed0349f64b713fab5b | Add add range funciton to interface | kirkchen/EFRepository | EFRepository/IRepository.cs | EFRepository/IRepository.cs | using System.Collections.Generic;
namespace EFRepository
{
/// <summary>
/// IRepository
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
public interface IRepository<TEntity> where TEntity : class
{
/// <summary>
/// Adds the specified data.
/// </summary>
/// <param name="data">The data.</param>
void Add(TEntity data);
/// <summary>
/// Adds the range.
/// </summary>
/// <param name="datalist">The datalist.</param>
void AddRange(IEnumerable<TEntity> datalist);
/// <summary>
/// Saves the changes.
/// </summary>
/// <returns></returns>
int SaveChanges();
}
} | namespace EFRepository
{
/// <summary>
/// IRepository
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
public interface IRepository<TEntity> where TEntity : class
{
/// <summary>
/// Adds the specified data.
/// </summary>
/// <param name="data">The data.</param>
void Add(TEntity data);
/// <summary>
/// Saves the changes.
/// </summary>
/// <returns></returns>
int SaveChanges();
}
} | mit | C# |
b3989dd12d1c777c90128c33c641de3c31a3d3d2 | Update assembly info. | eealeivan/jozh-translit | Src/JoZhTranslit/Properties/AssemblyInfo.cs | Src/JoZhTranslit/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("JoZhTranslit")]
[assembly: AssemblyDescription(".NET transliteration library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Aleksandr Ivanov")]
[assembly: AssemblyProduct("JoZhTranslit")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0cad48c3-0200-4ed3-a2b5-7df638dc1c00")]
[assembly: InternalsVisibleTo("JoZhTranslit.Tests")]
[assembly: InternalsVisibleTo("JoZhTranslit.Tests.Net40")]
// Version information for an assembly consists of the following four values:
//
// MAJOR version when you make incompatible API changes,
// MINOR version when you add functionality in a backwards-compatible manner, and
// PATCH version when you make backwards-compatible bug fixes.
[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("JoZhTranslit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JoZhTranslit")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0cad48c3-0200-4ed3-a2b5-7df638dc1c00")]
[assembly: InternalsVisibleTo("JoZhTranslit.Tests")]
[assembly: InternalsVisibleTo("JoZhTranslit.Tests.Net40")]
// 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.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
cbf485384a376be65ab15b977b161191e7ba93b9 | Update unshelve usage. | codemerlin/git-tfs,steveandpeggyb/Public,hazzik/git-tfs,adbre/git-tfs,jeremy-sylvis-tmg/git-tfs,irontoby/git-tfs,hazzik/git-tfs,irontoby/git-tfs,jeremy-sylvis-tmg/git-tfs,TheoAndersen/git-tfs,spraints/git-tfs,kgybels/git-tfs,andyrooger/git-tfs,modulexcite/git-tfs,steveandpeggyb/Public,allansson/git-tfs,jeremy-sylvis-tmg/git-tfs,allansson/git-tfs,codemerlin/git-tfs,adbre/git-tfs,hazzik/git-tfs,allansson/git-tfs,irontoby/git-tfs,allansson/git-tfs,NathanLBCooper/git-tfs,hazzik/git-tfs,WolfVR/git-tfs,bleissem/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,WolfVR/git-tfs,WolfVR/git-tfs,bleissem/git-tfs,TheoAndersen/git-tfs,TheoAndersen/git-tfs,PKRoma/git-tfs,NathanLBCooper/git-tfs,pmiossec/git-tfs,guyboltonking/git-tfs,vzabavnov/git-tfs,modulexcite/git-tfs,TheoAndersen/git-tfs,spraints/git-tfs,guyboltonking/git-tfs,codemerlin/git-tfs,adbre/git-tfs,NathanLBCooper/git-tfs,steveandpeggyb/Public,kgybels/git-tfs,guyboltonking/git-tfs,git-tfs/git-tfs,kgybels/git-tfs,spraints/git-tfs | GitTfs/Commands/Unshelve.cs | GitTfs/Commands/Unshelve.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NDesk.Options;
using StructureMap;
using Sep.Git.Tfs.Core;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("unshelve")]
[Description("unshelve [options] shelve-name destination-branch")]
[RequiresValidGitRepository]
public class Unshelve : GitTfsCommand
{
private readonly Globals _globals;
private readonly TextWriter _stdout;
public Unshelve(Globals globals, TextWriter stdout)
{
_globals = globals;
_stdout = stdout;
}
public string Owner { get; set; }
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "u|user=", "Shelveset owner (default: current user)\nUse 'all' to search all shelvesets.",
v => Owner = v },
};
}
}
public int Run(string shelvesetName, string destinationBranch)
{
var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId);
remote.Unshelve(Owner, shelvesetName, destinationBranch);
_stdout.WriteLine("Created branch " + destinationBranch + " from shelveset \"" + shelvesetName + "\".");
return GitTfsExitCodes.OK;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NDesk.Options;
using StructureMap;
using Sep.Git.Tfs.Core;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("unshelve")]
[Description("unshelve -u <shelve-owner-name> <shelve-name> <destination-branch>")]
[RequiresValidGitRepository]
public class Unshelve : GitTfsCommand
{
private readonly Globals _globals;
private readonly TextWriter _stdout;
public Unshelve(Globals globals, TextWriter stdout)
{
_globals = globals;
_stdout = stdout;
}
public string Owner { get; set; }
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "u|user=", "Shelveset owner (default: current user)\nUse 'all' to search all shelvesets.",
v => Owner = v },
};
}
}
public int Run(string shelvesetName, string destinationBranch)
{
var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId);
remote.Unshelve(Owner, shelvesetName, destinationBranch);
_stdout.WriteLine("Created branch " + destinationBranch + " from shelveset \"" + shelvesetName + "\".");
return GitTfsExitCodes.OK;
}
}
}
| apache-2.0 | C# |
2d4b8d928d1148ed57d24bf8e7cfce9e53765ae8 | Update MainActivity.cs | iperezmx87/Xamarin30Labs | Lab09/Lab09/MainActivity.cs | Lab09/Lab09/MainActivity.cs | using Android.App;
using Android.Widget;
using Android.OS;
using System;
namespace Lab09
{
[Activity(Label = "Lab09", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
ValidarActividad();
}
private async void ValidarActividad()
{
try
{
SALLab09.ServiceClient client = new SALLab09.ServiceClient();
SALLab09.ResultInfo result = await client.ValidateAsync("", "",
Android.Provider.Settings.Secure.GetString(ContentResolver,
Android.Provider.Settings.Secure.AndroidId));
RunOnUiThread(() =>
{
FindViewById<TextView>(Resource.Id.UserNameValue).Text = result.Fullname;
FindViewById<TextView>(Resource.Id.StatusValue).Text = Enum.GetName(typeof(SALLab09.Status), result.Status);
FindViewById<TextView>(Resource.Id.TokenValue).Text = result.Token;
});
}
catch (Exception ex)
{
Toast.MakeText(this, $"Error: {ex.Message}", ToastLength.Long).Show();
}
}
}
}
| using Android.App;
using Android.Widget;
using Android.OS;
using System;
namespace Lab09
{
[Activity(Label = "Lab09", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
ValidarActividad();
}
private async void ValidarActividad()
{
try
{
SALLab09.ServiceClient client = new SALLab09.ServiceClient();
SALLab09.ResultInfo result = await client.ValidateAsync("israel.perez@cencel.com.mx", "Isra-mx87",
Android.Provider.Settings.Secure.GetString(ContentResolver,
Android.Provider.Settings.Secure.AndroidId));
RunOnUiThread(() =>
{
FindViewById<TextView>(Resource.Id.UserNameValue).Text = result.Fullname;
FindViewById<TextView>(Resource.Id.StatusValue).Text = Enum.GetName(typeof(SALLab09.Status), result.Status);
FindViewById<TextView>(Resource.Id.TokenValue).Text = result.Token;
});
}
catch (Exception ex)
{
Toast.MakeText(this, $"Error: {ex.Message}", ToastLength.Long).Show();
}
}
}
}
| mit | C# |
6a3944aab7819d9b19b6cfd659dd487a2324724d | Mark TimerAttribute as MeansImplicitUse | ikkentim/SampSharp,ikkentim/SampSharp,ikkentim/SampSharp | src/SampSharp.Entities/Timers/TimerAttribute.cs | src/SampSharp.Entities/Timers/TimerAttribute.cs | using System;
using SampSharp.Entities.Annotations;
namespace SampSharp.Entities
{
/// <summary>
/// An attribute which indicates the method should be invoked at a specified interval.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[MeansImplicitUse]
public class TimerAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TimerAttribute"/> class.
/// </summary>
/// <param name="interval">The interval of the timer.</param>
public TimerAttribute(double interval)
{
Interval = interval;
}
/// <summary>
/// Gets or sets the interval of the timer.
/// </summary>
public double Interval { get; set; }
internal TimeSpan IntervalTimeSpan => TimeSpan.FromMilliseconds(Interval);
}
} | using System;
namespace SampSharp.Entities
{
/// <summary>
/// An attribute which indicates the method should be invoked at a specified interval.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class TimerAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TimerAttribute"/> class.
/// </summary>
/// <param name="interval">The interval of the timer.</param>
public TimerAttribute(double interval)
{
Interval = interval;
}
/// <summary>
/// Gets or sets the interval of the timer.
/// </summary>
public double Interval { get; set; }
internal TimeSpan IntervalTimeSpan => TimeSpan.FromMilliseconds(Interval);
}
} | apache-2.0 | C# |
869a15e6cdeca65c8259913187b970e8905c634f | Update MappingFramework/Mapping.cs | GeertBellekens/UML-Tooling-Framework,GeertBellekens/UML-Tooling-Framework | MappingFramework/Mapping.cs | MappingFramework/Mapping.cs |
using System;
using UML=TSF.UmlToolingFramework.UML;
namespace MappingFramework
{
/// <summary>
/// Description of Mapping.
/// </summary>
public interface Mapping
{
MappingNode source {get;set;}
MappingNode target {get;set;}
MappingLogic mappingLogic {get;set;}
string mappingLogicDescription { get; set; }
void save();
}
}
|
using System;
using UML=TSF.UmlToolingFramework.UML;
namespace MappingFramework
{
/// <summary>
/// Description of Mapping.
/// </summary>
public interface Mapping
{
MappingNode source {get;set;}
MappingNode target {get;set;}
MappingLogic mappingLogic {get;set;}
void save();
}
}
| bsd-2-clause | C# |
b05bcd195468b90677edd0f18d68dbe5cf19201c | Fix build | manio143/ShadowsOfShadows | src/Entities/Character.cs | src/Entities/Character.cs | using System;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using ShadowsOfShadows.Items;
using ShadowsOfShadows.Helpers;
using ShadowsOfShadows.Physics;
namespace ShadowsOfShadows.Entities
{
public abstract class Character : Entity, IInteractable, IUpdateable
{
public string Name { get; }
public bool IsMoving { get; set; }
private int Speed;
public int CurrentSpeed { get; set; }
public int Velocity { get; set; }
public List<Item> Equipment { get; }
public Character(string name, char renderChar, int speed, int velocity) : base(new Renderables.ConsoleRenderable(renderChar))
{
this.Name = name;
this.Speed = speed;
this.CurrentSpeed = speed;
this.Velocity = velocity;
this.Equipment = new List<Item>();
}
public Character(string name, char renderChar, int speed, int velocity, List<Item> equipment)
: this(name, renderChar, speed, velocity)
{
this.Equipment = equipment;
}
public void Interact()
{
}
private void Move()
{
if (IsMoving == false)
return;
switch (Transform.Direction)
{
case Direction.Right:
Transform.Position = new Point(Transform.Position.X + Velocity, Transform.Position.Y);
break;
case Direction.Left:
Transform.Position = new Point(Transform.Position.X - Velocity, Transform.Position.Y);
break;
case Direction.Up:
Transform.Position = new Point(Transform.Position.X, Transform.Position.Y - Velocity);
break;
case Direction.Down:
Transform.Position = new Point(Transform.Position.X, Transform.Position.Y + Velocity);
break;
}
}
public void Update(TimeSpan deltaTime)
{
CurrentSpeed--;
if (CurrentSpeed == 0)
{
CurrentSpeed = Speed;
Move();
}
}
public abstract void Shoot<T>(Direction direction) where T : Projectile;
public double Health { get; set; }
public double AttackPower { get; set; }
public double DefencePower { get; set; }
public double Mana { get; set; }
public bool Immortal { get; set; }
public double MagicPower { get; set; }
public double MaxMana { get; set; }
public double MaxHealth { get; set; }
public void Attack(Character character)
{
this.Health -= character.DefencePower;
character.Health -= this.AttackPower;
}
}
}
| using System;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using ShadowsOfShadows.Items;
using ShadowsOfShadows.Helpers;
using ShadowsOfShadows.Physics;
namespace ShadowsOfShadows.Entities
{
public abstract class Character : Entity, IInteractable, IUpdateable
{
public string Name { get; }
public bool IsMoving { get; set; }
private int Speed;
public int CurrentSpeed { get; set; }
public int Velocity { get; set; }
public List<Item> Equipment { get; }
public Character(string name, char renderChar, int speed, int velocity) : base(new Renderables.ConsoleRenderable(renderChar))
{
this.Name = name;
this.Speed = speed;
this.CurrentSpeed = speed;
this.Velocity = velocity;
this.Equipment = new List<Item>();
}
public Character(string name, char renderChar, int speed, int velocity, List<Item> equipment)
: this(name, renderChar, speed, velocity)
{
this.Equipment = equipment;
}
public void Interact()
{
}
private void Move()
{
if (IsMoving == false)
return;
switch (Transform.Direction)
{
case Direction.Right:
Transform.Position = new Point(Transform.Position.X + Velocity, Transform.Position.Y);
break;
case Direction.Left:
Transform.Position = new Point(Transform.Position.X - Velocity, Transform.Position.Y);
break;
case Direction.Up:
Transform.Position = new Point(Transform.Position.X, Transform.Position.Y - Velocity);
break;
case Direction.Down:
Transform.Position = new Point(Transform.Position.X, Transform.Position.Y + Velocity);
break;
}
}
public void Update(TimeSpan deltaTime)
{
CurrentSpeed--;
if (CurrentSpeed == 0)
{
CurrentSpeed = Speed;
Move();
}
}
public abstract void Shoot<T>(Direction direction) where T : Projectile;
public double Health { get; set; }
public double AttackPower { get; set; }
public double DefencePower { get; set; }
public double Mana { get; set; }
public bool Immortal { get; set; }
public double MagicPower { get; set; }
public void Attack(Character character)
{
this.Health -= character.DefencePower;
character.Health -= this.AttackPower;
}
}
}
| mit | C# |
250e3cac5b33be8fb94fd47417ff26e1751c1af4 | Fix typo | jacobdufault/fullserializer,darress/fullserializer,jacobdufault/fullserializer,jagt/fullserializer,Ksubaka/fullserializer,jagt/fullserializer,shadowmint/fullserializer,jacobdufault/fullserializer,jagt/fullserializer,Ksubaka/fullserializer,zodsoft/fullserializer,nuverian/fullserializer,lazlo-bonin/fullserializer,Ksubaka/fullserializer,caiguihou/myprj_02,shadowmint/fullserializer,shadowmint/fullserializer,karlgluck/fullserializer | Source/Internal/fsOption.cs | Source/Internal/fsOption.cs | using System;
namespace FullSerializer.Internal {
/// <summary>
/// Simple option type. This is akin to nullable types.
/// </summary>
public struct fsOption<T> {
private bool _hasValue;
private T _value;
public bool HasValue {
get { return _hasValue; }
}
public bool IsEmpty {
get { return _hasValue == false; }
}
public T Value {
get {
if (IsEmpty) throw new InvalidOperationException("fsOption is empty");
return _value;
}
}
public fsOption(T value) {
_hasValue = true;
_value = value;
}
public static fsOption<T> Empty;
}
public static class fsOption {
public static fsOption<T> Just<T>(T value) {
return new fsOption<T>(value);
}
}
} | using System;
namespace FullSerializer.Internal {
/// <summary>
/// Simple option time. This is akin to nullable types.
/// </summary>
public struct fsOption<T> {
private bool _hasValue;
private T _value;
public bool HasValue {
get { return _hasValue; }
}
public bool IsEmpty {
get { return _hasValue == false; }
}
public T Value {
get {
if (IsEmpty) throw new InvalidOperationException("fsOption is empty");
return _value;
}
}
public fsOption(T value) {
_hasValue = true;
_value = value;
}
public static fsOption<T> Empty;
}
public static class fsOption {
public static fsOption<T> Just<T>(T value) {
return new fsOption<T>(value);
}
}
} | mit | C# |
55e8336d7e0e5ca9d3aa40a22118a6f578601b27 | fix FaultSetCollection.GetMinimalSets() | maul-esel/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp | Source/SafetySharp/Analysis/FaultSetCollection.cs | Source/SafetySharp/Analysis/FaultSetCollection.cs | using System;
using System.Collections;
using System.Collections.Generic;
using SafetySharp.Runtime;
namespace SafetySharp.Analysis
{
class FaultSetCollection : IEnumerable<FaultSet>
{
private readonly int numFaults;
private readonly HashSet<FaultSet>[] elementsByCardinality;
public FaultSetCollection(int numFaults)
{
this.numFaults = numFaults;
elementsByCardinality = new HashSet<FaultSet>[numFaults + 1];
}
public void Add(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality] == null)
elementsByCardinality[cardinality] = new HashSet<FaultSet>();
elementsByCardinality[cardinality].Add(set);
}
public bool ContainsSubsetOf(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality]?.Contains(set) ?? false)
return true;
return ContainsProperSubsetOf(set);
}
public bool ContainsProperSubsetOf(FaultSet set)
{
var cardinality = set.Cardinality;
for (int i = 0; i < cardinality; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (element.IsSubsetOf(set))
return true;
}
}
return false;
}
public bool ContainsSupersetOf(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality]?.Contains(set) ?? false)
return true;
for (int i = numFaults; i > cardinality; --i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (set.IsSubsetOf(element))
return true;
}
}
return false;
}
public HashSet<FaultSet> GetMinimalSets()
{
var result = new HashSet<FaultSet>();
for (int i = 0; i <= numFaults; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (!ContainsProperSubsetOf(element))
result.Add(element);
}
}
return result;
}
public IEnumerator<FaultSet> GetEnumerator()
{
for (int i = 0; i <= numFaults; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
yield return element;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using SafetySharp.Runtime;
namespace SafetySharp.Analysis
{
class FaultSetCollection : IEnumerable<FaultSet>
{
private readonly int numFaults;
private readonly HashSet<FaultSet>[] elementsByCardinality;
public FaultSetCollection(int numFaults)
{
this.numFaults = numFaults;
elementsByCardinality = new HashSet<FaultSet>[numFaults + 1];
}
public void Add(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality] == null)
elementsByCardinality[cardinality] = new HashSet<FaultSet>();
elementsByCardinality[cardinality].Add(set);
}
public bool ContainsSubsetOf(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality]?.Contains(set) ?? false)
return true;
for (int i = 0; i < cardinality; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (element.IsSubsetOf(set))
return true;
}
}
return false;
}
public bool ContainsSupersetOf(FaultSet set)
{
var cardinality = set.Cardinality;
if (elementsByCardinality[cardinality]?.Contains(set) ?? false)
return true;
for (int i = numFaults; i > cardinality; --i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (set.IsSubsetOf(element))
return true;
}
}
return false;
}
public HashSet<FaultSet> GetMinimalSets()
{
var result = new HashSet<FaultSet>();
for (int i = 0; i <= numFaults; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
{
if (!ContainsSubsetOf(element))
result.Add(element);
}
}
return result;
}
public IEnumerator<FaultSet> GetEnumerator()
{
for (int i = 0; i <= numFaults; ++i)
{
if (elementsByCardinality[i] == null)
continue;
foreach (var element in elementsByCardinality[i])
yield return element;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| mit | C# |
d8865a2fc6897663288365b523416408d9e73204 | Remove Expenses from Report. | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey.Business/Report.cs | client/BlueMonkey/BlueMonkey.Business/Report.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
namespace BlueMonkey.Business
{
public class Report : BindableBase
{
private string _id;
public string Id
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
private DateTime _date;
public DateTime Date
{
get { return _date; }
set { SetProperty(ref _date, value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { SetProperty(ref _userId, value); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
namespace BlueMonkey.Business
{
public class Report : BindableBase
{
private string _id;
public string Id
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
private DateTime _date;
public DateTime Date
{
get { return _date; }
set { SetProperty(ref _date, value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { SetProperty(ref _userId, value); }
}
public ObservableCollection<Expense> Expenses { get; } = new ObservableCollection<Expense>();
}
}
| mit | C# |
78e829397c85f4c4d067cd389a4a94aaec8cc83a | Truncate user-agent version. | GetTabster/Tabster | Tabster/TabsterWebClient.cs | Tabster/TabsterWebClient.cs | #region
using System.Net;
using System.Text;
using System.Windows.Forms;
#endregion
namespace Tabster
{
public class TabsterWebClient : WebClient
{
public TabsterWebClient(IWebProxy proxy = null)
{
Proxy = proxy;
Encoding = Encoding.UTF8;
Headers.Add("user-agent", string.Format("Tabster {0}", Common.TruncateVersion(Application.ProductVersion)));
}
}
} | #region
using System.Net;
using System.Text;
using System.Windows.Forms;
#endregion
namespace Tabster
{
public class TabsterWebClient : WebClient
{
public TabsterWebClient(IWebProxy proxy = null)
{
Proxy = proxy;
Encoding = Encoding.UTF8;
Headers.Add("user-agent", string.Format("Tabster {0}", Application.ProductVersion));
}
}
} | apache-2.0 | C# |
b01cd12922fef944e68f920c823a1fc382a2b775 | update spatial refrence help text | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/Views/Shared/_SpatialReference.cshtml | WebAPI.API/Views/Shared/_SpatialReference.cshtml | <p class="help-block">
The spatial reference for the output and input geometries.
<strong class="text-warning">The output and input spatial references must match.</strong>
Choose any of the <abbr title="Well-known Id">wkid</abbr>'s from the
<a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/geographic_coordinate_systems.pdf">Geographic Coordinate System wkid reference</a>
or <a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/projected_coordinate_systems.pdf">Projected Coordinate System wkid reference</a>.
<code>26912</code> is the default.
</p>
<span class="label label-info">Popular WKID's</span>
<table class="table table-condensed">
<thead>
<tr>
<th>System</th>
<th>wkid</th>
</tr>
</thead>
<tbody>
<tr>
<td>Web Mercator</td>
<td>3857</td>
</tr>
<tr>
<td>Latitude/Longitude (WGS84)</td>
<td>4326</td>
</tr>
</tbody>
</table>
| <p class="help-block">
The spatial reference of the input geographic coordinate pair.
Choose any of the <abbr title="Well-known Id">wkid</abbr>'s from the
<a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/geographic_coordinate_systems.pdf">Geographic Coordinate System wkid reference</a>
or <a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/projected_coordinate_systems.pdf">Projected Coordinate System wkid reference</a>.
<code>26912</code> is the default.
</p>
<span class="label label-info">Popular WKID's</span>
<table class="table table-condensed">
<thead>
<tr>
<th>System</th>
<th>wkid</th>
</tr>
</thead>
<tbody>
<tr>
<td>Web Mercator</td>
<td>3857</td>
</tr>
<tr>
<td>Latitude/Longitude (WGS84)</td>
<td>4326</td>
</tr>
</tbody>
</table>
| mit | C# |
a0f03e1f307b193fcebe682ec7a08f384322338a | Add Dustin2 to Contact page. | jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
<strong>Dustin2:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
</address> | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
</address> | mit | C# |
6f864db660c061dd666b20dc5ea59518485782ca | Make demo script comply with guidelines | DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Examples/Experimental/Demos/UX/ObjectManipulator/Scripts/ReturnToBounds.cs | Assets/MixedRealityToolkit.Examples/Experimental/Demos/UX/ObjectManipulator/Scripts/ReturnToBounds.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Experimental.Demos
{
public class ReturnToBounds : MonoBehaviour
{
[SerializeField]
private Transform frontBounds = null;
public Transform FrontBounds
{
get => frontBounds;
set => frontBounds = value;
}
[SerializeField]
private Transform backBounds = null;
public Transform BackBounds
{
get => backBounds;
set => backBounds = value;
}
[SerializeField]
private Transform leftBounds = null;
public Transform LeftBounds
{
get => leftBounds;
set => leftBounds = value;
}
[SerializeField]
private Transform rightBounds = null;
public Transform RightBounds
{
get => rightBounds;
set => rightBounds = value;
}
[SerializeField]
private Transform bottomBounds = null;
public Transform BottomBounds
{
get => bottomBounds;
set => bottomBounds = value;
}
[SerializeField]
private Transform topBounds = null;
public Transform TopBounds
{
get => topBounds;
set => topBounds = value;
}
private Vector3 positionAtStart;
// Start is called before the first frame update
void Start()
{
positionAtStart = transform.position;
}
// Update is called once per frame
void Update()
{
if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x ||
transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y ||
transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z)
{
transform.position = positionAtStart;
}
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReturnToBounds : MonoBehaviour
{
[SerializeField]
Transform frontBounds = null;
[SerializeField]
Transform backBounds = null;
[SerializeField]
Transform leftBounds = null;
[SerializeField]
Transform rightBounds = null;
[SerializeField]
Transform bottomBounds = null;
[SerializeField]
Transform topBounds = null;
Vector3 positionAtStart;
// Start is called before the first frame update
void Start()
{
positionAtStart = transform.position;
}
// Update is called once per frame
void Update()
{
if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x ||
transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y ||
transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z)
{
transform.position = positionAtStart;
}
}
}
| mit | C# |
a13ff0d4c3e6685729b7e9f9d44d6bee5e8ec889 | Apply suggestions from code review | mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers | src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs | src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDiagnosticAnalyzerApiUsageAnalyzer : DiagnosticAnalyzerApiUsageAnalyzer<TypeSyntax>
{
protected override bool IsNamedTypeDeclarationBlock(SyntaxNode syntax)
{
switch (syntax.Kind())
{
case SyntaxKind.ClassDeclaration:
#if CODEANALYSIS_V3_OR_BETTER
case SyntaxKind.RecordDeclaration:
#endif
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
return true;
default:
return false;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDiagnosticAnalyzerApiUsageAnalyzer : DiagnosticAnalyzerApiUsageAnalyzer<TypeSyntax>
{
protected override bool IsNamedTypeDeclarationBlock(SyntaxNode syntax)
{
switch (syntax.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
return true;
default:
return false;
}
}
}
}
| mit | C# |
fb6ca1e24300120f387c95c0247007606b385c8d | Add Radius property to support ShapeType.Circle | MiXTelematics/MiX.Integrate.Api.Client | MiX.Integrate.Shared/Entities/Locations/Location.cs | MiX.Integrate.Shared/Entities/Locations/Location.cs | using System.Collections.Generic;
namespace MiX.Integrate.Shared.Entities.Locations
{
/// <summary>
/// defines a Location for a shape on a map.
/// </summary>
public class Location
{
/// <summary>Unique Id for the location</summary>
public long LocationId { get; set; }
/// <summary>Name of the location</summary>
public string Name { get; set; }
/// <summary>Address of the location</summary>
public string Address { get; set; }
/// <summary>Type of location</summary>
public LocationType LocationType { get; set; }
/// <summary>The type of shape describing the location</summary>
public ShapeType ShapeType { get; set; }
/// <summary>Radius of circle in metres. Only significant when <see cref="ShapeType"/> is <see cref=" Locations.ShapeType.Circle"/></summary>
public double Radius { get; set; }
/// <summary>The Well Known Text representation of the location shape. When <see cref="ShapeType"/> is <see cref="Locations.ShapeType.Circle"/>,
/// this property is the Well Known Text representation of the centre of the circle.</summary>
public string ShapeWkt { get; set; }
/// <summary>Signifies that the location has been logically deleted from the system.</summary>
public bool IsDeleted { get; set; }
/// <summary>Colour to use when rendering the shape</summary>
public string ColourOnMap { get; set; }
/// <summary>Opacity to use when rendering the shape</summary>
public decimal OpacityOnMap { get; set; }
/// <summary>Signifies that this is a temporary location for use in routing</summary>
public bool IsTemporary { get; set; }
public const string DEFAULT_COLOUR = "Blue";
public const decimal DEFAULT_OPACITY = 0.1M;
public static readonly List<string> LOCATION_COLOURS = new List<string>
{
"Black", "Blue", "Green", "Teal", "DeepSkyBlue", "Aqua", "ForestGreen", "LimeGreen",
"Indigo", "DimGray", "Maroon", "Purple", "LightGreen", "LightBlue", "FireBrick", "IndianRed",
"Orchid", "Crimson", "LightCoral", "Red", "DeepPink", "DarkOrange", "LightPink", "Yellow"
};
}
}
| using System.Collections.Generic;
namespace MiX.Integrate.Shared.Entities.Locations
{
/// <summary>
/// defines a Location for a shape on a map.
/// </summary>
public class Location
{
/// <summary>Unique Id for the location</summary>
public long LocationId { get; set; }
/// <summary>Name of the location</summary>
public string Name { get; set; }
/// <summary>Address of the location</summary>
public string Address { get; set; }
/// <summary>Type of location</summary>
public LocationType LocationType { get; set; }
/// <summary>The type of shape describing the location</summary>
public ShapeType ShapeType { get; set; }
/// <summary>The Well Known Text describing the outline of the shape</summary>
public string ShapeWkt { get; set; }
/// <summary>Signifies that the location has been logically deleted from the system.</summary>
public bool IsDeleted { get; set; }
/// <summary>Colour to render the shape on a map</summary>
public string ColourOnMap { get; set; }
/// <summary>Opacity to use when rending shape on a map</summary>
public decimal OpacityOnMap { get; set; }
/// <summary>Signifies that this is a temporary location for use in routing</summary>
public bool IsTemporary { get; set; }
public const string DEFAULT_COLOUR = "Blue";
public const decimal DEFAULT_OPACITY = 0.1M;
public static readonly List<string> LOCATION_COLOURS = new List<string>
{
"Black", "Blue", "Green", "Teal", "DeepSkyBlue", "Aqua", "ForestGreen", "LimeGreen",
"Indigo", "DimGray", "Maroon", "Purple", "LightGreen", "LightBlue", "FireBrick", "IndianRed",
"Orchid", "Crimson", "LightCoral", "Red", "DeepPink", "DarkOrange", "LightPink", "Yellow"
};
///// <summary>Geographic coordinate</summary>
//public class Coordinate
//{
// /// <summary>Longitude of coordinate</summary>
// public float Longitude { get; set; }
// /// <summary>Latitude of coordinate</summary>
// public float Latitude { get; set; }
//}
///// <summary>Centre coordinate of the location</summary>
//public Coordinate Centre { get; set; }
///// <summary>Radius of the shape</summary>
//public decimal RadiusKilometers { get; set; }
///// <summary>Upper left coordinate of the bounding rectangle around the shape</summary>
//public Coordinate BoundingUpperLeft { get; set; }
///// <summary>Lower right coordinate of the bounding rectangle around the shape</summary>
//public Coordinate BoundingLowerRight { get; set; }
}
}
| mit | C# |
638ce41c5434059a1a3002628a0c37344e480b8e | Fix the DoorRecorder (PunRPC) | DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17 | Proto/Assets/Scripts/Time/Recorders/DoorRecorder.cs | Proto/Assets/Scripts/Time/Recorders/DoorRecorder.cs | using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DoorRecorder : Recorder
{
private RecordState _previousState;
private bool _isOpen;
private readonly Dictionary<int, DoorRecordState> _states = new Dictionary<int, DoorRecordState>();
[SerializeField]
private new void Start()
{
_isOpen = false;
base.Start();
}
internal override RecordState FindClosestState(int key)
{
var index = FindClosestKey(key, new List<int>(_states.Keys));
return !_states.ContainsKey(index) ? _previousState : _states[index];
}
protected override int DoOnTick(int time)
{
if (this == null) return 0;
var curState = new DoorRecordState(_isOpen);
if (curState.Equals(_previousState)) return 0;
_previousState = curState;
_states[time] = curState;
return 0;
}
public void DoorInteraction(bool isOpen)
{
_isOpen = isOpen;
OpenDoor();
}
public bool DoorStatus()
{
return _isOpen;
}
[PunRPC]
internal override void DoRewind(int time)
{
if (this == null) return;
if (_states.ContainsKey(time))
{
PlayState(_states[time]);
}
else
{
PlayState(_states.Last().Key < time ? _previousState : FindClosestState(time));
}
}
internal override void PlayState<T>(T recordState)
{
if (!(recordState is DoorRecordState)) return;
var state = recordState as DoorRecordState;
DoorInteraction(state.IsOpen);
}
private void OpenDoor()
{
GetComponent<PhotonView>().RPC("RPCDoorInteract", PhotonTargets.All, DoorStatus());
}
[PunRPC]
void RPCDoorInteract(bool isOpen)
{
//if (!PhotonNetwork.isMasterClient) return;
//if (isOpen) PhotonNetwork.Destroy(gameObject);
//else
GetComponent<Renderer>().enabled = isOpen;
}
} | using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DoorRecorder : Recorder
{
private RecordState _previousState;
private bool _isOpen;
private readonly Dictionary<int, DoorRecordState> _states = new Dictionary<int, DoorRecordState>();
[SerializeField]
private new void Start()
{
_isOpen = false;
base.Start();
}
internal override RecordState FindClosestState(int key)
{
var index = FindClosestKey(key, new List<int>(_states.Keys));
return !_states.ContainsKey(index) ? _previousState : _states[index];
}
protected override int DoOnTick(int time)
{
if (this == null) return 0;
var curState = new DoorRecordState(_isOpen);
if (curState.Equals(_previousState)) return 0;
_previousState = curState;
_states[time] = curState;
return 0;
}
public void DoorInteraction(bool isOpen)
{
_isOpen = isOpen;
OpenDoor();
}
public bool DoorStatus()
{
return _isOpen;
}
internal override void DoRewind(int time)
{
if (this == null) return;
if (_states.ContainsKey(time))
{
PlayState(_states[time]);
}
else
{
PlayState(_states.Last().Key < time ? _previousState : FindClosestState(time));
}
}
internal override void PlayState<T>(T recordState)
{
if (!(recordState is DoorRecordState)) return;
var state = recordState as DoorRecordState;
DoorInteraction(state.IsOpen);
}
private void OpenDoor()
{
var param = new object[2];
param[0] = DoorStatus();
param[1] = gameObject;
GetComponent<PhotonView>().RPC("RPCDoorInteract", PhotonTargets.All, param);
}
[PunRPC]
void RPCDoorInteract(bool isOpen)
{
//if (!PhotonNetwork.isMasterClient) return;
//if (isOpen) PhotonNetwork.Destroy(gameObject);
//else
GetComponent<Renderer>().enabled = isOpen;
}
} | mit | C# |
109ee87d08d625d50c429d7bc5ca1d9b9674a21e | fix up assembly info | half-ogre/OwinDispatcher,half-ogre/OwinDispatcher | OwinDispatcher/Properties/AssemblyInfo.cs | OwinDispatcher/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Andrew Miller")]
[assembly: AssemblyProduct("OwinDispatcher")]
[assembly: AssemblyTitle("OwinDispatcher")]
[assembly: AssemblyCopyright("Copyright (C) 2013 Andrew Miller")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.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("OwinDispatcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OwinDispatcher")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("be3eea02-4781-479d-8036-0123a653cfb4")]
// 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# |
f019339cecd3b6b3972d6aa31d47e7f8d23ab89e | improve ContextPropagationToken doc comment | ejona86/grpc,grpc/grpc,muxi/grpc,jtattermusch/grpc,firebase/grpc,nicolasnoble/grpc,sreecha/grpc,stanley-cheung/grpc,vjpai/grpc,nicolasnoble/grpc,ctiller/grpc,nicolasnoble/grpc,nicolasnoble/grpc,ejona86/grpc,muxi/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jtattermusch/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,donnadionne/grpc,pszemus/grpc,donnadionne/grpc,muxi/grpc,stanley-cheung/grpc,carl-mastrangelo/grpc,nicolasnoble/grpc,ejona86/grpc,jtattermusch/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jtattermusch/grpc,muxi/grpc,firebase/grpc,jtattermusch/grpc,sreecha/grpc,nicolasnoble/grpc,donnadionne/grpc,muxi/grpc,pszemus/grpc,jtattermusch/grpc,sreecha/grpc,grpc/grpc,donnadionne/grpc,ctiller/grpc,sreecha/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,sreecha/grpc,vjpai/grpc,carl-mastrangelo/grpc,jboeuf/grpc,muxi/grpc,grpc/grpc,carl-mastrangelo/grpc,grpc/grpc,ctiller/grpc,donnadionne/grpc,carl-mastrangelo/grpc,muxi/grpc,donnadionne/grpc,nicolasnoble/grpc,ejona86/grpc,vjpai/grpc,carl-mastrangelo/grpc,pszemus/grpc,grpc/grpc,pszemus/grpc,vjpai/grpc,carl-mastrangelo/grpc,ejona86/grpc,carl-mastrangelo/grpc,vjpai/grpc,donnadionne/grpc,jtattermusch/grpc,jboeuf/grpc,ejona86/grpc,vjpai/grpc,grpc/grpc,stanley-cheung/grpc,muxi/grpc,ctiller/grpc,sreecha/grpc,sreecha/grpc,firebase/grpc,jboeuf/grpc,donnadionne/grpc,ctiller/grpc,muxi/grpc,jboeuf/grpc,firebase/grpc,stanley-cheung/grpc,donnadionne/grpc,jboeuf/grpc,sreecha/grpc,firebase/grpc,carl-mastrangelo/grpc,grpc/grpc,vjpai/grpc,pszemus/grpc,grpc/grpc,ejona86/grpc,carl-mastrangelo/grpc,jtattermusch/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,jtattermusch/grpc,pszemus/grpc,muxi/grpc,firebase/grpc,grpc/grpc,muxi/grpc,stanley-cheung/grpc,pszemus/grpc,vjpai/grpc,vjpai/grpc,firebase/grpc,nicolasnoble/grpc,vjpai/grpc,stanley-cheung/grpc,ctiller/grpc,pszemus/grpc,stanley-cheung/grpc,donnadionne/grpc,ejona86/grpc,donnadionne/grpc,carl-mastrangelo/grpc,ctiller/grpc,ctiller/grpc,ctiller/grpc,carl-mastrangelo/grpc,stanley-cheung/grpc,jboeuf/grpc,ejona86/grpc,ejona86/grpc,grpc/grpc,nicolasnoble/grpc,jtattermusch/grpc,pszemus/grpc,firebase/grpc,firebase/grpc,ctiller/grpc,muxi/grpc,jboeuf/grpc,grpc/grpc,jboeuf/grpc,firebase/grpc,pszemus/grpc,jboeuf/grpc,jtattermusch/grpc,sreecha/grpc,sreecha/grpc,vjpai/grpc,vjpai/grpc,sreecha/grpc,pszemus/grpc,jboeuf/grpc,ejona86/grpc,pszemus/grpc,jtattermusch/grpc,sreecha/grpc,firebase/grpc,stanley-cheung/grpc,nicolasnoble/grpc,firebase/grpc,grpc/grpc | src/csharp/Grpc.Core/ContextPropagationToken.cs | src/csharp/Grpc.Core/ContextPropagationToken.cs | #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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
namespace Grpc.Core
{
/// <summary>
/// Token for propagating context of server side handlers to child calls.
/// In situations when a backend is making calls to another backend,
/// it makes sense to propagate properties like deadline and cancellation
/// token of the server call to the child call.
/// Underlying gRPC implementation may provide other "opaque" contexts (like tracing context) that
/// are not explicitly accesible via the public C# API, but this token still allows propagating them.
/// </summary>
public abstract class ContextPropagationToken
{
internal ContextPropagationToken()
{
}
}
}
| #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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
namespace Grpc.Core
{
/// <summary>
/// Token for propagating context of server side handlers to child calls.
/// In situations when a backend is making calls to another backend,
/// it makes sense to propagate properties like deadline and cancellation
/// token of the server call to the child call.
/// The gRPC native layer provides some other contexts (like tracing context) that
/// are not accessible to explicitly C# layer, but this token still allows propagating them.
/// </summary>
public abstract class ContextPropagationToken
{
internal ContextPropagationToken()
{
}
}
}
| apache-2.0 | C# |
4ad2d0cfb606835a9fe82ddb3b22181588e04e33 | Remove deprecated debug setting | UselessToucan/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,peppy/osu | osu.Game/Overlays/Settings/Sections/Debug/GeneralSettings.cs | osu.Game/Overlays/Settings/Sections/Debug/GeneralSettings.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Show log overlay",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = "Bypass front-to-back render pass",
Bindable = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass)
}
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GeneralSettings : SettingsSubsection
{
protected override string Header => "General";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Show log overlay",
Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay)
},
new SettingsCheckbox
{
LabelText = "Performance logging",
Bindable = config.GetBindable<bool>(DebugSetting.PerformanceLogging)
},
new SettingsCheckbox
{
LabelText = "Bypass front-to-back render pass",
Bindable = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass)
}
};
}
}
}
| mit | C# |
10a9d97e32f2ded7b7ea0cfbe4bc3ba546528af9 | Fix PythiaOptions (#59565) | shyamnamboodiripad/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,bartdesmet/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,dotnet/roslyn,mavasani/roslyn,weltkante/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn | src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaOptions.cs | src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaOptions.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.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaOptions
{
public const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
public static readonly Option<bool> ShowDebugInfo = new(
"InternalFeatureOnOffOptions", nameof(ShowDebugInfo), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ShowDebugInfo)));
public static readonly Option<bool> RemoveRecommendationLimit = new(
"InternalFeatureOnOffOptions", nameof(RemoveRecommendationLimit), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(RemoveRecommendationLimit)));
}
[ExportSolutionOptionProvider, Shared]
internal class PythiaOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PythiaOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; }
= ImmutableArray.Create<IOption>(
PythiaOptions.ShowDebugInfo,
PythiaOptions.RemoveRecommendationLimit);
}
}
| // 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.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaOptions
{
public const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
public static readonly Option2<bool> ShowDebugInfo = new(
"InternalFeatureOnOffOptions", nameof(ShowDebugInfo), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ShowDebugInfo)));
public static readonly Option2<bool> RemoveRecommendationLimit = new(
"InternalFeatureOnOffOptions", nameof(RemoveRecommendationLimit), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(RemoveRecommendationLimit)));
}
[ExportSolutionOptionProvider, Shared]
internal class PythiaOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PythiaOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; }
= ImmutableArray.Create<IOption>(
PythiaOptions.ShowDebugInfo,
PythiaOptions.RemoveRecommendationLimit);
}
}
| mit | C# |
c9f27c638c7c8cfe7b6ebce6ce175d2f281c012d | create folder if it does not exist | cvent/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET | Src/Metrics/Reporters/TextFileReporter.cs | Src/Metrics/Reporters/TextFileReporter.cs | using System.Collections.Generic;
using System.IO;
namespace Metrics.Reporters
{
public class TextFileReporter : HumanReadableReporter
{
private readonly string fileName;
private readonly List<string> buffer = new List<string>();
public TextFileReporter(string fileName)
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
this.fileName = fileName;
}
protected override void WriteLine(string line, params string[] args)
{
this.buffer.Add(string.Format(line, args));
}
protected override void EndReport()
{
base.EndReport();
File.WriteAllLines(this.fileName, this.buffer);
buffer.Clear();
}
}
}
| using System.Collections.Generic;
using System.IO;
namespace Metrics.Reporters
{
public class TextFileReporter : HumanReadableReporter
{
private readonly string fileName;
private readonly List<string> buffer = new List<string>();
public TextFileReporter(string fileName)
{
this.fileName = fileName;
}
protected override void WriteLine(string line, params string[] args)
{
this.buffer.Add(string.Format(line, args));
}
protected override void EndReport()
{
base.EndReport();
File.WriteAllLines(this.fileName, this.buffer);
buffer.Clear();
}
}
}
| apache-2.0 | C# |
25f35d2c58371405eb574734dfb966f42d192c1e | Remove semicolon as it causes a JS parse error on Edge | stackify/stackify-api-dotnet,stackify/stackify-api-dotnet,stackify/stackify-api-dotnet | Src/StackifyLib/Web/RealUserMonitoring.cs | Src/StackifyLib/Web/RealUserMonitoring.cs | using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StackifyLib.Utils;
namespace StackifyLib.Web
{
public static class RealUserMonitoring
{
public static string GetHeaderScript()
{
var rumScriptUrl = Config.RumScriptUrl;
var rumKey = Config.RumKey;
if (string.IsNullOrWhiteSpace(rumScriptUrl) || string.IsNullOrWhiteSpace(rumKey))
{
// If we don't have a key and url, don't insert the script
return "";
}
var settings = new JObject();
var reqId = HelperFunctions.GetRequestId();
if (reqId != null)
{
settings["ID"] = reqId;
}
var appName = HelperFunctions.GetAppName();
if (!string.IsNullOrWhiteSpace(appName))
{
settings["Name"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(appName));
}
var environment = HelperFunctions.GetAppEnvironment();
if (!string.IsNullOrWhiteSpace(environment))
{
settings["Env"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(environment));
}
var reportingUrl = HelperFunctions.GetReportingUrl();
if (reportingUrl != null)
{
reportingUrl = HelperFunctions.MaskReportingUrl(reportingUrl);
settings["Trans"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(reportingUrl));
}
return string.Format(@"<script type=""text/javascript"">(window.StackifySettings || (window.StackifySettings = {0}))</script><script src=""{1}"" data-key=""{2}"" async></script>",
settings.ToString(Formatting.None), rumScriptUrl, rumKey);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StackifyLib.Utils;
namespace StackifyLib.Web
{
public static class RealUserMonitoring
{
public static string GetHeaderScript()
{
var rumScriptUrl = Config.RumScriptUrl;
var rumKey = Config.RumKey;
if (string.IsNullOrWhiteSpace(rumScriptUrl) || string.IsNullOrWhiteSpace(rumKey))
{
// If we don't have a key and url, don't insert the script
return "";
}
var settings = new JObject();
var reqId = HelperFunctions.GetRequestId();
if (reqId != null)
{
settings["ID"] = reqId;
}
var appName = HelperFunctions.GetAppName();
if (!string.IsNullOrWhiteSpace(appName))
{
settings["Name"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(appName));
}
var environment = HelperFunctions.GetAppEnvironment();
if (!string.IsNullOrWhiteSpace(environment))
{
settings["Env"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(environment));
}
var reportingUrl = HelperFunctions.GetReportingUrl();
if (reportingUrl != null)
{
reportingUrl = HelperFunctions.MaskReportingUrl(reportingUrl);
settings["Trans"] = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(reportingUrl));
}
return string.Format(@"<script type=""text/javascript"">(window.StackifySettings || (window.StackifySettings = {0};))</script><script src=""{1}"" data-key=""{2}"" async></script>",
settings.ToString(Formatting.None), rumScriptUrl, rumKey);
}
}
}
| apache-2.0 | C# |
e1eba6820b8409b5b16a6b6e36a2bfe0dc7d4b0c | Update IMongoUnitOfWork.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/Mongo/IMongoUnitOfWork.cs | TIKSN.Core/Data/Mongo/IMongoUnitOfWork.cs | using System;
namespace TIKSN.Data.Mongo
{
public interface IMongoUnitOfWork : IUnitOfWork
{
public IServiceProvider Services { get; }
}
}
| using System;
namespace TIKSN.Data.Mongo
{
public interface IMongoUnitOfWork : IUnitOfWork
{
public IServiceProvider Services { get; }
}
} | mit | C# |
365502a6878cd270efd1236240a4f8dcc5504efc | Change ctor parameter to byte array | mstrother/BmpListener | BmpListener/Bgp/IPAddrPrefix.cs | BmpListener/Bgp/IPAddrPrefix.cs | using System;
using System.Net;
namespace BmpListener.Bgp
{
public class IPAddrPrefix
{
public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP)
{
DecodeFromBytes(data, afi);
}
public byte Length { get; private set; }
public IPAddress Prefix { get; private set; }
public override string ToString()
{
return ($"{Prefix}/{Length}");
}
public int GetByteLength()
{
return 1 + (Length + 7) / 8;
}
public void DecodeFromBytes(byte[] data, AddressFamily afi)
{
Length = data.ElementAt(0);
if (Length <= 0) return;
var byteLength = (Length + 7) / 8;
var ipBytes = afi == AddressFamily.IP
? new byte[4]
: new byte[16];
Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength);
Prefix = new IPAddress(ipBytes);
}
}
}
| using System;
using System.Linq;
using System.Net;
namespace BmpListener.Bgp
{
public class IPAddrPrefix
{
public IPAddrPrefix(ArraySegment<byte> data, AddressFamily afi = AddressFamily.IP)
{
DecodeFromBytes(data, afi);
}
public byte Length { get; private set; }
public IPAddress Prefix { get; private set; }
public override string ToString()
{
return ($"{Prefix}/{Length}");
}
public int GetByteLength()
{
return 1 + (Length + 7) / 8;
}
public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi)
{
Length = data.ElementAt(0);
if (Length <= 0) return;
var byteLength = (Length + 7) / 8;
var ipBytes = afi == AddressFamily.IP
? new byte[4]
: new byte[16];
Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength);
Prefix = new IPAddress(ipBytes);
}
}
}
| mit | C# |
bb5cee9c4ad9a34400979903c8a6521322fd7b0e | fix input | HydroChlorix/NumberTranslater | ConsoleApplication/ConsoleTranslater/Program.cs | ConsoleApplication/ConsoleTranslater/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTranslater
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Input number : ");
var input = Console.ReadLine();
decimal number = 0;
if (input == "q" || input == "Q")
{
break;
}
else
{
if (decimal.TryParse(input, out number))
{
Translater ts = new Translater(number);
Console.WriteLine(ts.Translate());
}
else
{
Console.WriteLine("incorrect number input. pleas try again. (Press q to exit.)");
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTranslater
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Input number : ");
var input = Console.ReadLine();
decimal number = 0;
if (input == "q" || input == "Q")
{
break;
}
else
{
if (decimal.TryParse(input, out number))
{
Translater ts = new Translater(decimal.MaxValue);
Console.WriteLine(ts.Translate());
}
else
{
Console.WriteLine("incorrect number input. pleas try again. (Press q to exit.)");
}
}
}
}
}
}
| mit | C# |
f4e837c4c4ca2816cd76ec67d078f26dcd08a0e8 | fix GenderTools | petrovich/petrovich-net | NPetrovich/Utils/GenderUtils.cs | NPetrovich/Utils/GenderUtils.cs | using System.Globalization;
namespace NPetrovich.Utils
{
public static class GenderUtils
{
private const string ExceptionMessage = "You must specify middle name to detect gender";
private const string ParameterName = "middleName";
public static Gender Detect(string middleName)
{
Guard.IfArgumentNullOrWhitespace(middleName, ParameterName, ExceptionMessage);
if (middleName.EndsWith("ич", true, CultureInfo.InvariantCulture))
return Gender.Male;
if (middleName.EndsWith("на", true, CultureInfo.InvariantCulture))
return Gender.Female;
return Gender.Androgynous;
}
public static Gender DetectGender(this Petrovich petrovich)
{
Guard.IfArgumentNullOrWhitespace(petrovich.MiddleName, ParameterName, ExceptionMessage);
return Detect(petrovich.MiddleName);
}
}
}
| using System.Globalization;
namespace NPetrovich.Utils
{
public static class GenderUtils
{
private const string ExceptionMessage = "You must specify middle name to detect gender";
private const string ParameterName = "middleName";
public static Gender Detect(string middleName)
{
Guard.IfArgumentNullOrWhitespace(middleName, ParameterName, ExceptionMessage);
if (middleName.EndsWith("ич", true, CultureInfo.InvariantCulture))
return Gender.Male;
if (middleName.EndsWith("на", true, CultureInfo.InvariantCulture))
return Gender.Female;
return Gender.Androgynous;
}
public static Petrovich DetectGender(this Petrovich petrovich)
{
Guard.IfArgumentNullOrWhitespace(petrovich.MiddleName, ParameterName, ExceptionMessage);
petrovich.Gender = Detect(petrovich.MiddleName);
return petrovich;
}
}
}
| mit | C# |
109cdb5444123d146404539b399497956fcb0416 | Update RuleUpdater.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | ProcessBlockUtil/RuleUpdater.cs | ProcessBlockUtil/RuleUpdater.cs | /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("Process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
Console.WriteLine("Obtaining Paths...");
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete and copy Exist file.
*/
Console.WriteLine("Deleting old file...");
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt");
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
Console.WriteLine("Downloading new rules...");
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Restarting Service....");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
}
}
}
| /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("The process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete and copy Exist file.
*/
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt");
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Restarting Service....");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
}
}
}
| apache-2.0 | C# |
f285467a83145e2253fb019d94118c347376f948 | Test code | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Program.cs | Src/WHampson.Cascara/Program.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using WHampson.Cascara.Types;
namespace WHampson.Cascara
{
class Program
{
static void Main(string[] args)
{
//IntPtr ptr = Marshal.AllocHGlobal(64);
//Marshal.Copy(new byte[] { 0x00, 0x00, 0xFF, 0x7F }, 0, ptr, 4);
//unsafe
//{
// CascaraBool8* b8 = (CascaraBool8*) ptr;
// CascaraBool16* b16 = (CascaraBool16*) ptr + 2;
// CascaraBool32* b32 = (CascaraBool32*) ptr;
// Console.WriteLine(*b8);
// Console.WriteLine(*b16);
// Console.WriteLine(*b32);
//}
//Marshal.FreeHGlobal(ptr);
TemplateFile tf = new TemplateFile("../../../../Test/DynamicArray.xml");
tf.Process<object>("../../../../Test/DynamicArray.bin");
// Pause
Console.ReadKey();
}
}
}
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using WHampson.Cascara.Types;
using Int32 = WHampson.Cascara.Types.Int32;
namespace WHampson.Cascara
{
public class Vect3D
{
public Pointer<Float> X { get; set; }
public Pointer<Float> Y { get; set; }
public Pointer<Float> Z { get; set; }
public override string ToString()
{
return "{ " + string.Format("X: {0}, Y: {1}, Z: {2}", X[0], Y[0], Z[0]) + " }";
}
}
public class PlayerInfo
{
public Vect3D Location { get; set; }
public Pointer<Int32> Money { get; set; }
public Pointer<Int32> NumKills { get; set; }
public Pointer<Int8> Health { get; set; }
public Pointer<Int8> Armor { get; set; }
public Vect3D Location2 { get; set; }
}
public class TestClass
{
public PlayerInfo PLYR { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Read template and map to object instance
TemplateFile template = new TemplateFile("../../../../Test/DynamicArray.xml");
TestClass test = template.Process<TestClass>("../../../../Test/DynamicArray.bin");
//Console.WriteLine(test.PLYR.Location);
//Console.WriteLine(test.PLYR.Money.Value);
//Console.WriteLine(test.PLYR.NumKills.Value);
//Console.WriteLine(test.PLYR.Health.Value);
//Console.WriteLine(test.PLYR.Armor.Value);
//Console.WriteLine(test.PLYR.Location2);
// Pause
Console.ReadKey();
}
}
}
| mit | C# |
dd39b563cff5100032337af4beb052e2b89ffa98 | Fix formatting | jcmoyer/Yeena | Yeena/PathOfExile/PoEItemMod.cs | Yeena/PathOfExile/PoEItemMod.cs | // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
class PoEItemMod {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("level")]
private readonly int _level;
[JsonProperty("effects")]
private readonly List<PoEItemModStat> _effects;
public string Name { get { return _name; } }
public int Level { get { return _level; } }
public IReadOnlyList<PoEItemModStat> Effects { get { return _effects; } }
[JsonConstructor]
private PoEItemMod() {
}
public PoEItemMod(string name, int level, IEnumerable<PoEItemModStat> stats) {
_name = name;
_level = level;
_effects = stats.ToList();
}
public override string ToString() {
return Name;
}
}
}
| // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
class PoEItemMod {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("level")]
private readonly int _level;
[JsonProperty("effects")]
private readonly List<PoEItemModStat> _effects;
public string Name { get { return _name; } }
public int Level { get { return _level; } }
public IReadOnlyList<PoEItemModStat> Effects {get { return _effects; }}
[JsonConstructor]
private PoEItemMod() {
}
public PoEItemMod(string name, int level, IEnumerable<PoEItemModStat> stats) {
_name = name;
_level = level;
_effects = stats.ToList();
}
public override string ToString() {
return Name;
}
}
}
| apache-2.0 | C# |
ef15ab07dc4cdd3697fb1db5c46751273a25c911 | add range & angle increment | adamabdelhamed/PowerArgs,workabyte/PowerArgs,adamabdelhamed/PowerArgs,workabyte/PowerArgs | PowerArgs/CLI/Games/Weapons/SmartMineDropper.cs | PowerArgs/CLI/Games/Weapons/SmartMineDropper.cs | using PowerArgs.Cli.Physics;
namespace PowerArgs.Games
{
public class SmartMineDropper : Weapon
{
public float Range { get; set; } = 10;
public float AngleIncrement { get; set; } = 30;
public override WeaponStyle Style => WeaponStyle.Explosive;
public string TargetTag { get; set; } = "enemy";
public float Speed { get; set; } = 50;
public override void FireInternal(bool alt)
{
var mine = new ProximityMine(this) { TargetTag = TargetTag, Range = Range, AngleIncrement = AngleIncrement };
mine.SetProperty(nameof(Holder), this.Holder);
ProximityMineDropper.PlaceMineSafe(mine, Holder, !alt, Speed);
SpaceTime.CurrentSpaceTime.Add(mine);
OnWeaponElementEmitted.Fire(mine);
}
}
}
| using PowerArgs.Cli.Physics;
namespace PowerArgs.Games
{
public class SmartMineDropper : Weapon
{
public override WeaponStyle Style => WeaponStyle.Explosive;
public string TargetTag { get; set; } = "enemy";
public float Speed { get; set; } = 50;
public override void FireInternal(bool alt)
{
var mine = new ProximityMine(this) { TargetTag = TargetTag };
mine.SetProperty(nameof(Holder), this.Holder);
ProximityMineDropper.PlaceMineSafe(mine, Holder, !alt, Speed);
SpaceTime.CurrentSpaceTime.Add(mine);
OnWeaponElementEmitted.Fire(mine);
}
}
}
| mit | C# |
b8edb0e6ce60492a0b3fd12e5de7a84571b0ed93 | Change version to 1.0.0.0 | PierrickI3/ScreenRecordingAddin | ScreenRecordingAddin/Properties/AssemblyInfo.cs | ScreenRecordingAddin/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.
using ININ.InteractionClient.AddIn;
[assembly: AssemblyTitle("Screen Recording Addin")]
[assembly: AssemblyDescription("This Add-in initiates a screen recording when generic objects are picked up by the agent")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Interactive Intelligence, Inc.")]
[assembly: AssemblyProduct("ScreenRecordingAddin")]
[assembly: AssemblyCopyright("Copyright © Interactive Intelligence, Inc. 2016")]
[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("bc2afa1a-a3ef-4b88-b0ab-2c0521295fb6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AddInVersion(AddInVersion.CurrentVersion)] | 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.
using ININ.InteractionClient.AddIn;
[assembly: AssemblyTitle("Screen Recording Addin")]
[assembly: AssemblyDescription("This Add-in initiates a screen recording when generic objects are picked up by the agent")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Interactive Intelligence, Inc.")]
[assembly: AssemblyProduct("ScreenRecordingAddin")]
[assembly: AssemblyCopyright("Copyright © Interactive Intelligence, Inc. 2016")]
[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("bc2afa1a-a3ef-4b88-b0ab-2c0521295fb6")]
// 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.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AddInVersion(AddInVersion.CurrentVersion)] | apache-2.0 | C# |
dea9c720b4e19f55f7aa4c969bec62ea6415d79b | Update InternetConnectivityState.cs | tiksn/TIKSN-Framework | TIKSN.Core/Network/InternetConnectivityState.cs | TIKSN.Core/Network/InternetConnectivityState.cs | using System;
using System.Collections.Generic;
namespace TIKSN.Network
{
public class InternetConnectivityState : IEqualityComparer<InternetConnectivityState>,
IEquatable<InternetConnectivityState>
{
public InternetConnectivityState(bool isInternetAvailable, bool isWiFiAvailable,
bool isCellularNetworkAvailable)
{
this.IsInternetAvailable = isInternetAvailable;
this.IsWiFiAvailable = isWiFiAvailable;
this.IsCellularNetworkAvailable = isCellularNetworkAvailable;
}
public bool IsCellularNetworkAvailable { get; }
public bool IsInternetAvailable { get; }
public bool IsWiFiAvailable { get; }
public bool Equals(InternetConnectivityState x, InternetConnectivityState y) =>
x is null ? y is null : x.Equals(y);
public int GetHashCode(InternetConnectivityState obj) => this.IsInternetAvailable.GetHashCode() ^
this.IsWiFiAvailable.GetHashCode() ^
this.IsCellularNetworkAvailable.GetHashCode();
public bool Equals(InternetConnectivityState other)
{
if (other is null)
{
return false;
}
return this.IsInternetAvailable == other.IsInternetAvailable &&
this.IsWiFiAvailable == other.IsWiFiAvailable &&
this.IsCellularNetworkAvailable == other.IsCellularNetworkAvailable;
}
public override bool Equals(object obj) => this.Equals(obj as InternetConnectivityState);
public override int GetHashCode() => throw new NotImplementedException();
}
}
| using System;
using System.Collections.Generic;
namespace TIKSN.Network
{
public class InternetConnectivityState : IEqualityComparer<InternetConnectivityState>,
IEquatable<InternetConnectivityState>
{
public InternetConnectivityState(bool isInternetAvailable, bool isWiFiAvailable,
bool isCellularNetworkAvailable)
{
this.IsInternetAvailable = isInternetAvailable;
this.IsWiFiAvailable = isWiFiAvailable;
this.IsCellularNetworkAvailable = isCellularNetworkAvailable;
}
public bool IsCellularNetworkAvailable { get; }
public bool IsInternetAvailable { get; }
public bool IsWiFiAvailable { get; }
public bool Equals(InternetConnectivityState x, InternetConnectivityState y) =>
ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y);
public int GetHashCode(InternetConnectivityState obj) => this.IsInternetAvailable.GetHashCode() ^
this.IsWiFiAvailable.GetHashCode() ^
this.IsCellularNetworkAvailable.GetHashCode();
public bool Equals(InternetConnectivityState other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return this.IsInternetAvailable == other.IsInternetAvailable &&
this.IsWiFiAvailable == other.IsWiFiAvailable &&
this.IsCellularNetworkAvailable == other.IsCellularNetworkAvailable;
}
}
}
| mit | C# |
98f6ea90f43b7302cc6540982f03a052c6ea8c04 | Make edit profile policy optional | lambdakris/templating,seancpeters/templating,rschiefer/templating,mlorbetske/templating,danroth27/templating,danroth27/templating,danroth27/templating,seancpeters/templating,seancpeters/templating,seancpeters/templating,rschiefer/templating,lambdakris/templating,rschiefer/templating,lambdakris/templating,mlorbetske/templating | template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/Shared/_LoginPartial.cshtml | template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/Shared/_LoginPartial.cshtml | @*#if (IndividualLocalAuth) *@
@using Microsoft.AspNetCore.Identity
@using Company.WebApplication1.Models
@*#else
@*#if (IndividualB2CAuth)
@using Microsoft.Extensions.Options
#endif
@using System.Security.Principal
#endif *@
@*#if (IndividualLocalAuth) *@
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@*#endif *@
@*#if (IndividualB2CAuth)
@inject IOptions<AzureAdB2COptions> AzureAdB2COptions
#endif *@
@*#if (IndividualLocalAuth) *@
@if (SignInManager.IsSignedIn(User))
@*#else
@if (User.Identity.IsAuthenticated)
#endif *@
{
@*#if (IndividualLocalAuth) *@
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
@*#elseif (IndividualB2CAuth)
<ul class="nav navbar-nav navbar-right">
@if (!string.IsNullOrEmpty(AzureAdB2COptions.Value.EditProfilePolicyId))
{
<li><a asp-area="" asp-controller="Account" asp-action="EditProfile">Hello @User.Identity.Name!</a></li>
}
else
{
<li class="navbar-text">Hello @User.Identity.Name!</li>
}
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
#else
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name!</li>
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
#endif *@
}
else
{
<ul class="nav navbar-nav navbar-right">
@*#if (IndividualLocalAuth) *@
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
@*#else
<li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
#endif *@
</ul>
}
| @*#if (IndividualLocalAuth) *@
@using Microsoft.AspNetCore.Identity
@using Company.WebApplication1.Models
@*#else
@using System.Security.Principal
#endif *@
@*#if (IndividualLocalAuth) *@
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@*#endif *@
@*#if (IndividualLocalAuth) *@
@if (SignInManager.IsSignedIn(User))
@*#else
@if (User.Identity.IsAuthenticated)
#endif *@
{
@*#if (IndividualLocalAuth) *@
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
@*#elseif (IndividualB2CAuth)
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="EditProfile">Hello @User.Identity.Name!</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
#else
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name!</li>
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
#endif *@
}
else
{
<ul class="nav navbar-nav navbar-right">
@*#if (IndividualLocalAuth) *@
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
@*#else
<li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
#endif *@
</ul>
}
| mit | C# |
4e90f9d7028974f0b61dff1353894f4963406acf | Update _LoginPartial.cshtml | seancpeters/templating,danroth27/templating,danroth27/templating,lambdakris/templating,rschiefer/templating,danroth27/templating,seancpeters/templating,seancpeters/templating,mlorbetske/templating,rschiefer/templating,lambdakris/templating,seancpeters/templating,mlorbetske/templating,rschiefer/templating,lambdakris/templating | template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/Shared/_LoginPartial.cshtml | template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/StarterWeb-CSharp/Views/Shared/_LoginPartial.cshtml | @*#if (IndividualAuth) *@
@using Microsoft.AspNetCore.Identity
@using Company.WebApplication1.Models
@*#else
@using System.Security.Principal
#endif *@
@*#if (IndividualAuth) *@
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@*#endif *@
@*#if (IndividualAuth) *@
@if (SignInManager.IsSignedIn(User))
@*#else
@if (User.Identity.IsAuthenticated)
#endif *@
{
@*#if (IndividualAuth) *@
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
@*#else
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name!</li>
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
</ul>
#endif *@
}
else
{
<ul class="nav navbar-nav navbar-right">
@*#if (IndividualAuth) *@
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
@*#else
<li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
#endif *@
</ul>
}
| @*#if (IndividualAuth) *@
@using Microsoft.AspNetCore.Identity
@using Company.WebApplication1.Models
@*#else
@using System.Security.Principal
#endif *@
@*#if (IndividualAuth) *@
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@*#endif *@
@*#if (IndividualAuth) *@
@if (SignInManager.IsSignedIn(User))
@*#else
@if (User.Identity.IsAuthenticated)
#endif *@
{
@*#if (IndividualAuth) *@
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
@*#else
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">Hello @User.Identity.Name!</li>
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign Out</a></li>
</ul>
#endif *@
}
else
{
<ul class="nav navbar-nav navbar-right">
@*#if (IndividualAuth) *@
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
@*#else
<li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
#endif *@
</ul>
}
| mit | C# |
ec71d448297599e79eff87a428a65b2680e9da91 | Use current principal if provided for auth | civicsource/http,civicsource/webapi-utils | Core/Link.cs | Core/Link.cs | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Archon.WebApi
{
public abstract class Link
{
public Authorization Authorization { get; set; }
public HttpRequestMessage CreateRequest()
{
var req = CreateRequestInternal();
var authToken = GetAuthToken();
if (authToken != null)
req.Headers.Authorization = authToken.AsHeader();
return req;
}
Authorization GetAuthToken()
{
if (Authorization != null)
return Authorization;
var token = Thread.CurrentPrincipal as AuthToken;
if (token != null)
return Authorization.Bearer(token.Token);
return null;
}
protected abstract HttpRequestMessage CreateRequestInternal();
}
public abstract class Link<TResponse> : Link
{
public Task<TResponse> ParseResponseAsync(HttpResponseMessage response)
{
if (response == null)
throw new ArgumentNullException("response");
return ParseResponseInternal(response);
}
protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response);
}
} | using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Archon.WebApi
{
public abstract class Link
{
public Authorization Authorization { get; set; }
public HttpRequestMessage CreateRequest()
{
var req = CreateRequestInternal();
if (Authorization != null)
req.Headers.Authorization = Authorization.AsHeader();
return req;
}
protected abstract HttpRequestMessage CreateRequestInternal();
}
public abstract class Link<TResponse> : Link
{
public Task<TResponse> ParseResponseAsync(HttpResponseMessage response)
{
if (response == null)
throw new ArgumentNullException("response");
return ParseResponseInternal(response);
}
protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response);
}
} | mit | C# |
702636586a3835f52da712ca0e12cf8cf64cf24c | Fix test | Vector241-Eric/CoypuDemo,Vector241-Eric/CoypuDemo,Vector241-Eric/CoypuDemo | src/FunctionalTests.Web/Tests/CalculatorPageTests.cs | src/FunctionalTests.Web/Tests/CalculatorPageTests.cs | using FunctionalTests.Web.Bases;
using FunctionalTests.Web.Pages;
using NUnit.Framework;
using Should;
namespace FunctionalTests.Web.Tests
{
public class CalculatorPageTests
{
[TestFixture]
public class When_landing_on_the_page : FunctionalTestBase
{
[Test]
public void Should_show_a_zero_value()
{
RunTest(browser =>
{
var page = new CalculatorPage(browser);
page.Visit();
page.GetDisplayValue().ShouldEqual("0");
});
}
}
[TestFixture]
public class When_adding_two_numbers : FunctionalTestBase
{
[Test]
public void Should_display_the_addition_result()
{
RunTest(browser =>
{
var page = new CalculatorPage(browser);
page.Visit();
page.Enter("111");
page.Enter("+");
page.Enter("222");
page.Enter("=");
page.GetDisplayValue().ShouldEqual("333");
});
}
}
}
} | using FunctionalTests.Web.Bases;
using FunctionalTests.Web.Pages;
using NUnit.Framework;
using Should;
namespace FunctionalTests.Web.Tests
{
public class CalculatorPageTests
{
[TestFixture]
public class When_landing_on_the_page : FunctionalTestBase
{
[Test]
public void Should_show_a_zero_value()
{
RunTest(browser =>
{
var page = new CalculatorPage(browser);
page.Visit();
page.GetDisplayValue().ShouldEqual("0");
});
}
}
[TestFixture]
public class When_adding_two_numbers : FunctionalTestBase
{
[Test]
public void Should_display_the_addition_result()
{
RunTest(browser =>
{
var page = new CalculatorPage(browser);
page.Visit();
page.Enter("111");
page.Enter("+");
page.Enter("222");
page.Enter("=");
page.GetDisplayValue().ShouldEqual("3334");
});
}
}
}
} | mit | C# |
9cc72f31a150725eaa1ec72f8464c3bfc40cd02c | Add semver styles | nikeee/HolzShots | src/HolzShots.Core/Net/Custom/SemVersionConverter.cs | src/HolzShots.Core/Net/Custom/SemVersionConverter.cs | using Newtonsoft.Json;
using Semver;
namespace HolzShots.Net.Custom
{
/// <summary>
/// Taken from
/// https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f
/// (https://github.com/maxhauser/semver/issues/21)
/// </summary>
public class SemVersionConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (value == null)
{
writer.WriteNull();
}
else
{
if (!(value is SemVersion))
throw new JsonSerializationException("Expected SemVersion object value");
writer.WriteValue(value.ToString());
}
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.String)
throw new JsonSerializationException($"Unexpected token or value when parsing version. Token: {reader.TokenType}, Value: {reader.Value}");
try
{
var v = reader.Value as string;
return SemVersion.Parse(v, SemVersionStyles.Strict);
}
catch (Exception ex)
{
throw new JsonSerializationException($"Error parsing SemVersion string: {reader.Value}", ex);
}
}
public override bool CanConvert(Type objectType) => objectType == typeof(SemVersion);
}
}
| using Newtonsoft.Json;
using Semver;
namespace HolzShots.Net.Custom
{
/// <summary>
/// Taken from
/// https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f
/// (https://github.com/maxhauser/semver/issues/21)
/// </summary>
public class SemVersionConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (value == null)
{
writer.WriteNull();
}
else
{
if (!(value is SemVersion))
throw new JsonSerializationException("Expected SemVersion object value");
writer.WriteValue(value.ToString());
}
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.String)
throw new JsonSerializationException($"Unexpected token or value when parsing version. Token: {reader.TokenType}, Value: {reader.Value}");
try
{
var v = reader.Value as string;
return SemVersion.Parse(v);
}
catch (Exception ex)
{
throw new JsonSerializationException($"Error parsing SemVersion string: {reader.Value}", ex);
}
}
public override bool CanConvert(Type objectType) => objectType == typeof(SemVersion);
}
}
| agpl-3.0 | C# |
114defcc13a960c8aed446c4510d35686d4be058 | Print milliseconds | xPaw/adventofcode-solutions,xPaw/adventofcode-solutions,xPaw/adventofcode-solutions | 2021/Program.cs | 2021/Program.cs | using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using AdventOfCode2021;
Console.OutputEncoding = Encoding.UTF8;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
var day = DateTime.Today.Day;
var runs = 1;
if (args.Length > 0)
{
if (!int.TryParse(args[0], out day))
{
Console.Error.WriteLine("Usage: [day [runs]]");
return 1;
}
if (args.Length > 1)
{
if (!int.TryParse(args[1], out runs))
{
Console.Error.WriteLine("Usage: <day> [runs]");
return 1;
}
}
}
string part1 = string.Empty;
string part2 = string.Empty;
var data = await File.ReadAllTextAsync($"Data/day{day}.txt");
var type = GetSolutionType(day);
var stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < runs; i++)
{
var solution = (IAnswer)Activator.CreateInstance(type)!;
(part1, part2) = solution.Solve(data);
}
stopWatch.Stop();
Console.Write("Part 1: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(part1);
Console.ResetColor();
Console.Write("Part 2: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(part2);
Console.ResetColor();
Console.Write("Time : ");
if (runs > 1)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds / runs);
Console.ResetColor();
Console.Write("ms average for ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(runs);
Console.ResetColor();
Console.WriteLine(" runs");
}
else
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("{0:N6}", stopWatch.Elapsed.TotalMilliseconds);
Console.ResetColor();
Console.Write("ms for a single run");
}
return 0;
static Type GetSolutionType(int day)
{
foreach (Type type in typeof(AnswerAttribute).Assembly.GetTypes())
{
if (!typeof(IAnswer).IsAssignableFrom(type))
{
continue;
}
var attributes = type.GetCustomAttributes(typeof(AnswerAttribute), true);
foreach (AnswerAttribute attribute in attributes)
{
if (attribute.Day == day)
{
return type;
}
}
}
throw new Exception($"Unable to find solution for day {day}");
}
| using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using AdventOfCode2021;
Console.OutputEncoding = Encoding.UTF8;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
var day = DateTime.Today.Day;
var runs = 1;
if (args.Length > 0)
{
if (!int.TryParse(args[0], out day))
{
Console.Error.WriteLine("Usage: [day [runs]]");
return 1;
}
if (args.Length > 1)
{
if (!int.TryParse(args[1], out runs))
{
Console.Error.WriteLine("Usage: <day> [runs]");
return 1;
}
}
}
string part1 = string.Empty;
string part2 = string.Empty;
var data = await File.ReadAllTextAsync($"Data/day{day}.txt");
var type = GetSolutionType(day);
var stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < runs; i++)
{
var solution = (IAnswer)Activator.CreateInstance(type)!;
(part1, part2) = solution.Solve(data);
}
stopWatch.Stop();
Console.Write("Part 1: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(part1);
Console.ResetColor();
Console.Write("Part 2: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(part2);
Console.ResetColor();
Console.Write("Time : ");
if (runs > 1)
{
var average = new TimeSpan(stopWatch.Elapsed.Ticks / runs);
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(average.Duration());
Console.ResetColor();
Console.Write(" average for ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(runs);
Console.ResetColor();
Console.WriteLine(" runs");
}
else
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(stopWatch.Elapsed.Duration());
Console.ResetColor();
}
return 0;
static Type GetSolutionType(int day)
{
foreach (Type type in typeof(AnswerAttribute).Assembly.GetTypes())
{
if (!typeof(IAnswer).IsAssignableFrom(type))
{
continue;
}
var attributes = type.GetCustomAttributes(typeof(AnswerAttribute), true);
foreach (AnswerAttribute attribute in attributes)
{
if (attribute.Day == day)
{
return type;
}
}
}
throw new Exception($"Unable to find solution for day {day}");
}
| unlicense | C# |
7d2ce35646db5f13a89881332b660a240da8b8ef | fix button toggle base. | Amarcolina/LeapMotionCoreAssets,ryanwang/LeapMotionCoreAssets | Assets/LeapMotion/Widgets/Scripts/Button/ButtonToggleBase.cs | Assets/LeapMotion/Widgets/Scripts/Button/ButtonToggleBase.cs | using UnityEngine;
using System.Collections;
namespace LMWidgets
{
public abstract class ButtonToggleBase : ButtonBase, BinaryInteractionHandler<bool>, IDataBoundWidget<ButtonToggleBase, bool> {
protected DataBinderToggle m_dataBinder;
protected bool m_toggleState = true;
public abstract void ButtonTurnsOn();
public abstract void ButtonTurnsOff();
/// <summary>
/// Gets or sets the current state of the toggle button.
/// </summary>
public bool ToggleState {
get { return m_toggleState; }
set {
if ( m_toggleState == value ) { return; }
setButtonState(value);
if ( m_dataBinder != null ) { m_dataBinder.SetCurrentData(m_toggleState); } // Update externally linked data
}
}
protected override void Start() {
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData(), true); // Initilize widget value
}
else {
setButtonState(false, true);
}
}
public void SetWidgetValue(bool value) {
if ( State == LeapPhysicsState.Interacting ) { return; } // Don't worry about state changes during interaction.
setButtonState (value);
}
// Stop listening to any previous data binder and start listening to the new one.
public void RegisterDataBinder(LMWidgets.DataBinder<LMWidgets.ButtonToggleBase, bool> dataBinder) {
if (dataBinder == null) {
return;
}
UnregisterDataBinder ();
m_dataBinder = dataBinder as DataBinderToggle;
setButtonState(m_dataBinder.GetCurrentData());
}
// Stop listening to any previous data binder.
public void UnregisterDataBinder() {
m_dataBinder = null;
}
private void setButtonState(bool toggleState, bool force = false) {
if ( toggleState == m_toggleState && !force ) { return; } // Don't do anything if there's no change
m_toggleState = toggleState;
if (m_toggleState == true)
ButtonTurnsOn();
else
ButtonTurnsOff();
}
protected override void buttonReleased()
{
base.FireButtonEnd(m_toggleState);
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData()); // Update once we're done interacting
}
}
protected override void buttonPressed()
{
if (m_toggleState == false)
ButtonTurnsOn();
else
ButtonTurnsOff();
ToggleState = !ToggleState;
base.FireButtonStart(m_toggleState);
}
}
}
| using UnityEngine;
using System.Collections;
namespace LMWidgets
{
public abstract class ButtonToggleBase : ButtonBase, BinaryInteractionHandler<bool>, IDataBoundWidget<ButtonToggleBase, bool> {
protected DataBinderToggle m_dataBinder;
protected bool m_toggleState = true;
public abstract void ButtonTurnsOn();
public abstract void ButtonTurnsOff();
/// <summary>
/// Gets or sets the current state of the toggle button.
/// </summary>
public bool ToggleState {
get { return m_toggleState; }
set {
if ( m_toggleState == value ) { return; }
setButtonState(value);
}
}
protected override void Start() {
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData(), true); // Initilize widget value
}
else {
setButtonState(false, true);
}
}
public void SetWidgetValue(bool value) {
if ( State == LeapPhysicsState.Interacting ) { return; } // Don't worry about state changes during interaction.
setButtonState (value);
}
// Stop listening to any previous data binder and start listening to the new one.
public void RegisterDataBinder(LMWidgets.DataBinder<LMWidgets.ButtonToggleBase, bool> dataBinder) {
if (dataBinder == null) {
return;
}
UnregisterDataBinder ();
m_dataBinder = dataBinder as DataBinderToggle;
setButtonState(m_dataBinder.GetCurrentData());
}
// Stop listening to any previous data binder.
public void UnregisterDataBinder() {
m_dataBinder = null;
}
private void setButtonState(bool toggleState, bool force = false) {
if ( toggleState == m_toggleState && !force ) { return; } // Don't do anything if there's no change
m_toggleState = toggleState;
if (m_toggleState == true)
ButtonTurnsOn();
else
ButtonTurnsOff();
}
protected override void buttonReleased()
{
base.FireButtonEnd(m_toggleState);
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData()); // Update once we're done interacting
}
}
protected override void buttonPressed()
{
if (m_toggleState == false)
ButtonTurnsOn();
else
ButtonTurnsOff();
ToggleState = !ToggleState;
base.FireButtonStart(m_toggleState);
}
}
}
| apache-2.0 | C# |
f7c8fefb2de39a7fe5a84c3f98e3fa38f353b288 | Update UnprotectProtectSheet.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Worksheets/Security/Unprotect/UnprotectProtectSheet.cs | Examples/CSharp/Worksheets/Security/Unprotect/UnprotectProtectSheet.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security.Unprotect
{
public class UnprotectingProtectedWorksheet
{
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);
//Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Unprotecting the worksheet with a password
worksheet.Unprotect("aspose");
//Save Workbook
workbook.Save(dataDir + "output.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security.Unprotect
{
public class UnprotectingProtectedWorksheet
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Unprotecting the worksheet with a password
worksheet.Unprotect("aspose");
//Save Workbook
workbook.Save(dataDir + "output.out.xls");
}
}
} | mit | C# |
485d67f42086413dab66947789451cde25edd1ec | update UrlGenarator | csyntax/BlogSystem | Source/BlogSystem.Web.Infrastructure/Helpers/UrlGenerator.cs | Source/BlogSystem.Web.Infrastructure/Helpers/UrlGenerator.cs | namespace BlogSystem.Web.Infrastructure.Helpers
{
using System.Text;
public class UrlGenerator : IUrlGenerator
{
public string GenerateUrl(string uglyString)
{
var resultString = new StringBuilder(uglyString.Length);
var isLastCharacterDash = false;
uglyString = uglyString.Replace("C#", "CSharp");
uglyString = uglyString.Replace("F#", "FSharp");
uglyString = uglyString.Replace("C++", "CPlusPlus");
uglyString = uglyString.Replace("ASP.NET", "AspNet");
uglyString = uglyString.Replace(".NET", "DotNet");
foreach (char character in uglyString)
{
if (char.IsLetterOrDigit(character))
{
resultString.Append(character);
isLastCharacterDash = false;
}
else if (!isLastCharacterDash)
{
resultString.Append('-');
isLastCharacterDash = true;
}
}
return resultString.ToString().Trim('-');
}
}
} | namespace BlogSystem.Web.Infrastructure.Helpers
{
using System.Text;
public class UrlGenerator : IUrlGenerator
{
public string GenerateUrl(string uglyString)
{
StringBuilder resultString = new StringBuilder(uglyString.Length);
bool isLastCharacterDash = false;
uglyString = uglyString.Replace("C#", "CSharp");
uglyString = uglyString.Replace("F#", "FSharp");
uglyString = uglyString.Replace("C++", "CPlusPlus");
uglyString = uglyString.Replace("ASP.NET", "AspNet");
uglyString = uglyString.Replace(".NET", "DotNet");
foreach (char character in uglyString)
{
if (char.IsLetterOrDigit(character))
{
resultString.Append(character);
isLastCharacterDash = false;
}
else if (!isLastCharacterDash)
{
resultString.Append('-');
isLastCharacterDash = true;
}
}
return resultString.ToString().Trim('-');
}
}
} | mit | C# |
0de606b995353ebf215db6ef785648db4096b8ff | Fix failing tests. | SuperJMN/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia | tests/Avalonia.Controls.UnitTests/ImageTests.cs | tests/Avalonia.Controls.UnitTests/ImageTests.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Moq;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ImageTests
{
[Fact]
public void Measure_Should_Return_Correct_Size_For_No_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.PixelSize == new PixelSize(50, 100));
var target = new Image();
target.Stretch = Stretch.None;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_Fill_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.PixelSize == new PixelSize(50, 100));
var target = new Image();
target.Stretch = Stretch.Fill;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_Uniform_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.PixelSize == new PixelSize(50, 100));
var target = new Image();
target.Stretch = Stretch.Uniform;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(25, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_UniformToFill_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.PixelSize == new PixelSize(50, 100));
var target = new Image();
target.Stretch = Stretch.UniformToFill;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Moq;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ImageTests
{
[Fact]
public void Measure_Should_Return_Correct_Size_For_No_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.Size == new Size(50, 100));
var target = new Image();
target.Stretch = Stretch.None;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_Fill_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.Size == new Size(50, 100));
var target = new Image();
target.Stretch = Stretch.Fill;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_Uniform_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.Size == new Size(50, 100));
var target = new Image();
target.Stretch = Stretch.Uniform;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(25, 50), target.DesiredSize);
}
[Fact]
public void Measure_Should_Return_Correct_Size_For_UniformToFill_Stretch()
{
var bitmap = Mock.Of<IBitmap>(x => x.Size == new Size(50, 100));
var target = new Image();
target.Stretch = Stretch.UniformToFill;
target.Source = bitmap;
target.Measure(new Size(50, 50));
Assert.Equal(new Size(50, 50), target.DesiredSize);
}
}
}
| mit | C# |
4a89d93bffed06b50510c4beef2d6c98d277543b | Add non generic IService interface | peasy/Peasy.NET,ahanusa/Peasy.NET,ahanusa/facile.net | Peasy/IService.cs | Peasy/IService.cs | using System.Collections.Generic;
namespace Peasy
{
public interface IService
{
}
public interface IService<T, TKey> : ISupportGetAllCommand<T>,
ISupportGetByIDCommand<T, TKey>,
ISupportInsertCommand<T>,
ISupportUpdateCommand<T>,
ISupportDeleteCommand<TKey>
{
}
public interface ISupportGetAllCommand<T> : IService
{
ICommand<IEnumerable<T>> GetAllCommand();
}
public interface ISupportGetByIDCommand<T, TKey> : IService
{
ICommand<T> GetByIDCommand(TKey id);
}
public interface ISupportInsertCommand<T> : IService
{
ICommand<T> InsertCommand(T entity);
}
public interface ISupportUpdateCommand<T> : IService
{
ICommand<T> UpdateCommand(T entity);
}
public interface ISupportDeleteCommand<TKey> : IService
{
ICommand DeleteCommand(TKey id);
}
}
| using System.Collections.Generic;
namespace Peasy
{
public interface IService<T, TKey> : ISupportGetAllCommand<T>,
ISupportGetByIDCommand<T, TKey>,
ISupportInsertCommand<T>,
ISupportUpdateCommand<T>,
ISupportDeleteCommand<TKey>
{
}
public interface ISupportGetAllCommand<T>
{
ICommand<IEnumerable<T>> GetAllCommand();
}
public interface ISupportGetByIDCommand<T, TKey>
{
ICommand<T> GetByIDCommand(TKey id);
}
public interface ISupportInsertCommand<T>
{
ICommand<T> InsertCommand(T entity);
}
public interface ISupportUpdateCommand<T>
{
ICommand<T> UpdateCommand(T entity);
}
public interface ISupportDeleteCommand<TKey>
{
ICommand DeleteCommand(TKey id);
}
}
| mit | C# |
529f97992ef8a29f48f8f9960e3dc071c16d28c6 | remove bugsnag api key entries | peeedge/mobile,eatskolnikov/mobile,peeedge/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile,eatskolnikov/mobile,masterrr/mobile,eatskolnikov/mobile,masterrr/mobile | Phoebe/Build.cs | Phoebe/Build.cs | using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string XamInsightsApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string GoogleOAuthClientId = "";
public static readonly string XamInsightsApiKey = "";
#endif
#endregion
}
} | using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string BugsnagApiKey = "";
public static readonly string XamInsightsApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string BugsnagApiKey = "";
public static readonly string GoogleOAuthClientId = "";
public static readonly string XamInsightsApiKey = "";
#endif
#endregion
}
} | bsd-3-clause | C# |
800c18bcc20d2281314e54c876fb0d663e7bb4e2 | Update Bootstrap package in v5 test pages to v5.2.2 | atata-framework/atata-bootstrap,atata-framework/atata-bootstrap | test/Atata.Bootstrap.TestApp/Pages/v5/_Layout.cshtml | test/Atata.Bootstrap.TestApp/Pages/v5/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
@RenderSection("styles", false)
</head>
<body>
<div class="container">
<h1 class="text-center">@ViewBag.Title</h1>
@RenderBody()
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
@RenderSection("scripts", false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
@RenderSection("styles", false)
</head>
<body>
<div class="container">
<h1 class="text-center">@ViewBag.Title</h1>
@RenderBody()
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
@RenderSection("scripts", false)
</body>
</html>
| apache-2.0 | C# |
2176af7edd14d5797358091725b3e0da637c72a0 | Add IHttpMaxRequestBodySizeFeature.IsReadOnly (#858) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Http.Features/IHttpMaxRequestBodySizeFeature.cs | src/Microsoft.AspNetCore.Http.Features/IHttpMaxRequestBodySizeFeature.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Http.Features
{
/// <summary>
/// Feature to inspect and modify the maximum request body size for a single request.
/// </summary>
public interface IHttpMaxRequestBodySizeFeature
{
/// <summary>
/// Indicates whether <see cref="MaxRequestBodySize"/> is read-only.
/// If true, this could mean that the request body has already been read from
/// or that <see cref="IHttpUpgradeFeature.UpgradeAsync"/> was called.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// The maximum allowed size of the current request body in bytes.
/// When set to null, the maximum request body size is unlimited.
/// This cannot be modified after the reading the request body has started.
/// This limit does not affect upgraded connections which are always unlimited.
/// </summary>
/// <remarks>
/// Defaults to the server's global max request body size limit.
/// </remarks>
long? MaxRequestBodySize { get; set; }
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Http.Features
{
/// <summary>
/// Feature to inspect and modify the maximum request body size for a single request.
/// </summary>
public interface IHttpMaxRequestBodySizeFeature
{
/// <summary>
/// The maximum allowed size of the current request body in bytes.
/// When set to null, the maximum request body size is unlimited.
/// This cannot be modified after the reading the request body has started.
/// This limit does not affect upgraded connections which are always unlimited.
/// </summary>
/// <remarks>
/// Defaults to the server's global max request body size limit.
/// </remarks>
long? MaxRequestBodySize { get; set; }
}
} | apache-2.0 | C# |
37d40a3cf6ee7e9cd3d57b9cc0a96045664d29ba | Add notes, remove duplicate call | NickCraver/StackExchange.Exceptional,NickCraver/StackExchange.Exceptional | src/StackExchange.Exceptional.AspNetCore/ExceptionalServiceExtensions.cs | src/StackExchange.Exceptional.AspNetCore/ExceptionalServiceExtensions.cs | using Microsoft.Extensions.Configuration;
using StackExchange.Exceptional;
using System;
using Microsoft.AspNetCore.Hosting;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for configuring Exceptional for MVC.
/// </summary>
public static class ExceptionalServiceExtensions
{
/// <summary>
/// Adds Exceptional configuration for logging errors.
/// </summary>
/// <param name="services">The services collection to configure.</param>
/// <param name="config">The config to bind to, e.g. Config.GetSection("Exceptional")</param>
/// <param name="configureSettings">An <see cref="Action{ExceptionalSettings}"/> to configure options for Exceptional.</param>
public static IServiceCollection AddExceptional(this IServiceCollection services, IConfiguration config, Action<ExceptionalSettings> configureSettings = null)
{
services.Configure<ExceptionalSettings>(config.Bind); // Custom extension
return AddExceptional(services, configureSettings);
}
/// <summary>
/// Adds Exceptional configuration for logging errors.
/// </summary>
/// <param name="services">The services collection to configure.</param>
/// <param name="configureSettings">An <see cref="Action{ExceptionalSettings}"/> to configure options for Exceptional.</param>
public static IServiceCollection AddExceptional(this IServiceCollection services, Action<ExceptionalSettings> configureSettings = null)
{
if (configureSettings != null)
{
services.Configure(configureSettings);
}
// When done configuring, set the background settings object for non-context logging.
services.Configure<ExceptionalSettings>(Exceptional.Configure);
services.AddTransient<IStartupFilter, ExceptionalStartupFilter>(); // Note: transient is how all framework IStartupFilters are registered
return services;
}
}
}
| using Microsoft.Extensions.Configuration;
using StackExchange.Exceptional;
using System;
using Microsoft.AspNetCore.Hosting;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for configuring Exceptional for MVC.
/// </summary>
public static class ExceptionalServiceExtensions
{
/// <summary>
/// Adds Exceptional configuration for logging errors.
/// </summary>
/// <param name="services">The services collection to configure.</param>
/// <param name="config">The config to bind to, e.g. Config.GetSection("Exceptional")</param>
/// <param name="configureSettings">An <see cref="Action{ExceptionalSettings}"/> to configure options for Exceptional.</param>
public static IServiceCollection AddExceptional(this IServiceCollection services, IConfiguration config, Action<ExceptionalSettings> configureSettings = null)
{
services.Configure<ExceptionalSettings>(config.Bind); // Custom extension
services.AddTransient<IStartupFilter, ExceptionalStartupFilter>();
return AddExceptional(services, configureSettings);
}
/// <summary>
/// Adds Exceptional configuration for logging errors.
/// </summary>
/// <param name="services">The services collection to configure.</param>
/// <param name="configureSettings">An <see cref="Action{ExceptionalSettings}"/> to configure options for Exceptional.</param>
public static IServiceCollection AddExceptional(this IServiceCollection services, Action<ExceptionalSettings> configureSettings = null)
{
if (configureSettings != null)
{
services.Configure(configureSettings);
}
// When done configuring, set the background settings object for non-context logging.
services.Configure<ExceptionalSettings>(Exceptional.Configure);
services.AddTransient<IStartupFilter, ExceptionalStartupFilter>();
return services;
}
}
}
| apache-2.0 | C# |
fc9a96602f4c54a57aa2789848d7702c40fd2cf6 | add new value based on additional tests | AerisG222/NExifTool | src/NExifTool/Enums/GainControl.cs | src/NExifTool/Enums/GainControl.cs | using System;
namespace NExifTool.Enums
{
public class GainControl
: TagEnum<ushort>
{
public static readonly GainControl None = new GainControl(0, "None");
public static readonly GainControl LowGainUp = new GainControl(1, "Low gain up");
public static readonly GainControl HighGainUp = new GainControl(2, "High gain up");
public static readonly GainControl LowGainDown = new GainControl(3, "Low gain down");
public static readonly GainControl HighGainDown = new GainControl(4, "High gain down");
public static readonly GainControl Unknown = new GainControl(256, "Unknown");
public GainControl(ushort key, string description)
: base(key, description)
{
}
public static GainControl FromKey(ushort key)
{
switch(key)
{
case 0: return None;
case 1: return LowGainUp;
case 2: return HighGainUp;
case 3: return LowGainDown;
case 4: return HighGainDown;
case 256: return Unknown;
}
throw new ArgumentOutOfRangeException(nameof(key));
}
}
}
| using System;
namespace NExifTool.Enums
{
public class GainControl
: TagEnum<ushort>
{
public static readonly GainControl None = new GainControl(0, "None");
public static readonly GainControl LowGainUp = new GainControl(1, "Low gain up");
public static readonly GainControl HighGainUp = new GainControl(2, "High gain up");
public static readonly GainControl LowGainDown = new GainControl(3, "Low gain down");
public static readonly GainControl HighGainDown = new GainControl(4, "High gain down");
public GainControl(ushort key, string description)
: base(key, description)
{
}
public static GainControl FromKey(ushort key)
{
switch(key)
{
case 0: return None;
case 1: return LowGainUp;
case 2: return HighGainUp;
case 3: return LowGainDown;
case 4: return HighGainDown;
}
throw new ArgumentOutOfRangeException(nameof(key));
}
}
}
| mit | C# |
3015bc31de8bf90a4b7f10ea1a50632125e55672 | Fix typo on IRenderProcessMessageHandler.OnContextCreated | jamespearce2006/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,Livit/CefSharp | CefSharp/Handler/IRenderProcessMessageHandler.cs | CefSharp/Handler/IRenderProcessMessageHandler.cs | // Copyright © 2010-2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
/// <summary>
/// Messages sent by the render process can be handled by implementing this
/// interface.
/// </summary>
public interface IRenderProcessMessageHandler
{
/// <summary>
/// OnContextCreated is called in the Render process immediately after a CefV8Context is created.
/// An IPC message is immediately sent to notify the context has been created
/// (should be safe to execute javascript). If the page has no javascript then no V8Context will be created
/// and as a result this method will not be called. Currently only called for the Main frame <see cref="IFrame.IsMain"/>
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame.</param>
void OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame);
/// <summary>
/// OnContextReleased is called in the Render process immediately before the CefV8Context is released.
/// An IPC message is immediately sent to notify the context has been released
/// (cannot execute javascript this point). If the page had no javascript then the context would not have been created
/// and as a result this method will not be called. Currently only called for the Main frame <see cref="IFrame.IsMain"/>
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame.</param>
void OnContextReleased(IWebBrowser browserControl, IBrowser browser, IFrame frame);
/// <summary>
/// Invoked when an element in the UI gains focus (or possibly no
/// element gains focus; i.e. an element lost focus).
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame object</param>
/// <param name="node">An object with information about the node (if any) that has focus.</param>
void OnFocusedNodeChanged(IWebBrowser browserControl, IBrowser browser, IFrame frame, IDomNode node);
}
}
| // Copyright © 2010-2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
/// <summary>
/// Messages sent by the render process can be handled by implementing this
/// interface.
/// </summary>
public interface IRenderProcessMessageHandler
{
/// <summary>
/// OnContextCreated is called in the Render process immediately after a CefV8Context is created.
/// An IPC message is immediately sent to notify the context has been created
/// (should be safe to execute javascript). If the page has no javascript then on context will be created
/// and as a result this method will not be called. Currently only called for the Main frame <see cref="IFrame.IsMain"/>
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame.</param>
void OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame);
/// <summary>
/// OnContextReleased is called in the Render process immediately before the CefV8Context is released.
/// An IPC message is immediately sent to notify the context has been released
/// (cannot execute javascript this point). If the page had no javascript then the context would not have been created
/// and as a result this method will not be called. Currently only called for the Main frame <see cref="IFrame.IsMain"/>
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame.</param>
void OnContextReleased(IWebBrowser browserControl, IBrowser browser, IFrame frame);
/// <summary>
/// Invoked when an element in the UI gains focus (or possibly no
/// element gains focus; i.e. an element lost focus).
/// </summary>
/// <param name="browserControl">The ChromiumWebBrowser control</param>
/// <param name="browser">the browser object</param>
/// <param name="frame">The frame object</param>
/// <param name="node">An object with information about the node (if any) that has focus.</param>
void OnFocusedNodeChanged(IWebBrowser browserControl, IBrowser browser, IFrame frame, IDomNode node);
}
}
| bsd-3-clause | C# |
b27b1606d764ac616e9780c5f91865c0dfd18bcc | use a list of key-value pairs instead of a dictionary (as it's not supported by xmlserializer natively and I'm too lazy to make it work) | SexyFishHorse/CitiesSkylines-Birdcage | Infrastructure/Configuration/ModConfiguration.cs | Infrastructure/Configuration/ModConfiguration.cs | namespace SexyFishHorse.CitiesSkylines.Infrastructure.Configuration
{
using System;
using System.Collections.Generic;
public class ModConfiguration
{
public ModConfiguration()
{
Settings = new List<KeyValuePair<string, object>>();
}
public List<KeyValuePair<string, object>> Settings { get; set; }
}
}
| namespace SexyFishHorse.CitiesSkylines.Infrastructure.Configuration
{
using System.Collections.Generic;
public class ModConfiguration
{
public IDictionary<string, object> Settings { get; set; }
}
}
| mit | C# |
6e49d6464c000d81fb31730209246b36f4bc17a2 | Test to run gui on STA thread | admoexperience/admo-kinect,admoexperience/admo-kinect | AdmoTests/CustomActionTests/CustomActionTests.cs | AdmoTests/CustomActionTests/CustomActionTests.cs | using System;
using System.Threading;
using Admo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AdmoInstallerCustomAction;
using System.Windows;
namespace AdmoTests.CustomActionTests
{
[TestClass]
public class CustomActionTests
{
[TestMethod]
public void TestRunWPFOnSTAThread()
{
//Will have to use gui testing tools here
Thread t = new Thread(() =>
{
var app = new Application();
app.Run(new DownloadRuntimeWPF());
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Abort();
}
}
}
| using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AdmoInstallerCustomAction;
using System.Windows;
namespace AdmoTests.CustomActionTests
{
[TestClass]
public class CustomActionTests
{
[TestMethod]
public void TestMethod1()
{
//Will have to use gui testing tools here
//ManualResetEvent syncEvent = new ManualResetEvent(false);
//Thread t = new Thread(() =>
//{
// var app = new Application();
// app.Run(new DownloadRuntimeWPF());
// // syncEvent.Set();
//});
//t.SetApartmentState(ApartmentState.STA);
//t.Start();
//t.Join();
}
}
}
| mit | C# |
b2718f18baf66188477efccc73f97569d957723b | fix rsa key generation failing | NTumbleBit/NTumbleBit,DanGould/NTumbleBit | NTumbleBit/BouncyCastle/security/SecureRandom.cs | NTumbleBit/BouncyCastle/security/SecureRandom.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit.BouncyCastle.Security
{
internal class SecureRandom : Random
{
public SecureRandom()
{
}
public override int Next()
{
return RandomUtils.GetInt32();
}
public override int Next(int maxValue)
{
throw new NotImplementedException();
}
public override int Next(int minValue, int maxValue)
{
throw new NotImplementedException();
}
public override void NextBytes(byte[] buffer)
{
RandomUtils.GetBytes(buffer);
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit.BouncyCastle.Security
{
internal class SecureRandom : Random
{
public SecureRandom()
{
}
public override int Next()
{
throw new NotImplementedException();
}
public override int Next(int maxValue)
{
throw new NotImplementedException();
}
public override int Next(int minValue, int maxValue)
{
throw new NotImplementedException();
}
public override void NextBytes(byte[] buffer)
{
RandomUtils.GetBytes(buffer);
}
}
}
| mit | C# |
a8490b5bba75afe927b21a9f8a9771824b6b1a53 | Add version number | loicteixeira/gj-unity-api | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.0.0";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "http://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION + "/";
public const string API_USERS_AUTH = "users/auth/";
public const string API_USERS_FETCH = "users/";
public const string API_SESSIONS_OPEN = "sessions/open/";
public const string API_SESSIONS_PING = "sessions/ping/";
public const string API_SESSIONS_CLOSE = "sessions/close/";
public const string API_SCORES_ADD = "scores/add/";
public const string API_SCORES_FETCH = "scores/";
public const string API_SCORES_TABLES_FETCH = "scores/tables/";
public const string API_TROPHIES_ADD = "trophies/add-achieved/";
public const string API_TROPHIES_FETCH = "trophies/";
public const string API_DATASTORE_SET = "data-store/set/";
public const string API_DATASTORE_UPDATE = "data-store/update/";
public const string API_DATASTORE_FETCH = "data-store/";
public const string API_DATASTORE_REMOVE = "data-store/remove/";
public const string API_DATASTORE_KEYS_FETCH = "data-store/get-keys/";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "http://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION + "/";
public const string API_USERS_AUTH = "users/auth/";
public const string API_USERS_FETCH = "users/";
public const string API_SESSIONS_OPEN = "sessions/open/";
public const string API_SESSIONS_PING = "sessions/ping/";
public const string API_SESSIONS_CLOSE = "sessions/close/";
public const string API_SCORES_ADD = "scores/add/";
public const string API_SCORES_FETCH = "scores/";
public const string API_SCORES_TABLES_FETCH = "scores/tables/";
public const string API_TROPHIES_ADD = "trophies/add-achieved/";
public const string API_TROPHIES_FETCH = "trophies/";
public const string API_DATASTORE_SET = "data-store/set/";
public const string API_DATASTORE_UPDATE = "data-store/update/";
public const string API_DATASTORE_FETCH = "data-store/";
public const string API_DATASTORE_REMOVE = "data-store/remove/";
public const string API_DATASTORE_KEYS_FETCH = "data-store/get-keys/";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| mit | C# |
60301099399d32e7c142182a0e3a1d5f8c612b90 | Update CompositeCurrencyConverter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/CompositeCurrencyConverter.cs | TIKSN.Core/Finance/CompositeCurrencyConverter.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance
{
public abstract class CompositeCurrencyConverter : ICompositeCurrencyConverter
{
protected ICurrencyConversionCompositionStrategy compositionStrategy;
protected List<ICurrencyConverter> converters;
protected CompositeCurrencyConverter(ICurrencyConversionCompositionStrategy compositionStrategy)
{
this.compositionStrategy =
compositionStrategy ?? throw new ArgumentNullException(nameof(compositionStrategy));
this.converters = new List<ICurrencyConverter>();
}
public void Add(ICurrencyConverter converter) => this.converters.Add(converter);
public abstract Task<Money> ConvertCurrencyAsync(Money baseMoney, CurrencyInfo counterCurrency,
DateTimeOffset asOn, CancellationToken cancellationToken);
public abstract Task<IEnumerable<CurrencyPair>> GetCurrencyPairsAsync(DateTimeOffset asOn,
CancellationToken cancellationToken);
public abstract Task<decimal> GetExchangeRateAsync(CurrencyPair pair, DateTimeOffset asOn,
CancellationToken cancellationToken);
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance
{
public abstract class CompositeCurrencyConverter : ICompositeCurrencyConverter
{
protected ICurrencyConversionCompositionStrategy compositionStrategy;
protected List<ICurrencyConverter> converters;
protected CompositeCurrencyConverter(ICurrencyConversionCompositionStrategy compositionStrategy)
{
this.compositionStrategy = compositionStrategy ?? throw new ArgumentNullException(nameof(compositionStrategy));
converters = new List<ICurrencyConverter>();
}
public void Add(ICurrencyConverter converter)
{
this.converters.Add(converter);
}
public abstract Task<Money> ConvertCurrencyAsync(Money baseMoney, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken);
public abstract Task<IEnumerable<CurrencyPair>> GetCurrencyPairsAsync(DateTimeOffset asOn, CancellationToken cancellationToken);
public abstract Task<decimal> GetExchangeRateAsync(CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken);
}
} | mit | C# |
aaf37729bcc062e08c1d9b6fa732b37199d979c6 | Add Get web client string method | fredatgithub/UsefulFunctions | FonctionsUtiles.Fred.Csharp/FunctionsInternet.cs | FonctionsUtiles.Fred.Csharp/FunctionsInternet.cs | using System;
using System.Net;
using System.Text;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsInternet
{
public static string Manifest()
{
const string newLine = "\n";
StringBuilder result = new StringBuilder();
result.Append(newLine + "Name= FonctionsUtiles.Fred.Csharp" + newLine);
result.Append("Version= 1.0.0.0" + newLine);
result.Append("Method= bool GetWebClientBinaries(string url = \"http://www.google.com/\", string fileName = \"untitled-file.pdf\")" + newLine);
result.Append("Method= " + newLine);
result.Append("Method= " + newLine);
return result.ToString();
}
public static bool GetWebClientBinaries(string url = "http://www.google.com/",
string fileName = "untitled-file.pdf")
{
WebClient client = new WebClient();
bool result = false;
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
client.DownloadFile(url, fileName);
result = true;
}
catch (WebException)
{
result = false;
}
catch (NotSupportedException)
{
result = false;
}
return result;
}
public static string GetWebClientString(string url = "http://www.google.com/")
{
// create a new instance of WebClient
WebClient client = new WebClient();
string result = string.Empty;
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
// actually execute the GET request
string ret = client.DownloadString(url);
// ret now contains the contents of the webpage
Console.WriteLine("First 256 bytes of response: " + ret.Substring(0, 265));
result = ret;
}
catch (WebException we)
{
// WebException.Status holds useful information
Console.WriteLine(we.Message + "\n" + we.Status.ToString());
}
catch (NotSupportedException ne)
{
// other errors
Console.WriteLine(ne.Message);
}
return result;
}
}
} | using System;
using System.Net;
using System.Text;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsInternet
{
public static string Manifest()
{
const string newLine = "\n";
StringBuilder result = new StringBuilder();
result.Append(newLine + "Name= FonctionsUtiles.Fred.Csharp" + newLine);
result.Append("Version= 1.0.0.0" + newLine);
result.Append("Method= bool GetWebClientBinaries(string url = \"http://www.google.com/\", string fileName = \"untitled-file.pdf\")" + newLine);
result.Append("Method= " + newLine);
result.Append("Method= " + newLine);
return result.ToString();
}
public static bool GetWebClientBinaries(string url = "http://www.google.com/",
string fileName = "untitled-file.pdf")
{
WebClient client = new WebClient();
bool result = false;
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
client.DownloadFile(url, fileName);
result = true;
}
catch (WebException)
{
result = false;
}
catch (NotSupportedException)
{
result = false;
}
return result;
}
}
} | mit | C# |
50b25680e220c3517f8372df30f175dd72bd8d99 | update AssemblyVersion on ServiceContract | gigya/microdot | Gigya.ServiceContract/Properties/AssemblyInfo.cs | Gigya.ServiceContract/Properties/AssemblyInfo.cs | #region Copyright
// Copyright 2017 Gigya Inc. 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 SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
// This is the NuGet version, if pre-release should be in the format of "2.0.0-Zdevelop08".
[assembly: AssemblyInformationalVersion("2.4.9-pre01")]
[assembly: AssemblyVersion("2.4.9.0")]
[assembly: AssemblyFileVersion("2.4.9.0")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)] | #region Copyright
// Copyright 2017 Gigya Inc. 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 SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
// This is the NuGet version, if pre-release should be in the format of "2.0.0-Zdevelop08".
[assembly: AssemblyInformationalVersion("2.4.8.0")]
[assembly: AssemblyVersion("2.4.8.0")]
[assembly: AssemblyFileVersion("2.4.8.0")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)] | apache-2.0 | C# |
3f1a4a5f50cb62ee10f1e989cc4da8c874002cfa | remove error when trying to delete list | ismaelbelghiti/Tigwi,ismaelbelghiti/Tigwi | Core/Tigwi.UI/Views/Shared/_ConfirmDeleteModal.cshtml | Core/Tigwi.UI/Views/Shared/_ConfirmDeleteModal.cshtml | <div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Delete a list</h3>
</div>
<div class="modal-body">
<p>This feature is not implemented yet.</p>
</div>
@*
<div class="modal-body">
<p>Are you sur you want to delete list <b id="deleteListName"></b> : <b id="deleteListDescr"></b> ?</p>
<ul id="deleteListMembers">
</ul>
</div>
<div class="modal-footer">
@using(Html.BeginForm("DeleteList","List"))
{
<input type="hidden" name="id" id="deleteListId"/>
<a href="#" class="btn" data-dismiss="modal">Cancel</a>
<button class="btn btn-primary" type="submit" >Yes !</button>
}
</div>
*@
| <div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Delete a list</h3>
</div>
<div class="modal-body">
<p>Are you sur you want to delete list <b id="deleteListName"></b> : <b id="deleteListDescr"></b> ?</p>
<ul id="deleteListMembers">
</ul>
</div>
<div class="modal-footer">
@using(Html.BeginForm("DeleteList","List"))
{
<input type="hidden" name="id" id="deleteListId"/>
<a href="#" class="btn" data-dismiss="modal">Cancel</a>
<button class="btn btn-primary" type="submit" >Yes !</button>
}
</div>
| bsd-3-clause | C# |
5db49cb2a557354883cf4d00a5b599cc26266e60 | Implement first step of automation layer | dirkrombauts/fizz-buzz | Specification/AutomationLayer/StepDefinitions.cs | Specification/AutomationLayer/StepDefinitions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
namespace FizzBuzz.Specification.AutomationLayer
{
[Binding]
public class StepDefinitions
{
private int currentNumber;
[Given(@"the current number is '(.*)'")]
public void GivenTheCurrentNumberIs(int currentNumber)
{
this.currentNumber = currentNumber;
}
[When(@"I print the number")]
public void WhenIPrintTheNumber()
{
ScenarioContext.Current.Pending();
}
[Then(@"the result is '(.*)'")]
public void ThenTheResultIs(int p0)
{
ScenarioContext.Current.Pending();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
namespace FizzBuzz.Specification.AutomationLayer
{
[Binding]
public class StepDefinitions
{
[Given(@"the current number is '(.*)'")]
public void GivenTheCurrentNumberIs(int p0)
{
ScenarioContext.Current.Pending();
}
[When(@"I print the number")]
public void WhenIPrintTheNumber()
{
ScenarioContext.Current.Pending();
}
[Then(@"the result is '(.*)'")]
public void ThenTheResultIs(int p0)
{
ScenarioContext.Current.Pending();
}
}
}
| mit | C# |
4c41b6ae7eac45a43a82ac79139a0fbda8ec01a9 | Throw error if not attached to a camera | EvanHahn/Unity-RTS-camera | RTSCamera.cs | RTSCamera.cs | using UnityEngine;
using System.Collections;
public class RTSCamera : MonoBehaviour {
public bool disablePanning = false;
public bool disableSelect = false;
public Color selectColor = Color.green;
public float selectLineWidth = 2f;
private readonly string[] INPUT_MOUSE_BUTTONS = {"Mouse Look", "Mouse Select"};
private bool[] isDragging = new bool[2];
private Vector3 selectStartPosition;
private Texture2D pixel;
void Start() {
if (!camera) {
throw new MissingComponentException("RTS Camera must be attached to a camera.");
}
setPixel(selectColor);
}
void Update() {
updateDragging();
updateLook();
}
void OnGUI() {
updateSelect();
}
private void updateDragging() {
for (int index = 0; index <= 1; index ++) {
if (isClicking(index) && !isDragging[index]) {
isDragging[index] = true;
if (index == 1) {
selectStartPosition = getMousePosition();
}
} else if (!isClicking(index) && isDragging[index]) {
isDragging[index] = false;
}
}
}
private void updateLook() {
if (!isDragging[0] || disablePanning) { return; }
var newPosition = transform.position;
var mousePosition = getMouseMovement();
newPosition.x = newPosition.x - mousePosition.x;
newPosition.y = newPosition.y - mousePosition.y;
transform.position = newPosition;
}
private void updateSelect() {
if (!isDragging[1] || disableSelect) { return; }
var x = selectStartPosition.x;
var y = selectStartPosition.y;
var width = getMousePosition().x - selectStartPosition.x;
var height = getMousePosition().y - selectStartPosition.y;
GUI.DrawTexture(new Rect(x, y, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x, y, selectLineWidth, height), pixel);
GUI.DrawTexture(new Rect(x, y + height, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x + width, y, selectLineWidth, height), pixel);
}
private bool isClicking(int index) {
return Input.GetAxis(INPUT_MOUSE_BUTTONS[index]) == 1;
}
private Vector2 getMouseMovement() {
return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
private void setPixel(Color color) {
pixel = new Texture2D(1, 1);
pixel.SetPixel(0, 0, color);
pixel.Apply();
}
private Vector3 getMousePosition() {
var result = Input.mousePosition;
result.y = Screen.height - result.y;
return result;
}
}
| using UnityEngine;
using System.Collections;
public class RTSCamera : MonoBehaviour {
public bool disablePanning = false;
public bool disableSelect = false;
public Color selectColor = Color.green;
public float selectLineWidth = 2f;
private readonly string[] INPUT_MOUSE_BUTTONS = {"Mouse Look", "Mouse Select"};
private bool[] isDragging = new bool[2];
private Vector3 selectStartPosition;
private Texture2D pixel;
void Start() {
setPixel(selectColor);
}
void Update() {
updateDragging();
updateLook();
}
void OnGUI() {
updateSelect();
}
private void updateDragging() {
for (int index = 0; index <= 1; index ++) {
if (isClicking(index) && !isDragging[index]) {
isDragging[index] = true;
if (index == 1) {
selectStartPosition = getMousePosition();
}
} else if (!isClicking(index) && isDragging[index]) {
isDragging[index] = false;
}
}
}
private void updateLook() {
if (!isDragging[0] || disablePanning) { return; }
var newPosition = transform.position;
var mousePosition = getMouseMovement();
newPosition.x = newPosition.x - mousePosition.x;
newPosition.y = newPosition.y - mousePosition.y;
transform.position = newPosition;
}
private void updateSelect() {
if (!isDragging[1] || disableSelect) { return; }
var x = selectStartPosition.x;
var y = selectStartPosition.y;
var width = getMousePosition().x - selectStartPosition.x;
var height = getMousePosition().y - selectStartPosition.y;
GUI.DrawTexture(new Rect(x, y, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x, y, selectLineWidth, height), pixel);
GUI.DrawTexture(new Rect(x, y + height, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x + width, y, selectLineWidth, height), pixel);
}
private bool isClicking(int index) {
return Input.GetAxis(INPUT_MOUSE_BUTTONS[index]) == 1;
}
private Vector2 getMouseMovement() {
return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
private void setPixel(Color color) {
pixel = new Texture2D(1, 1);
pixel.SetPixel(0, 0, color);
pixel.Apply();
}
private Vector3 getMousePosition() {
var result = Input.mousePosition;
result.y = Screen.height - result.y;
return result;
}
}
| mit | C# |
d41ab6a42965397218c9c91cc808201d24c382dd | Fix integration tests - register PackageMigrationRunner | dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS | src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs | src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Installer.cs | using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Install.InstallSteps;
using Umbraco.Cms.Core.Install.Models;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Infrastructure.Install.InstallSteps;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.DependencyInjection
{
public static partial class UmbracoBuilderExtensions
{
/// <summary>
/// Adds the services for the Umbraco installer
/// </summary>
internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder)
{
// register the installer steps
builder.Services.AddScoped<InstallSetupStep, NewInstallStep>();
builder.Services.AddScoped<InstallSetupStep, UpgradeStep>();
builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>();
builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>();
builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>();
builder.Services.AddTransient<InstallStepCollection>();
builder.Services.AddUnique<InstallHelper>();
builder.Services.AddTransient<PackageMigrationRunner>();
return builder;
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Install.InstallSteps;
using Umbraco.Cms.Core.Install.Models;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Infrastructure.Install.InstallSteps;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.DependencyInjection
{
public static partial class UmbracoBuilderExtensions
{
/// <summary>
/// Adds the services for the Umbraco installer
/// </summary>
internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder)
{
// register the installer steps
builder.Services.AddScoped<InstallSetupStep, NewInstallStep>();
builder.Services.AddScoped<InstallSetupStep, UpgradeStep>();
builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>();
builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>();
builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>();
builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>();
builder.Services.AddTransient<InstallStepCollection>();
builder.Services.AddUnique<InstallHelper>();
return builder;
}
}
}
| mit | C# |
1b78327ba0ddb98baebfc103dd5c15b7acf0a038 | Fix broken test | jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | iam/api/GrantableRolesTest/GrantableRolesTest.cs | iam/api/GrantableRolesTest/GrantableRolesTest.cs | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Xunit;
namespace GoogleCloudSamples
{
public class GrantableRolesTest
{
[Fact]
public void TestGrantableRoles()
{
// Main will throw an exception on fail
string project = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
string resource = "//cloudresourcemanager.googleapis.com/projects/" + project;
Console.WriteLine(resource);
GrantableRoles.Main(new[] { resource });
}
}
}
| // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Xunit;
namespace GoogleCloudSamples
{
public class GrantableRolesTest
{
[Fact]
public void TestGrantableRoles()
{
// Main will throw an exception on fail
string project = Environment.GetEnvironmentVariable(
"GOOGLE_PROJECT_ID");
string resource = "//cloudresourcemanager.googleapis.com/projects/" +
project;
GrantableRoles.Main(new[] { resource });
}
}
}
| apache-2.0 | C# |
5fd7588f3e556c3104fbdb3ef536f4c39a73003e | Implement WebResourceName.GetHashCode and Equals for UnitTests | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/DataAccess/WebResourceName.cs | CalDavSynchronizer/DataAccess/WebResourceName.cs | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
namespace CalDavSynchronizer.DataAccess
{
public class WebResourceName
{
public string OriginalAbsolutePath {get; set; }
public string Id {get; set; }
public WebResourceName (Uri uri)
: this (uri.AbsolutePath)
{
}
public WebResourceName (string absolutePath)
{
OriginalAbsolutePath = absolutePath;
Id = DecodedString (absolutePath);
}
private static string DecodedString (string value)
{
string newValue;
while ((newValue = Uri.UnescapeDataString (value)) != value)
value = newValue;
return newValue;
}
public WebResourceName ()
{
}
public override int GetHashCode ()
{
return Comparer.GetHashCode (this);
}
public override bool Equals (object obj)
{
return Comparer.Equals (this, obj as WebResourceName);
}
public static readonly IEqualityComparer<WebResourceName> Comparer = new WebResourceNameEqualityComparer();
private class WebResourceNameEqualityComparer : IEqualityComparer<WebResourceName>
{
private static readonly IEqualityComparer<string> s_stringComparer = StringComparer.OrdinalIgnoreCase;
public bool Equals (WebResourceName x, WebResourceName y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return s_stringComparer.Equals (x.Id, y.Id);
}
public int GetHashCode (WebResourceName obj)
{
return s_stringComparer.GetHashCode (obj.Id);
}
}
}
} | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
namespace CalDavSynchronizer.DataAccess
{
public class WebResourceName
{
public string OriginalAbsolutePath {get; set; }
public string Id {get; set; }
public WebResourceName (Uri uri)
: this (uri.AbsolutePath)
{
}
public WebResourceName (string absolutePath)
{
OriginalAbsolutePath = absolutePath;
Id = DecodedString (absolutePath);
}
private static string DecodedString (string value)
{
string newValue;
while ((newValue = Uri.UnescapeDataString (value)) != value)
value = newValue;
return newValue;
}
public WebResourceName ()
{
}
public static readonly IEqualityComparer<WebResourceName> Comparer = new WebResourceNameEqualityComparer();
private class WebResourceNameEqualityComparer : IEqualityComparer<WebResourceName>
{
private static readonly IEqualityComparer<string> s_stringComparer = StringComparer.OrdinalIgnoreCase;
public bool Equals (WebResourceName x, WebResourceName y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return s_stringComparer.Equals (x.Id, y.Id);
}
public int GetHashCode (WebResourceName obj)
{
return s_stringComparer.GetHashCode (obj.Id);
}
}
}
} | agpl-3.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.