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 |
---|---|---|---|---|---|---|---|---|
6c5561d7d930e2cd43da53bb6c231df2aa8f9951 | Update ArrowMarker.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Modules/Renderer/Avalonia/Nodes/Markers/ArrowMarker.cs | src/Core2D/Modules/Renderer/Avalonia/Nodes/Markers/ArrowMarker.cs | #nullable enable
using A = Avalonia;
using AP = Avalonia.Platform;
namespace Core2D.Modules.Renderer.Avalonia.Nodes.Markers;
internal class ArrowMarker : MarkerBase
{
public A.Point P11;
public A.Point P21;
public A.Point P12;
public A.Point P22;
public override void Draw(object? dc)
{
if (dc is not AP.IDrawingContextImpl context)
{
return;
}
if (ShapeViewModel is { } && ShapeViewModel.IsStroked && Pen is { })
{
context.DrawLine(Pen, P11, P21);
context.DrawLine(Pen, P12, P22);
}
}
}
| #nullable enable
using A = Avalonia;
using AP = Avalonia.Platform;
namespace Core2D.Modules.Renderer.Avalonia.Nodes.Markers;
internal class ArrowMarker : MarkerBase
{
public A.Point P11;
public A.Point P21;
public A.Point P12;
public A.Point P22;
public override void Draw(object? dc)
{
if (dc is not AP.IDrawingContextImpl context)
{
return;
}
if (ShapeViewModel.IsStroked)
{
context.DrawLine(Pen, P11, P21);
context.DrawLine(Pen, P12, P22);
}
}
}
| mit | C# |
1f6e098f74623ddb83f456f3b14023ad69d523ab | Fix PubSub converter attribute in protobuf | googleapis/google-cloudevents-dotnet,googleapis/google-cloudevents-dotnet | src/Google.Events.Protobuf/Cloud/PubSub/V1/ConverterAttributes.cs | src/Google.Events.Protobuf/Cloud/PubSub/V1/ConverterAttributes.cs | // Copyright 2020, Google LLC
//
// 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<MessagePublishedData>))]
public partial class MessagePublishedData { }
}
| // Copyright 2020, Google LLC
//
// 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
| apache-2.0 | C# |
831785fe9fc4e3fd00889ce59b38c68a6c021a9a | Make AddAuthorization() idempotent | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Authorization/ServiceCollectionExtensions.cs | src/Microsoft.AspNet.Authorization/ServiceCollectionExtensions.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.
using System;
using Microsoft.AspNet.Authorization;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services)
{
services.AddOptions();
services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>());
services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, PassThroughAuthorizationHandler>());
return services;
}
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services, [NotNull] Action<AuthorizationOptions> configure)
{
services.Configure(configure);
return services.AddAuthorization();
}
}
} | // 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.
using System;
using Microsoft.AspNet.Authorization;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services)
{
services.AddOptions();
services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>());
services.AddTransient<IAuthorizationHandler, PassThroughAuthorizationHandler>();
return services;
}
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services, [NotNull] Action<AuthorizationOptions> configure)
{
services.Configure(configure);
return services.AddAuthorization();
}
}
} | apache-2.0 | C# |
092f234943dcdf5b5b89732c5d1d1e8f8d0343ab | Add a check to make sure the CombatMode is the current player (#663) | space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14 | Content.Client/GameObjects/Components/Mobs/CombatModeComponent.cs | Content.Client/GameObjects/Components/Mobs/CombatModeComponent.cs | using Content.Client.UserInterface;
using Content.Shared.GameObjects.Components.Mobs;
using Robust.Client.GameObjects;
using Robust.Client.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects.Components.Mobs
{
[RegisterComponent]
public sealed class CombatModeComponent : SharedCombatModeComponent
{
#pragma warning disable 649
[Dependency] private readonly IPlayerManager _playerManager;
#pragma warning restore 649
[ViewVariables(VVAccess.ReadWrite)]
public bool IsInCombatMode { get; private set; }
[ViewVariables(VVAccess.ReadWrite)]
public TargetingZone ActiveZone { get; private set; }
#pragma warning disable 649
[Dependency] private readonly IGameHud _gameHud;
#pragma warning restore 649
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
base.HandleComponentState(curState, nextState);
var state = (CombatModeComponentState) curState;
IsInCombatMode = state.IsInCombatMode;
ActiveZone = state.TargetingZone;
if (Owner == _playerManager.LocalPlayer.ControlledEntity)
{
UpdateHud();
}
}
public override void HandleMessage(ComponentMessage message, INetChannel netChannel = null, IComponent component = null)
{
base.HandleMessage(message, netChannel, component);
switch (message)
{
case PlayerAttachedMsg _:
_gameHud.CombatPanelVisible = true;
UpdateHud();
break;
case PlayerDetachedMsg _:
_gameHud.CombatPanelVisible = false;
break;
}
}
private void UpdateHud()
{
_gameHud.CombatModeActive = IsInCombatMode;
_gameHud.TargetingZone = ActiveZone;
}
}
}
| using Content.Client.UserInterface;
using Content.Shared.GameObjects.Components.Mobs;
using Robust.Client.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects.Components.Mobs
{
[RegisterComponent]
public sealed class CombatModeComponent : SharedCombatModeComponent
{
[ViewVariables(VVAccess.ReadWrite)]
public bool IsInCombatMode { get; private set; }
[ViewVariables(VVAccess.ReadWrite)]
public TargetingZone ActiveZone { get; private set; }
#pragma warning disable 649
[Dependency] private readonly IGameHud _gameHud;
#pragma warning restore 649
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
base.HandleComponentState(curState, nextState);
var state = (CombatModeComponentState) curState;
IsInCombatMode = state.IsInCombatMode;
ActiveZone = state.TargetingZone;
UpdateHud();
}
public override void HandleMessage(ComponentMessage message, INetChannel netChannel = null, IComponent component = null)
{
base.HandleMessage(message, netChannel, component);
switch (message)
{
case PlayerAttachedMsg _:
_gameHud.CombatPanelVisible = true;
UpdateHud();
break;
case PlayerDetachedMsg _:
_gameHud.CombatPanelVisible = false;
break;
}
}
private void UpdateHud()
{
_gameHud.CombatModeActive = IsInCombatMode;
_gameHud.TargetingZone = ActiveZone;
}
}
}
| mit | C# |
2e3578b953a710ab370692f3c015e901cc9286df | Add winner menu in the back office site. | tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer | DailySoccer2015/DailySoccerBackOffice/Views/Shared/_Layout.cshtml | DailySoccer2015/DailySoccerBackOffice/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
@*<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>*@
<li>@Html.ActionLink("Winner", "Index", "Winner")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
7ac147a604ea8096e9ffc2c1705b78791896790c | rename a test to clarify. | jwChung/Experimentalism,jwChung/Experimentalism | test/Experiment.IdiomsUnitTest/ExcludingReadOnlyPropertiesTest.cs | test/Experiment.IdiomsUnitTest/ExcludingReadOnlyPropertiesTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Jwc.Experiment.Idioms
{
public class ExcludingReadOnlyPropertiesTest
{
[Fact]
public void SutIsEnumerableOfMemberInfo()
{
var sut = new ExcludingReadOnlyProperties(new MemberInfo[0]);
Assert.IsAssignableFrom<IEnumerable<MemberInfo>>(sut);
}
[Fact]
public void TargetMembersIsCorrect()
{
var targetMembers = GetType().GetMembers();
var sut = new ExcludingReadOnlyProperties(targetMembers);
var expected = sut.TargetMembers;
Assert.Equal(targetMembers, expected);
}
[Fact]
public void InitializeWithNullTargetMembersThrows()
{
Assert.Throws<ArgumentNullException>(
() => new ExcludingReadOnlyProperties(null));
}
[Fact]
public void SutEnumeratesOnlyWritableProperties()
{
var targetMembers = typeof(TypeWithProperties).GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var sut = new ExcludingReadOnlyProperties(targetMembers);
var expected = new[]
{
typeof(TypeWithProperties).GetProperty("GetSetProperty"),
typeof(TypeWithProperties).GetProperty("SetProperty"),
typeof(TypeWithProperties).GetProperty("PrivateGetProperty")
};
var actual = sut.Cast<PropertyInfo>().ToArray();
Assert.Equal(expected, actual);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Jwc.Experiment.Idioms
{
public class ExcludingReadOnlyPropertiesTest
{
[Fact]
public void SutIsEnumerableOfMemberInfo()
{
var sut = new ExcludingReadOnlyProperties(new MemberInfo[0]);
Assert.IsAssignableFrom<IEnumerable<MemberInfo>>(sut);
}
[Fact]
public void TargetMembersIsCorrect()
{
var targetMembers = GetType().GetMembers();
var sut = new ExcludingReadOnlyProperties(targetMembers);
var expected = sut.TargetMembers;
Assert.Equal(targetMembers, expected);
}
[Fact]
public void InitializeWithNullTargetMembersThrows()
{
Assert.Throws<ArgumentNullException>(
() => new ExcludingReadOnlyProperties(null));
}
[Fact]
public void SutDoesNotEnumerateReadOnlyProperties()
{
var targetMembers = typeof(TypeWithProperties).GetProperties(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var sut = new ExcludingReadOnlyProperties(targetMembers);
var expected = new[]
{
typeof(TypeWithProperties).GetProperty("GetSetProperty"),
typeof(TypeWithProperties).GetProperty("SetProperty"),
typeof(TypeWithProperties).GetProperty("PrivateGetProperty")
};
var actual = sut.Cast<PropertyInfo>().ToArray();
Assert.Equal(expected, actual);
}
}
} | mit | C# |
a4ff5e79d91ed959ca57e2f7e7e1cf29236e0d92 | Bump version | HelloFax/hellosign-dotnet-sdk | HelloSign/Properties/AssemblyInfo.cs | HelloSign/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("HelloSign")]
[assembly: AssemblyDescription("Client library for using the HelloSign API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HelloSign")]
[assembly: AssemblyProduct("HelloSign")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("HelloSign")]
[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("c36ca08c-9b2a-4b52-a8ae-03d364d69267")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// [assembly: AssemblyVersion("1.0.*")]
// [assembly: AssemblyVersion("0.0.0.0")]
// NOTE: This gets reported in the user-agent string for HTTP requests made.
[assembly: AssemblyFileVersion("0.4.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("HelloSign")]
[assembly: AssemblyDescription("Client library for using the HelloSign API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HelloSign")]
[assembly: AssemblyProduct("HelloSign")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("HelloSign")]
[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("c36ca08c-9b2a-4b52-a8ae-03d364d69267")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// [assembly: AssemblyVersion("1.0.*")]
// [assembly: AssemblyVersion("0.0.0.0")]
// NOTE: This gets reported in the user-agent string for HTTP requests made.
[assembly: AssemblyFileVersion("0.2.0.0")]
| mit | C# |
182bf29c7b4dcd012b6423fb0656173e1036d17e | Change access level to public so that StructureMap can find the property for the queuename | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Application/Commands/CreateEmployerAccount/CreateAccountCommandHandler.cs | src/SFA.DAS.EmployerApprenticeshipsService.Application/Commands/CreateEmployerAccount/CreateAccountCommandHandler.cs | using System;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Messages;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Attributes;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Data;
using SFA.DAS.Messaging;
namespace SFA.DAS.EmployerApprenticeshipsService.Application.Commands.CreateEmployerAccount
{
public class CreateAccountCommandHandler : AsyncRequestHandler<CreateAccountCommand>
{
[QueueName]
public string das_at_eas_get_employer_levy { get; set; }
private readonly IAccountRepository _accountRepository;
private readonly IMessagePublisher _messagePublisher;
private readonly CreateAccountCommandValidator _validator;
public CreateAccountCommandHandler(IAccountRepository accountRepository, IMessagePublisher messagePublisher)
{
if (accountRepository == null)
throw new ArgumentNullException(nameof(accountRepository));
if (messagePublisher == null)
throw new ArgumentNullException(nameof(messagePublisher));
_accountRepository = accountRepository;
_messagePublisher = messagePublisher;
_validator = new CreateAccountCommandValidator();
}
protected override async Task HandleCore(CreateAccountCommand message)
{
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid())
throw new InvalidRequestException(validationResult.ValidationDictionary);
var accountId = await _accountRepository.CreateAccount(message.UserId, message.CompanyNumber, message.CompanyName, message.EmployerRef);
await _messagePublisher.PublishAsync(new EmployerRefreshLevyQueueMessage
{
AccountId = accountId
});
}
}
} | using System;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Messages;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Attributes;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Data;
using SFA.DAS.Messaging;
namespace SFA.DAS.EmployerApprenticeshipsService.Application.Commands.CreateEmployerAccount
{
public class CreateAccountCommandHandler : AsyncRequestHandler<CreateAccountCommand>
{
[QueueName]
private string das_at_eas_get_employer_levy { get; set; }
private readonly IAccountRepository _accountRepository;
private readonly IMessagePublisher _messagePublisher;
private readonly CreateAccountCommandValidator _validator;
public CreateAccountCommandHandler(IAccountRepository accountRepository, IMessagePublisher messagePublisher)
{
if (accountRepository == null)
throw new ArgumentNullException(nameof(accountRepository));
if (messagePublisher == null)
throw new ArgumentNullException(nameof(messagePublisher));
_accountRepository = accountRepository;
_messagePublisher = messagePublisher;
_validator = new CreateAccountCommandValidator();
}
protected override async Task HandleCore(CreateAccountCommand message)
{
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid())
throw new InvalidRequestException(validationResult.ValidationDictionary);
var accountId = await _accountRepository.CreateAccount(message.UserId, message.CompanyNumber, message.CompanyName, message.EmployerRef);
await _messagePublisher.PublishAsync(new EmployerRefreshLevyQueueMessage
{
AccountId = accountId
});
}
}
} | mit | C# |
06a655af5d0187803a0048ddd28fa500f92fe8ba | Move initial position of KeyCounter upwards. | Drezi126/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,DrabWeb/osu,tacchinotacchi/osu,smoogipooo/osu,DrabWeb/osu,peppy/osu,Frontear/osuKyzer,johnneijzen/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,ZLima12/osu,2yangk23/osu,peppy/osu-new,Nabile-Rahmani/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,RedNesto/osu,NeoAdonis/osu,nyaamara/osu,osu-RP/osu-RP,smoogipoo/osu,Damnae/osu,2yangk23/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu | osu.Game/Modes/UI/StandardHudOverlay.cs | osu.Game/Modes/UI/StandardHudOverlay.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
namespace osu.Game.Modes.UI
{
public class StandardHudOverlay : HudOverlay
{
protected override PercentageCounter CreateAccuracyCounter() => new PercentageCounter
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Position = new Vector2(0, 65),
TextSize = 20,
Margin = new MarginPadding { Right = 5 },
};
protected override ComboCounter CreateComboCounter() => new StandardComboCounter
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
};
protected override HealthDisplay CreateHealthDisplay() => new StandardHealthDisplay
{
Size = new Vector2(1, 5),
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding { Top = 20 }
};
protected override KeyCounterCollection CreateKeyCounter() => new KeyCounterCollection
{
IsCounting = true,
FadeTime = 50,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Margin = new MarginPadding(10),
Y = - TwoLayerButton.SIZE_RETRACTED.Y,
};
protected override ScoreCounter CreateScoreCounter() => new ScoreCounter(6)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
TextSize = 40,
Position = new Vector2(0, 30),
Margin = new MarginPadding { Right = 5 },
};
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
namespace osu.Game.Modes.UI
{
public class StandardHudOverlay : HudOverlay
{
protected override PercentageCounter CreateAccuracyCounter() => new PercentageCounter
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Position = new Vector2(0, 65),
TextSize = 20,
Margin = new MarginPadding { Right = 5 },
};
protected override ComboCounter CreateComboCounter() => new StandardComboCounter
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
};
protected override HealthDisplay CreateHealthDisplay() => new StandardHealthDisplay
{
Size = new Vector2(1, 5),
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding { Top = 20 }
};
protected override KeyCounterCollection CreateKeyCounter() => new KeyCounterCollection
{
IsCounting = true,
FadeTime = 50,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Margin = new MarginPadding(10),
};
protected override ScoreCounter CreateScoreCounter() => new ScoreCounter(6)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
TextSize = 40,
Position = new Vector2(0, 30),
Margin = new MarginPadding { Right = 5 },
};
}
}
| mit | C# |
160f893922d6071260476df320375c7f911f4931 | Fix C# Pair.cs, #1634. | ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4 | runtime/CSharp/runtime/CSharp/Antlr4.Runtime/Misc/Pair.cs | runtime/CSharp/runtime/CSharp/Antlr4.Runtime/Misc/Pair.cs | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
namespace Antlr4.Runtime.Misc
{
public class Pair<A, B>
{
public readonly A a;
public readonly B b;
public Pair(A a, B b)
{
this.a = a;
this.b = b;
}
public override bool Equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (!(obj is Pair<A, B>))
{
return false;
}
Pair<A, B> other = (Pair<A, B>)obj;
return (a == null ? other.a == null : a.Equals(other.a)) &&
(b == null ? other.b == null : b.Equals(other.b));
}
public override int GetHashCode()
{
int hash = MurmurHash.Initialize();
hash = MurmurHash.Update(hash, a);
hash = MurmurHash.Update(hash, b);
return MurmurHash.Finish(hash, 2);
}
public override String ToString()
{
return String.Format("({0}, {1})", a, b);
}
}
} | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
namespace Antlr4.Runtime.Misc
{
public class Pair<A, B>
{
public readonly A a;
public readonly B b;
public Pair(A a, B b)
{
this.a = a;
this.b = b;
}
public override bool Equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (!(obj is Pair<A, B>)) {
return false;
}
Pair <A, B> other = (Pair <A, B>)obj;
return a==null ? other.a==null : a.Equals(other.b);
}
public override int GetHashCode()
{
int hash = MurmurHash.Initialize();
hash = MurmurHash.Update(hash, a);
hash = MurmurHash.Update(hash, b);
return MurmurHash.Finish(hash, 2);
}
public override String ToString()
{
return String.Format("(%s, %s)", a, b);
}
}
}
| bsd-3-clause | C# |
93f1804cd7b51e23eed3d2f54c4943f0f8c02175 | Make the system respect the Target ConnectionString Provider designation. | bsstahl/PPTail,bsstahl/PPTail | PrehensilePonyTail/PPTail/Program.cs | PrehensilePonyTail/PPTail/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
using PPTail.Extensions;
namespace PPTail
{
public class Program
{
const string _connectionStringProviderKey = "Provider";
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// Generate the website pages
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// Store the resulting output
var outputRepoInstanceName = settings.TargetConnection.GetConnectionStringValue(_connectionStringProviderKey);
var outputRepo = serviceProvider.GetNamedService<IOutputRepository>(outputRepoInstanceName);
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using PPTail.Entities;
using PPTail.Interfaces;
namespace PPTail
{
public class Program
{
public static void Main(string[] args)
{
(var argsAreValid, var argumentErrrors) = args.ValidateArguments();
if (argsAreValid)
{
var (sourceConnection, targetConnection, templateConnection) = args.ParseArguments();
var settings = (null as ISettings).Create(sourceConnection, targetConnection, templateConnection);
var templates = (null as IEnumerable<Template>).Create(templateConnection);
var container = (null as IServiceCollection).Create(settings, templates);
var serviceProvider = container.BuildServiceProvider();
// TODO: Move data load here -- outside of the build process
//var contentRepos = serviceProvider.GetServices<IContentRepository>();
//var contentRepo = contentRepos.First(); // TODO: Implement properly
var siteBuilder = serviceProvider.GetService<ISiteBuilder>();
var sitePages = siteBuilder.Build();
// TODO: Change this to use the named provider specified in the input args
var outputRepo = serviceProvider.GetService<Interfaces.IOutputRepository>();
outputRepo.Save(sitePages);
}
else
{
// TODO: Display argument errors to user
throw new NotImplementedException();
}
}
}
}
| mit | C# |
4f49c7a2c4caa8cdf6c428e4229e5e701d807ea8 | Use HttpDownloadString | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Tooling/LatestMyGetVersionAttribute.cs | source/Nuke.Common/Tooling/LatestMyGetVersionAttribute.cs | // Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Common.Utilities;
using Nuke.Common.ValueInjection;
namespace Nuke.Common.Tooling
{
[PublicAPI]
public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase
{
private readonly string _feed;
private readonly string _package;
public LatestMyGetVersionAttribute(string feed, string package)
{
_feed = feed;
_package = package;
}
public override object GetValue(MemberInfo member, object instance)
{
var content = HttpTasks.HttpDownloadString($"https://www.myget.org/RSS/{_feed}");
return XmlTasks.XmlPeekFromString(content, ".//title")
// TODO: regex?
.First(x => x.Contains($"/{_package} "))
.Split('(').Last()
.Split(')').First()
.TrimStart("version ");
}
}
}
| // Copyright 2020 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Nuke.Common.IO;
using Nuke.Common.Utilities;
using Nuke.Common.ValueInjection;
namespace Nuke.Common.Tooling
{
[PublicAPI]
public class LatestMyGetVersionAttribute : ValueInjectionAttributeBase
{
private readonly string _feed;
private readonly string _package;
public LatestMyGetVersionAttribute(string feed, string package)
{
_feed = feed;
_package = package;
}
public override object GetValue(MemberInfo member, object instance)
{
var rssFile = NukeBuild.TemporaryDirectory / $"{_feed}.xml";
HttpTasks.HttpDownloadFile($"https://www.myget.org/RSS/{_feed}", rssFile);
return XmlTasks.XmlPeek(rssFile, ".//title")
// TODO: regex?
.First(x => x.Contains($"/{_package} "))
.Split('(').Last()
.Split(')').First()
.TrimStart("version ");
}
}
}
| mit | C# |
dfbbf80b070969cd3c9f4fb94481fa8786142032 | use PS to update version | valadas/Dnn.Platform,wael101/Dnn.Platform,bdukes/Dnn.Platform,svdv71/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,EPTamminga/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,svdv71/Dnn.Platform,nvisionative/Dnn.Platform,wael101/Dnn.Platform,svdv71/Dnn.Platform,dnnsoftware/Dnn.Platform,wael101/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,nvisionative/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,robsiera/Dnn.Platform | Build/cake/version.cake | Build/cake/version.cake | #addin Cake.XdtTransform
#addin "Cake.FileHelpers"
#addin Cake.Powershell
#tool "nuget:?package=GitVersion.CommandLine&prerelease"
GitVersion version;
var buildId = EnvironmentVariable("Build.BuildId") ?? string.Empty;
Task("BuildServerSetVersion")
.IsDependentOn("GitVersion")
.Does(() => {
StartPowershellScript("Write-Host", args =>
{
args.AppendQuoted($"##vso[build.updatebuildnumber]{version.FullSemver}.{buildId}");
});
});
Task("GitVersion")
.Does(() => {
version = GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true,
UpdateAssemblyInfoFilePath = @"SolutionInfo.cs"
});
});
Task("UpdateDnnManifests")
.IsDependentOn("GitVersion")
.DoesForEach(GetFiles("**/*.dnn"), (file) =>
{
var transformFile = File(System.IO.Path.GetTempFileName());
FileAppendText(transformFile, GetXdtTransformation());
XdtTransformConfig(file, transformFile, file);
});
public string GetBuildNumber()
{
return version.LegacySemVerPadded;
}
public string GetProductVersion()
{
return version.MajorMinorPatch;
}
public string GetXdtTransformation()
{
var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}";
return $@"<?xml version=""1.0""?>
<dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform"">
<packages>
<package version=""{versionString}""
xdt:Transform=""SetAttributes(version)""
xdt:Locator=""Condition([not(@version)])"" />
</packages>
</dotnetnuke>";
}
| #addin Cake.XdtTransform
#addin "Cake.FileHelpers"
#tool "nuget:?package=GitVersion.CommandLine&prerelease"
GitVersion version;
Task("BuildServerSetVersion")
.Does(() => {
GitVersion(new GitVersionSettings {
OutputType = GitVersionOutput.BuildServer
});
});
Task("GitVersion")
.Does(() => {
version = GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true,
UpdateAssemblyInfoFilePath = @"SolutionInfo.cs"
});
});
Task("UpdateDnnManifests")
.IsDependentOn("GitVersion")
.DoesForEach(GetFiles("**/*.dnn"), (file) =>
{
var transformFile = File(System.IO.Path.GetTempFileName());
FileAppendText(transformFile, GetXdtTransformation());
XdtTransformConfig(file, transformFile, file);
});
public string GetBuildNumber()
{
return version.LegacySemVerPadded;
}
public string GetProductVersion()
{
return version.MajorMinorPatch;
}
public string GetXdtTransformation()
{
var versionString = $"{version.Major.ToString("00")}.{version.Minor.ToString("00")}.{version.Patch.ToString("00")}";
return $@"<?xml version=""1.0""?>
<dotnetnuke xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform"">
<packages>
<package version=""{versionString}""
xdt:Transform=""SetAttributes(version)""
xdt:Locator=""Condition([not(@version)])"" />
</packages>
</dotnetnuke>";
}
| mit | C# |
6ebbaa601adaeaa96c1cbb154f07bb82188d0291 | Update TypedURL.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.TypedURLs/TypedURL.cs | RegistryPlugin.TypedURLs/TypedURL.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.TypedURLs
{
public class TypedURL:IValueOut
{
public TypedURL(string url, DateTimeOffset? timestamp, string slack)
{
Url = url;
Timestamp = timestamp;
Slack = slack;
}
public DateTimeOffset? Timestamp { get; }
public string Url { get; }
public string Slack { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => Url;
public string BatchValueData2 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => $"Slack: {Slack}";
}
}
| using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.TypedURLs
{
public class TypedURL:IValueOut
{
public TypedURL(string url, DateTimeOffset? timestamp, string slack)
{
Url = url;
Timestamp = timestamp;
Slack = slack;
}
public DateTimeOffset? Timestamp { get; }
public string Url { get; }
public string Slack { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => Url;
public string BatchValueData2 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} ";
public string BatchValueData3 => $"Slack: {Slack}";
}
} | mit | C# |
5e6cdbe8fb517fda7c68a210ab1bcbbfac198354 | add missing using | zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos | source/Cosmos.System2/FileSystem/VFS/FileSystemManager.cs | source/Cosmos.System2/FileSystem/VFS/FileSystemManager.cs | using System;
using System.Collections.Generic;
namespace Cosmos.System.FileSystem.VFS
{
public static class FileSystemManager
{
private static List<FileSystemFactory> registeredFileSystems =
new List<FileSystemFactory>() {
new FAT.FatFileSystemFactory(),
new ISO9660.ISO9660FileSystemFactory()
};
public static List<FileSystemFactory> RegisteredFileSystems { get {
return registeredFileSystems;
}}
public static bool Register(FileSystemFactory factory)
{
foreach (var item in registeredFileSystems)
{
if(item.Name == factory.Name)
{
return false;
}
}
registeredFileSystems.Add(factory);
return true;
}
public static bool Remove(FileSystemFactory factory)
{
return Remove(factory.Name);
}
public static bool Remove(string factoryName)
{
foreach (var item in registeredFileSystems)
{
if(item.Name == factory.Name)
{
registeredFileSystems.Remove(item);
return true;
}
}
return false;
}
}
} | using System;
namespace Cosmos.System.FileSystem.VFS
{
public static class FileSystemManager
{
private static List<FileSystemFactory> registeredFileSystems =
new List<FileSystemFactory>() {
new FAT.FatFileSystemFactory(),
new ISO9660.ISO9660FileSystemFactory()
};
public static List<FileSystemFactory> RegisteredFileSystems { get {
return registeredFileSystems;
}}
public static bool Register(FileSystemFactory factory)
{
foreach (var item in registeredFileSystems)
{
if(item.Name == factory.Name)
{
return false;
}
}
registeredFileSystems.Add(factory);
return true;
}
public static bool Remove(FileSystemFactory factory)
{
return Remove(factory.Name);
}
public static bool Remove(string factoryName)
{
foreach (var item in registeredFileSystems)
{
if(item.Name == factory.Name)
{
registeredFileSystems.Remove(item);
return true;
}
}
return false;
}
}
} | bsd-3-clause | C# |
e1379c4d81b7b02cf3e48cf9bd718c307215e4bb | Fix constructor | lukencode/FluentEmail,lukencode/FluentEmail | src/Renderers/FluentEmail.Liquid/LiquidRendererOptions.cs | src/Renderers/FluentEmail.Liquid/LiquidRendererOptions.cs | using System;
using System.Text.Encodings.Web;
using Fluid;
using Microsoft.Extensions.FileProviders;
namespace FluentEmail.Liquid
{
public class LiquidRendererOptions
{
/// <summary>
/// Allows configuring template context before running the template. Parameters are context that has been
/// prepared and the model that is going to be used.
/// </summary>
/// <remarks>
/// This API creates dependency on Fluid.
/// </remarks>
public Action<TemplateContext, object>? ConfigureTemplateContext { get; set; }
/// <summary>
/// Text encoder to use. Defaults to <see cref="HtmlEncoder"/>.
/// </summary>
public TextEncoder TextEncoder { get; set; } = HtmlEncoder.Default;
/// <summary>
/// File provider to use, used when resolving references in templates, like master layout.
/// </summary>
public IFileProvider? FileProvider { get; set; }
/// <summary>
/// Set custom Template Options for Fluid
/// </summary>
public TemplateOptions TemplateOptions { get; set; } = new TemplateOptions();
}
}
| using System;
using System.Text.Encodings.Web;
using Fluid;
using Microsoft.Extensions.FileProviders;
namespace FluentEmail.Liquid
{
public class LiquidRendererOptions
{
/// <summary>
/// Allows configuring template context before running the template. Parameters are context that has been
/// prepared and the model that is going to be used.
/// </summary>
/// <remarks>
/// This API creates dependency on Fluid.
/// </remarks>
public Action<TemplateContext, object>? ConfigureTemplateContext { get; set; }
/// <summary>
/// Text encoder to use. Defaults to <see cref="HtmlEncoder"/>.
/// </summary>
public TextEncoder TextEncoder { get; set; } = HtmlEncoder.Default;
/// <summary>
/// File provider to use, used when resolving references in templates, like master layout.
/// </summary>
public IFileProvider? FileProvider { get; set; }
/// <summary>
/// Set custom Template Options for Fluid
/// </summary>
public TemplateOptions TemplateOptions { get; set; } = new();
}
} | mit | C# |
7788d0fea4f947296e13858a5a9dba20d8b8309b | remove blank lines | YoloDev/elephanet,jmkelly/elephanet,YoloDev/elephanet,jmkelly/elephanet | Elephanet/Queryable.cs | Elephanet/Queryable.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Elephanet
{
public interface IJsonbQueryable<T>: IOrderedQueryable<T>
{
string CommandText();
}
public interface IJsonbQueryable: IOrderedQueryable
{
string CommandText();
}
public class JsonbQueryable<T> : IJsonbQueryable<T>
{
IJsonbQueryProvider _provider;
Expression _expression;
public JsonbQueryable(IJsonbQueryProvider provider) {
if (provider == null) {
throw new ArgumentNullException("provider");
}
_provider = provider;
_expression = Expression.Constant(this);
}
public JsonbQueryable(IJsonbQueryProvider provider, Expression expression) {
if (provider == null) {
throw new ArgumentNullException("provider");
}
if (expression == null) {
throw new ArgumentNullException("expression");
}
if (!typeof(IQueryable<T>).IsAssignableFrom(expression.Type)) {
throw new ArgumentOutOfRangeException("expression");
}
_provider = provider;
_expression = expression;
}
Expression IQueryable.Expression {
get { return _expression; }
}
Type IQueryable.ElementType {
get { return typeof(T); }
}
public IEnumerator<T> GetEnumerator() {
return ((IEnumerable<T>)_provider.Execute(_expression)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)_provider.Execute(_expression)).GetEnumerator();
}
public string CommandText()
{
return _provider.GetQueryText(_expression);
}
IQueryProvider IQueryable.Provider
{
get { return (IJsonbQueryProvider)_provider; }
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Elephanet
{
public interface IJsonbQueryable<T>: IOrderedQueryable<T>
{
string CommandText();
}
public interface IJsonbQueryable: IOrderedQueryable
{
string CommandText();
}
public class JsonbQueryable<T> : IJsonbQueryable<T>
{
IJsonbQueryProvider _provider;
Expression _expression;
public JsonbQueryable(IJsonbQueryProvider provider) {
if (provider == null) {
throw new ArgumentNullException("provider");
}
_provider = provider;
_expression = Expression.Constant(this);
}
public JsonbQueryable(IJsonbQueryProvider provider, Expression expression) {
if (provider == null) {
throw new ArgumentNullException("provider");
}
if (expression == null) {
throw new ArgumentNullException("expression");
}
if (!typeof(IQueryable<T>).IsAssignableFrom(expression.Type)) {
throw new ArgumentOutOfRangeException("expression");
}
_provider = provider;
_expression = expression;
}
Expression IQueryable.Expression {
get { return _expression; }
}
Type IQueryable.ElementType {
get { return typeof(T); }
}
public IEnumerator<T> GetEnumerator() {
return ((IEnumerable<T>)_provider.Execute(_expression)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)_provider.Execute(_expression)).GetEnumerator();
}
public string CommandText()
{
return _provider.GetQueryText(_expression);
}
IQueryProvider IQueryable.Provider
{
get { return (IJsonbQueryProvider)_provider; }
}
}
}
| mit | C# |
3af701e139a09a51ba060d85d7436b919b8871d1 | Increase memory limit | takenet/blip-sdk-csharp | src/Take.Blip.Builder/Hosting/ConventionsConfiguration.cs | src/Take.Blip.Builder/Hosting/ConventionsConfiguration.cs | using System;
namespace Take.Blip.Builder.Hosting
{
public class ConventionsConfiguration : IConfiguration
{
public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);
public virtual string RedisStorageConfiguration => "localhost";
public virtual int RedisDatabase => 0;
public virtual int MaxTransitionsByInput => 10;
public virtual int TraceQueueBoundedCapacity => 512;
public virtual int TraceQueueMaxDegreeOfParallelism => 512;
public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);
public virtual string RedisKeyPrefix => "builder";
public bool ContactCacheEnabled => true;
public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);
public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);
public int ExecuteScriptLimitRecursion => 50;
public int ExecuteScriptMaxStatements => 1000;
public long ExecuteScriptLimitMemory => 100_000_000; // Nearly 100MB
public long ExecuteScriptLimitMemoryWarning => 10_000_000; // Nearly 10MB
public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
}
} | using System;
namespace Take.Blip.Builder.Hosting
{
public class ConventionsConfiguration : IConfiguration
{
public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);
public virtual string RedisStorageConfiguration => "localhost";
public virtual int RedisDatabase => 0;
public virtual int MaxTransitionsByInput => 10;
public virtual int TraceQueueBoundedCapacity => 512;
public virtual int TraceQueueMaxDegreeOfParallelism => 512;
public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);
public virtual string RedisKeyPrefix => "builder";
public bool ContactCacheEnabled => true;
public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);
public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);
public int ExecuteScriptLimitRecursion => 50;
public int ExecuteScriptMaxStatements => 1000;
public long ExecuteScriptLimitMemory => 1_000_000; // Nearly 1MB or 1 << 20
public long ExecuteScriptLimitMemoryWarning => 500_000; // Nearly 512KB or 1 << 19
public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
}
} | apache-2.0 | C# |
57b5068dd25556f0c832db5ca62fe9cae7706a53 | Fix - Corretta Tipologia | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Classi/Condivise/Tipologia.cs | src/backend/SO115App.Models/Classi/Condivise/Tipologia.cs | //-----------------------------------------------------------------------
// <copyright file="Tipologia.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.Models.Classi.Condivise;
namespace SO115App.API.Models.Classi.Condivise
{
public class Tipologia
{
public Tipologia(string codice, string descrizione, string icona)
{
this.Codice = codice;
this.Descrizione = descrizione;
this.Icona = icona;
}
/// <summary>
/// Codice della Tipologia
/// </summary>
public string Codice { get; set; }
/// <summary>
/// Descrizione Tipologia
/// </summary>
public string Descrizione { get; set; }
/// <summary>
/// Indica la tipologia di luogo nel quale è avvenuto il fatto (Es. Abitazione)
/// </summary>
public TipologiaLuogoEvento TipoLuogoEvento { get; set; }
/// <summary>
/// Classe Icona Fontawsome corrispondente alla tipologia
/// </summary>
public string Icona { get; set; }
/// <summary>
/// Definisce la categoria della Tipologia
/// </summary>
public string Categoria { get; set; }
/// <summary>
/// Indica se questa tipologia sarà presente nei "preferiti" nella sezione Filtri
/// </summary>
public bool Star { get; set; }
/// <summary>
/// Indica l'incendio è boschivo
/// </summary>
public bool Boschivo { get; set; }
public MatriceAdeguatezzaMezzo AdeguatezzaMezzo { get; set; }
public int OpportunitaSganciamento { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="Tipologia.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
namespace SO115App.API.Models.Classi.Condivise
{
public class Tipologia
{
public Tipologia(string codice, string descrizione, string icona)
{
this.Codice = codice;
this.Descrizione = descrizione;
this.Icona = icona;
}
/// <summary>
/// Codice della Tipologia
/// </summary>
public string Codice { get; set; }
/// <summary>
/// Descrizione Tipologia
/// </summary>
public string Descrizione { get; set; }
/// <summary>
/// Indica la tipologia di luogo nel quale è avvenuto il fatto (Es. Abitazione)
/// </summary>
public TipologiaLuogoEvento TipoLuogoEvento { get; set; }
/// <summary>
/// Classe Icona Fontawsome corrispondente alla tipologia
/// </summary>
public string Icona { get; set; }
/// <summary>
/// Definisce la categoria della Tipologia
/// </summary>
public string Categoria { get; set; }
/// <summary>
/// Indica se questa tipologia sarà presente nei "preferiti" nella sezione Filtri
/// </summary>
public bool Star { get; set; }
/// <summary>
/// Indica l'incendio è boschivo
/// </summary>
public bool Boschivo { get; set; }
}
}
| agpl-3.0 | C# |
f22d1053321b768ac884b5f8ef9ec145f6c79186 | Fix the "Validation failed: Weight is not a number" error | EasyPost/easypost-csharp,EasyPost/easypost-csharp | EasyPost/Client.cs | EasyPost/Client.cs | using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
namespace EasyPost {
public class Client {
public string version;
internal RestClient client;
internal ClientConfiguration configuration;
public Client(ClientConfiguration clientConfiguration) {
System.Net.ServicePointManager.SecurityProtocol = Security.GetProtocol();
if (clientConfiguration == null) throw new ArgumentNullException("clientConfiguration");
configuration = clientConfiguration;
client = new RestClient(clientConfiguration.ApiBase);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
version = info.FileVersion;
}
public IRestResponse Execute(Request request) {
return client.Execute(PrepareRequest(request));
}
public T Execute<T>(Request request) where T : new() {
RestResponse<T> response = (RestResponse<T>)client.Execute<T>(PrepareRequest(request));
int StatusCode = Convert.ToInt32(response.StatusCode);
if (StatusCode > 399) {
try {
Dictionary<string, Dictionary<string, object>> Body = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(response.Content);
throw new HttpException(StatusCode, (string)Body["error"]["message"], (string)Body["error"]["code"]);
} catch {
throw new HttpException(StatusCode, "RESPONSE.PARSE_ERROR", response.Content);
}
}
return response.Data;
}
internal RestRequest PrepareRequest(Request request) {
RestRequest restRequest = (RestRequest)request;
restRequest.AddHeader("user_agent", string.Concat("EasyPost/v2 CSharp/", version));
restRequest.AddHeader("authorization", "Bearer " + this.configuration.ApiKey);
restRequest.AddHeader("content_type", "application/x-www-form-urlencoded");
return restRequest;
}
}
}
| using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace EasyPost {
public class Client {
public string version;
internal RestClient client;
internal ClientConfiguration configuration;
public Client(ClientConfiguration clientConfiguration) {
System.Net.ServicePointManager.SecurityProtocol = Security.GetProtocol();
if (clientConfiguration == null) throw new ArgumentNullException("clientConfiguration");
configuration = clientConfiguration;
client = new RestClient(clientConfiguration.ApiBase);
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
version = info.FileVersion;
}
public IRestResponse Execute(Request request) {
return client.Execute(PrepareRequest(request));
}
public T Execute<T>(Request request) where T : new() {
RestResponse<T> response = (RestResponse<T>)client.Execute<T>(PrepareRequest(request));
int StatusCode = Convert.ToInt32(response.StatusCode);
if (StatusCode > 399) {
try {
Dictionary<string, Dictionary<string, object>> Body = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(response.Content);
throw new HttpException(StatusCode, (string)Body["error"]["message"], (string)Body["error"]["code"]);
} catch {
throw new HttpException(StatusCode, "RESPONSE.PARSE_ERROR", response.Content);
}
}
return response.Data;
}
internal RestRequest PrepareRequest(Request request) {
RestRequest restRequest = (RestRequest)request;
restRequest.AddHeader("user_agent", string.Concat("EasyPost/v2 CSharp/", version));
restRequest.AddHeader("authorization", "Bearer " + this.configuration.ApiKey);
restRequest.AddHeader("content_type", "application/x-www-form-urlencoded");
return restRequest;
}
}
} | mit | C# |
148f68b7bd0f765a56122ae66fc2bc6ec31b624d | Make cookie valid for 30 days. | gyrosworkshop/Wukong,gyrosworkshop/Wukong | Wukong/Controllers/AuthController.cs | Wukong/Controllers/AuthController.cs | using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true,
ExpiresUtc = System.DateTime.UtcNow.AddDays(30)
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
} | using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
} | mit | C# |
391eb2e95adaa0e6dbd14358c7b11babb13df98c | Print abbreviated quote | nja/keel,nja/keel | Keel/Builtins/Print.cs | Keel/Builtins/Print.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Keel.Objects;
using System.IO;
namespace Keel.Builtins
{
public class Print : Builtin
{
public Print()
: base("PRINT", "X")
{ }
public override LispObject Apply(Cons argumentValues, LispEnvironment env)
{
Console.WriteLine(PrintObject(argumentValues.Car));
return argumentValues.Car;
}
public static string PrintObject(LispObject x)
{
var sb = new StringBuilder();
PrintObject(x, sb);
return sb.ToString();
}
private static void PrintObject(LispObject x, StringBuilder output)
{
if (x.IsAtom)
{
output.Append(x.ToString());
}
else if (Car.Of(x) is Symbol
&& ((Symbol)Car.Of(x)).SameName("QUOTE")
&& !Cdr.Of(x).IsNil
&& Cdr.Of(Cdr.Of(x)).IsNil)
{
output.Append("'");
PrintObject(Car.Of(Cdr.Of(x)), output);
}
else
{
output.Append("(");
PrintObject(Car.Of(x), output);
PrintCdr(Cdr.Of(x), output);
output.Append(")");
}
}
private static void PrintCdr(LispObject x, StringBuilder output)
{
if (x.IsNil)
{
return;
}
else if (x.IsAtom)
{
output.Append(" . " + x);
}
else
{
output.Append(" ");
PrintObject(Car.Of(x), output);
PrintCdr(Cdr.Of(x), output);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Keel.Objects;
using System.IO;
namespace Keel.Builtins
{
public class Print : Builtin
{
public Print()
: base("PRINT", "X")
{ }
public override LispObject Apply(Cons argumentValues, LispEnvironment env)
{
Console.WriteLine(PrintObject(argumentValues.Car));
return argumentValues.Car;
}
public static string PrintObject(LispObject x)
{
var sb = new StringBuilder();
PrintObject(x, sb);
return sb.ToString();
}
private static void PrintObject(LispObject x, StringBuilder output)
{
if (x.IsAtom)
{
output.Append(x.ToString());
}
else
{
output.Append("(");
PrintObject(Car.Of(x), output);
PrintCdr(Cdr.Of(x), output);
output.Append(")");
}
}
private static void PrintCdr(LispObject x, StringBuilder output)
{
if (x.IsNil)
{
return;
}
else if (x.IsAtom)
{
output.Append(" . " + x);
}
else
{
output.Append(" ");
PrintObject(Car.Of(x), output);
PrintCdr(Cdr.Of(x), output);
}
}
}
}
| mit | C# |
1442fefd15cb10fd78127c841b3a3ba8b0c0925a | Check assemblies reference System.Net.Http v4.0 | github/VisualStudio,github/VisualStudio,github/VisualStudio | test/GitHub.VisualStudio.UnitTests/GitHubAssemblyTests.cs | test/GitHub.VisualStudio.UnitTests/GitHubAssemblyTests.cs | using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[Theory]
public void GitHub_Assembly_Should_Not_Reference_System_Net_Http_Above_4_0(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
if (referencedAssembly.Name == "System.Net.Http")
{
Assert.That(referencedAssembly.Version, Is.EqualTo(new Version("4.0.0.0")));
}
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
| using System.IO;
using System.Reflection;
using NUnit.Framework;
public class GitHubAssemblyTests
{
[Theory]
public void GitHub_Assembly_Should_Not_Reference_DesignTime_Assembly(string assemblyFile)
{
var asm = Assembly.LoadFrom(assemblyFile);
foreach (var referencedAssembly in asm.GetReferencedAssemblies())
{
Assert.That(referencedAssembly.Name, Does.Not.EndWith(".DesignTime"),
"DesignTime assemblies should be embedded not referenced");
}
}
[DatapointSource]
string[] GitHubAssemblies => Directory.GetFiles(AssemblyDirectory, "GitHub.*.dll");
string AssemblyDirectory => Path.GetDirectoryName(GetType().Assembly.Location);
}
| mit | C# |
c933bf70dfc3487d5013fef6ab3d4f87dd000a2b | Add unit test for annual calendar | lukeryannetnz/quartznet-dynamodb,lukeryannetnz/quartznet-dynamodb | src/QuartzNET-DynamoDB.Tests/Unit/CalendarSerialisationTests.cs | src/QuartzNET-DynamoDB.Tests/Unit/CalendarSerialisationTests.cs | using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
/// <summary>
/// Tests that the description property of the base calendar type serialises and deserialises correctly.
/// </summary>
/// <returns>The calendar description.</returns>
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
/// <summary>
/// Tests that the excluded days property of the annual calendar serialises and deserialises correctly.
/// </summary>
[Fact]
[Trait("Category", "Unit")]
public void Annual()
{
var importantDate = new DateTime(2015, 04, 02);
AnnualCalendar cal = new AnnualCalendar();
cal.SetDayExcluded(DateTime.Today, true);
cal.SetDayExcluded(importantDate, true);
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(DateTime.Today));
Assert.True(((AnnualCalendar)deserialised.Calendar).IsDayExcluded(importantDate));
}
}
}
| using System;
using Quartz.Impl.Calendar;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
/// <summary>
/// Tests the DynamoCalendar serialisation for all quartz derived calendar types.
/// </summary>
public class CalendarSerialisationTests
{
[Fact]
[Trait("Category", "Unit")]
public void BaseCalendarDescription()
{
BaseCalendar cal = new BaseCalendar() { Description = "Hi mum" };
var sut = new DynamoCalendar("test", cal);
var serialised = sut.ToDynamo();
var deserialised = new DynamoCalendar(serialised);
Assert.Equal(sut.Description, deserialised.Description);
}
}
}
| apache-2.0 | C# |
79500538624b301b1bd01744de2e15488b8bfd18 | Add logging | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Support.Web/App_Start/Startup.auth.cs | src/SFA.DAS.EmployerUsers.Support.Web/App_Start/Startup.auth.cs | using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Support.Shared.SiteConnection;
using System.Web.Mvc;
namespace SFA.DAS.EmployerUsers.Support.Web
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
var ioc = DependencyResolver.Current;
var siteValidatorSettings = ioc.GetService<ISiteValidatorSettings>();
var logger = ioc.GetService<ILog>();
logger.Info($"ConfigreAuth Audience:{siteValidatorSettings.Audience} Tenant:{siteValidatorSettings.Tenant}");
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudiences = siteValidatorSettings.Audience.Split(','),
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
},
Tenant = siteValidatorSettings.Tenant
});
}
}
} | using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using SFA.DAS.Support.Shared.SiteConnection;
using System.Web.Mvc;
namespace SFA.DAS.EmployerUsers.Support.Web
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
var ioc = DependencyResolver.Current;
var siteValidatorSettings = ioc.GetService<ISiteValidatorSettings>();
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudiences = siteValidatorSettings.Audience.Split(','),
RoleClaimType = "roles"
},
Tenant = siteValidatorSettings.Tenant
});
}
}
} | mit | C# |
abd162a8e09294e3669ab54ee0fc7165919ccebf | Add some explanatory comments | cityindex-attic/RESTful-Webservice-Schema,cityindex-attic/RESTful-Webservice-Schema,cityindex-attic/RESTful-Webservice-Schema | src/JsonSchemaGeneration/Generator.cs | src/JsonSchemaGeneration/Generator.cs | using JsonSchemaGeneration.JsonSchemaDTO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonSchemaGeneration
{
public class Generator
{
public string GenerateJsonSchema(XmlDocSource xmlDocSource)
{
//Checks that DTOs all have valid XML comments
XmlDocUtils.EnsureXmlDocsAreValid(xmlDocSource);
//Checks that each DTO type can be documented
new Auditor().AuditTypes(xmlDocSource);
//Creates Jschema for all DTO types where it can find XML docs
//NB, Auditor errors if any of the DTOs don't have XML docs
return new JsonSchemaDtoEmitter().EmitDtoJson(xmlDocSource);
}
public string GenerateSmd(XmlDocSource xmlDocSource, string jsonSchema)
{
var smdEmitter = new WcfSMD.Emitter();
var smd = smdEmitter.EmitSmdJson(xmlDocSource, true, (JObject) JsonConvert.DeserializeObject(jsonSchema));
JObject smdObj = (JObject) JsonConvert.DeserializeObject(smd);
JObject streamingObj = (JObject) JsonConvert.DeserializeObject(xmlDocSource.StreamingJsonPatch);
smdObj["services"]["streaming"] = streamingObj;
smd = smdObj.ToString(Formatting.Indented);
return smd;
}
}
}
| using JsonSchemaGeneration.JsonSchemaDTO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonSchemaGeneration
{
public class Generator
{
public string GenerateJsonSchema(XmlDocSource xmlDocSource)
{
XmlDocUtils.EnsureXmlDocsAreValid(xmlDocSource);
new Auditor().AuditTypes(xmlDocSource);
return new JsonSchemaDtoEmitter().EmitDtoJson(xmlDocSource);
}
public string GenerateSmd(XmlDocSource xmlDocSource, string jsonSchema)
{
var smdEmitter = new WcfSMD.Emitter();
var smd = smdEmitter.EmitSmdJson(xmlDocSource, true, (JObject) JsonConvert.DeserializeObject(jsonSchema));
JObject smdObj = (JObject) JsonConvert.DeserializeObject(smd);
JObject streamingObj = (JObject) JsonConvert.DeserializeObject(xmlDocSource.StreamingJsonPatch);
smdObj["services"]["streaming"] = streamingObj;
smd = smdObj.ToString(Formatting.Indented);
return smd;
}
}
}
| apache-2.0 | C# |
b07ae078a2a456697b44593965cbc6eed01d7091 | Rollback feature added | PowerMogli/Rabbit.Db | src/Micro+/Entity/EntityExtensions.cs | src/Micro+/Entity/EntityExtensions.cs | using System.Data;
using MicroORM.Base;
using MicroORM.Caching;
using MicroORM.Storage;
namespace MicroORM.Entity
{
public static class EntityExtensions
{
public static void Load<TEntity>(this TEntity entity) where TEntity : Entity, new()
{
EntityInfo entityInfo = EntityInfoCacheManager.GetEntityInfo(entity);
if (entityInfo.EntityState == EntityState.Loaded) return;
string connectionString = Registrar<string>.GetFor(entity.GetType());
DbEngine dbEngine = Registrar<DbEngine>.GetFor(entity.GetType());
using (IDbSession entitySession = new DbSession(connectionString, dbEngine))
{
entitySession.Load(entity);
entityInfo.EntityState = EntityState.Loaded;
entityInfo.ComputeSnapshot(entity);
}
}
public static bool PersistChanges<TEntity>(this TEntity entity, bool delete = false) where TEntity : Entity
{
string connectionString = Registrar<string>.GetFor(entity.GetType());
DbEngine dbEngine = Registrar<DbEngine>.GetFor(entity.GetType());
EntityInfo entityInfo = EntityInfoCacheManager.GetEntityInfo(entity);
using (IDbSession dbSession = new DbSession(connectionString, dbEngine))
{
try
{
using (IDbTransaction transaction = dbSession.BeginTransaction(IsolationLevel.ReadUncommitted))
{
if (dbSession.PersistChanges(entity, delete) == false) return false;
transaction.Commit();
entityInfo.MergeChanges();
return true;
}
}
catch
{
entityInfo.ClearChanges();
}
return false;
}
}
}
}
| using System.Data;
using MicroORM.Base;
using MicroORM.Storage;
namespace MicroORM.Entity
{
public static class EntityExtensions
{
public static void Load<TEntity>(this TEntity entity) where TEntity : Entity, new()
{
if (entity.EntityState == EntityState.Loaded) return;
string connectionString = Registrar<string>.GetFor(entity.GetType());
DbEngine dbEngine = Registrar<DbEngine>.GetFor(entity.GetType());
using (IDbSession entitySession = new DbSession(connectionString, dbEngine))
{
entitySession.Load(entity);
entity.EntityState = EntityState.Loaded;
}
}
public static void PersistChanges<TEntity>(this TEntity entity) where TEntity : Entity
{
string connectionString = Registrar<string>.GetFor(entity.GetType());
DbEngine dbEngine = Registrar<DbEngine>.GetFor(entity.GetType());
using (IDbSession dbSession = new DbSession(connectionString, dbEngine))
{
using (IDbTransaction transaction = dbSession.BeginTransaction(IsolationLevel.ReadUncommitted))
{
dbSession.PersistChanges(entity);
transaction.Commit();
}
}
}
}
}
| apache-2.0 | C# |
056e7c61508b40fb2894e4f6fe7daff6b66371d5 | Update SettingHeightAllRows.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/RowsColumns/HeightAndWidth/SettingHeightAllRows.cs | Examples/CSharp/RowsColumns/HeightAndWidth/SettingHeightAllRows.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingHeightAllRows
{
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);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the height of all rows in the worksheet to 15
worksheet.Cells.StandardHeight = 15;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingHeightAllRows
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the height of all rows in the worksheet to 15
worksheet.Cells.StandardHeight = 15;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
} | mit | C# |
b50f93d07d2163fb70b183e32a54a2eae1921379 | Debug try catch added to values controller | KitKare/KitKareService,KitKare/KitKareService | KitKare.Server/Controllers/ValuesController.cs | KitKare.Server/Controllers/ValuesController.cs | using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
try
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
catch (Exception e)
{
return new string[] { e.Message };
}
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| using KitKare.Data.Models;
using KitKare.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper.QueryableExtensions;
using KitKare.Server.ViewModels;
namespace KitKare.Server.Controllers
{
public class ValuesController : ApiController
{
private IRepository<User> users;
public ValuesController(IRepository<User> users)
{
this.users = users;
}
// GET api/values
public IEnumerable<string> Get()
{
var user = this.users.All().ProjectTo<ProfileViewModel>().FirstOrDefault();
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| mit | C# |
5b852c74288ad0a2f1e73c5ee20d87af4d870a7d | add self operator | ketoo/NFActor | NFActor/NFBehaviour.cs | NFActor/NFBehaviour.cs | //-----------------------------------------------------------------------
// <copyright file="NFBehaviour.cs">
// Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFActor>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.ObjectModel;
namespace NFrame
{
public class NFBehaviour : IDisposable
{
public virtual void Dispose()
{
}
public virtual void Init(){}
public virtual void AfterInit() {}
public virtual void BeforeShut() {}
public virtual void Shut() {}
public virtual void Execute() {}
public virtual void SetSelf(NFIDENTID xID) { mxID = xID; }
public virtual NFIDENTID Self() { return mxID; }
private NFIDENTID mxID = new NFIDENTID();
}
}
| //-----------------------------------------------------------------------
// <copyright file="NFBehaviour.cs">
// Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFActor>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.ObjectModel;
namespace NFrame
{
public class NFBehaviour : IDisposable
{
public virtual void Dispose()
{
}
public virtual void Init(){}
public virtual void AfterInit() {}
public virtual void BeforeShut() {}
public virtual void Shut() {}
public virtual void Execute() {}
public virtual NFIDENTID Self() { return new NFIDENTID(); }
//event
//ThreadPool
}
}
| apache-2.0 | C# |
533a9c3a0cfd6ef2fa7ffdaa5609df02a92cf6bd | Update GrahamBeer.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/GrahamBeer.cs | src/Firehose.Web/Authors/GrahamBeer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GrahamBeer : IAmACommunityMember
{
public string FirstName => "Graham";
public string LastName => "Beer";
public string ShortBioOrTagLine => "System Engineer";
public string StateOrRegion => "UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Gbeer7";
public string GravatarHash => "27d2592f62f63479cac9314da41f9af1";
public string GitHubHandle => "Gbeer7";
public GeoPosition Position => new GeoPosition(47.643417, -122.126083);
public Uri WebSite => new Uri("https://graham-beer.github.io/#blog");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://graham-beer.github.io/feed.xml"); }
}
public string GitHubHandle => "Graham-Beer";
public GeoPosition Position => new GeoPosition(39.0913089, -77.5440391);
}
}
| public class GrahamBeer : IAmACommunityMember
{
public string FirstName => "Graham";
public string LastName => "Beer";
public string ShortBioOrTagLine => "System Engineer";
public string StateOrRegion => "UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "Gbeer7";
public string GravatarHash => "27d2592f62f63479cac9314da41f9af1";
public string GitHubHandle => "Gbeer7";
public GeoPosition Position => new GeoPosition(47.643417, -122.126083);
public Uri WebSite => new Uri("https://graham-beer.github.io/#blog");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://graham-beer.github.io/feed.xml"); } }
}
| mit | C# |
9da139fdc07438fc45563e28fab3016d7ab78b60 | Add copyright header to new file | tijoytom/corert,gregkalapos/corert,botaberg/corert,tijoytom/corert,gregkalapos/corert,krytarowski/corert,shrah/corert,yizhang82/corert,tijoytom/corert,gregkalapos/corert,shrah/corert,krytarowski/corert,botaberg/corert,shrah/corert,yizhang82/corert,yizhang82/corert,botaberg/corert,gregkalapos/corert,krytarowski/corert,tijoytom/corert,krytarowski/corert,shrah/corert,botaberg/corert,yizhang82/corert | src/ILCompiler.DependencyAnalysisFramework/src/IDependencyNode.cs | src/ILCompiler.DependencyAnalysisFramework/src/IDependencyNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace ILCompiler.DependencyAnalysisFramework
{
public interface IDependencyNode
{
bool Marked
{
get;
}
}
public interface IDependencyNode<DependencyContextType> : IDependencyNode
{
bool InterestingForDynamicDependencyAnalysis
{
get;
}
bool HasDynamicDependencies
{
get;
}
bool HasConditionalStaticDependencies
{
get;
}
bool StaticDependenciesAreComputed
{
get;
}
IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> GetStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ILCompiler.DependencyAnalysisFramework
{
public interface IDependencyNode
{
bool Marked
{
get;
}
}
public interface IDependencyNode<DependencyContextType> : IDependencyNode
{
bool InterestingForDynamicDependencyAnalysis
{
get;
}
bool HasDynamicDependencies
{
get;
}
bool HasConditionalStaticDependencies
{
get;
}
bool StaticDependenciesAreComputed
{
get;
}
IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> GetStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context);
IEnumerable<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context);
}
}
| mit | C# |
042bb9bba00f6a68279a0867344c421fb2449f03 | Change property types to better match up with Boo syntax | eatdrinksleepcode/casper,eatdrinksleepcode/casper | MSBuild/MSBuild.cs | MSBuild/MSBuild.cs | using System.Collections.Generic;
using System.Collections;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public IList Targets { get; set; }
public IDictionary Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var propertyName in Properties.Keys) {
args.Add("/p:" + propertyName + "=" + Properties[propertyName]);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
| using System.Collections.Generic;
namespace Casper {
public class MSBuild : TaskBase {
public string WorkingDirectory { get; set; }
public string ProjectFile { get; set; }
public string[] Targets { get; set; }
public IDictionary<string, string> Properties { get; set; }
public override void Execute() {
List<string> args = new List<string>();
if (null != ProjectFile) {
args.Add(ProjectFile);
}
if (null != Targets) {
args.Add("/t:" + string.Join(";", Targets));
}
if (null != Properties) {
foreach (var entry in Properties) {
args.Add("/p:" + entry.Key + "=" + entry.Value);
}
}
var exec = new Exec {
WorkingDirectory = WorkingDirectory,
Executable = "xbuild",
Arguments = string.Join(" ", args),
};
exec.Execute();
}
}
}
| mit | C# |
d7f47a49d6087e56e3f8106e5a67f7d1023b8fb3 | Make Regex readonly | Eleven19/SSISManagement,Eleven19/SSISManagement | src/SSISManagement/Data/Catalog/Parameters/SsisParameterMapper.cs | src/SSISManagement/Data/Catalog/Parameters/SsisParameterMapper.cs | using System;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using Insight.Database.Mapping;
namespace SqlServer.Management.IntegrationServices.Data.Catalog.Parameters
{
/// <summary>
/// A parameter mapper which changes the SSIS style parameters to CamelCase.
/// </summary>
internal class SsisParameterMapper : IParameterMapper
{
private static readonly Regex RenameRegex =
new Regex(@"(?<id>[A-Z,a-z,0-9]+)(?<underscore>_)+");
public string MapParameter(Type type, IDbCommand command, IDataParameter parameter)
{
var connectionString = command.Connection.ConnectionString;
var commandText = command.CommandText ?? string.Empty;
if (ConnectionStrings.IsSsisConnectionString(connectionString)
// don't change casing of the ReturnValue parameter since Insight.Database makes use of it
&& parameter.Direction != ParameterDirection.ReturnValue
)
{
Console.WriteLine(command.CommandText);
var member = RenameRegex.Replace(parameter.ParameterName, match =>
{
var id = match.Groups["id"].Value;
return System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase(id);
});
Debug.WriteLine("Mapping ParameterName={0}; to Member={1};", parameter.ParameterName, member);
return member;
}
return null;
}
}
} | using System;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using Insight.Database.Mapping;
namespace SqlServer.Management.IntegrationServices.Data.Catalog.Parameters
{
/// <summary>
/// A parameter mapper which changes the SSIS style parameters to CamelCase.
/// </summary>
internal class SsisParameterMapper : IParameterMapper
{
private static Regex RenameRegex =
new Regex(@"(?<id>[A-Z,a-z,0-9]+)(?<underscore>_)+");
public string MapParameter(Type type, IDbCommand command, IDataParameter parameter)
{
var connectionString = command.Connection.ConnectionString;
var commandText = command.CommandText ?? string.Empty;
if (ConnectionStrings.IsSsisConnectionString(connectionString)
// don't change casing of the ReturnValue parameter since Insight.Database makes use of it
&& parameter.Direction != ParameterDirection.ReturnValue
)
{
Console.WriteLine(command.CommandText);
var member = RenameRegex.Replace(parameter.ParameterName, match =>
{
var id = match.Groups["id"].Value;
return System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase(id);
});
Debug.WriteLine("Mapping ParameterName={0}; to Member={1};", parameter.ParameterName, member);
return member;
}
return null;
}
}
} | unlicense | C# |
3555175c2d41197fc6e1a8bc8043634e7a2aaf8d | test method with param | andrewdavey/witness,andrewdavey/witness,andrewdavey/witness | src/Witness.Tests/DotnetContextTest.cs | src/Witness.Tests/DotnetContextTest.cs | using System;
using System.Linq;
using System.Text;
using Xunit;
namespace Witness.Tests
{
public class ExecutingAuthenticateHeader : ExecutableHeadersTest
{
public ExecutingAuthenticateHeader()
{
HeaderSet("x-witness-onauthenticate");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteOnAuthenticate();
Assert.True(executed);
}
}
public class ExecutingBeginRequestHeader : ExecutableHeadersTest
{
public ExecutingBeginRequestHeader()
{
HeaderSet("x-witness-beginrequest");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteBeginRequest();
Assert.True(executed);
}
}
public class ExecutingEndRequestHeader : ExecutableHeadersTest
{
public ExecutingEndRequestHeader()
{
HeaderSet("x-witness-endrequest");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteEndRequest();
Assert.True(executed);
}
}
public class CallingAMethodFromJavascript
{
static bool called;
DotNetContext context;
public CallingAMethodFromJavascript()
{
context = new DotNetContext()
.Add("callingAMethod", () => called = true);
}
[Fact]
public void IsCalled()
{
context.Run("callingAMethod()");
Assert.True(called);
}
}
public class CallingAParametisedMethodFromJavascript
{
static string result;
DotNetContext context;
public CallingAParametisedMethodFromJavascript()
{
context = new DotNetContext()
.Add("callingAMethod", () => result = "called");
}
[Fact]
public void IsCalled()
{
context.Run("callingAMethod('called')");
Assert.Equal(result,"called");
}
}
}
| using System;
using System.Linq;
using System.Text;
using Xunit;
namespace Witness.Tests
{
public class ExecutingAuthenticateHeader : ExecutableHeadersTest
{
public ExecutingAuthenticateHeader()
{
HeaderSet("x-witness-onauthenticate");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteOnAuthenticate();
Assert.True(executed);
}
}
public class ExecutingBeginRequestHeader : ExecutableHeadersTest
{
public ExecutingBeginRequestHeader()
{
HeaderSet("x-witness-beginrequest");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteBeginRequest();
Assert.True(executed);
}
}
public class ExecutingEndRequestHeader : ExecutableHeadersTest
{
public ExecutingEndRequestHeader()
{
HeaderSet("x-witness-endrequest");
}
[Fact]
public void HeaderIsExecuted()
{
headers.ExecuteEndRequest();
Assert.True(executed);
}
}
public class CallingAMethodFromJavascript
{
static bool called;
DotNetContext context;
public CallingAMethodFromJavascript()
{
context = new DotNetContext()
.Add("callingAMethod", () => called = true);
}
[Fact]
public void IsCalled()
{
context.Run("callingAMethod()");
Assert.True(called);
}
}
}
| bsd-2-clause | C# |
3f78163e875d68cc1227b05b20215f158146e035 | Enable all kernels except FAT. | tgiphil/Cosmos,jp2masa/Cosmos,tgiphil/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,fanoI/Cosmos,CosmosOS/Cosmos,trivalik/Cosmos,trivalik/Cosmos,fanoI/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,zarlo/Cosmos | Tests/Cosmos.TestRunner.Core/TestKernelSets.cs | Tests/Cosmos.TestRunner.Core/TestKernelSets.cs | using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
| using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
////yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
//yield return typeof(SimpleStructsAndArraysTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
////yield return typeof(FrotzKernel.Kernel);
}
}
}
| bsd-3-clause | C# |
eec77b052790f720fa716d10b96aad540b9cb083 | replace icon | ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,peppy/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu | osu.Game.Rulesets.Catch/Mods/CatchModFloatingFruits.cs | osu.Game.Rulesets.Catch/Mods/CatchModFloatingFruits.cs | using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModFloatingFruits : Mod, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Name => "Floating Fruits";
public override string Acronym => "FF";
public override string Description => "The fruits are... floating?";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon => FontAwesome.Solid.Cloud;
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset)
{
drawableRuleset.Anchor = Anchor.Centre;
drawableRuleset.Origin = Anchor.Centre;
drawableRuleset.Scale = new osuTK.Vector2(1, -1);
}
}
}
| using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModFloatingFruits : Mod, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Name => "Floating Fruits";
public override string Acronym => "FF";
public override string Description => "The fruits are... floating?";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon => FontAwesome.Brands.Fly;
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset)
{
drawableRuleset.Anchor = Anchor.Centre;
drawableRuleset.Origin = Anchor.Centre;
drawableRuleset.Scale = new osuTK.Vector2(1, -1);
}
}
}
| mit | C# |
9d228c85464de2bfe68d8d86a3794112d7bb54fb | Delete EnvironmentAugments.GetEnvironmentVariables (#14500) | rartemev/coreclr,krk/coreclr,wateret/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,JosephTremoulet/coreclr,mmitche/coreclr,wateret/coreclr,poizan42/coreclr,wateret/coreclr,poizan42/coreclr,poizan42/coreclr,yizhang82/coreclr,mmitche/coreclr,rartemev/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,krk/coreclr,cshung/coreclr,poizan42/coreclr,krk/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,cshung/coreclr,rartemev/coreclr,mmitche/coreclr,rartemev/coreclr,yizhang82/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,wateret/coreclr,yizhang82/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,JosephTremoulet/coreclr,mmitche/coreclr,cshung/coreclr,rartemev/coreclr,wtgodbe/coreclr,wateret/coreclr,yizhang82/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,yizhang82/coreclr,wateret/coreclr,poizan42/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,mmitche/coreclr,cshung/coreclr,rartemev/coreclr,krk/coreclr,krk/coreclr,krk/coreclr | src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs | src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Internal.Runtime.Augments
{
/// <summary>For internal use only. Exposes runtime functionality to the Environments implementation in corefx.</summary>
public static class EnvironmentAugments
{
public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId;
public static void Exit(int exitCode) => Environment.Exit(exitCode);
public static int ExitCode { get { return Environment.ExitCode; } set { Environment.ExitCode = value; } }
public static void FailFast(string message, Exception error) => Environment.FailFast(message, error);
public static string[] GetCommandLineArgs() => Environment.GetCommandLineArgs();
public static bool HasShutdownStarted => Environment.HasShutdownStarted;
public static int TickCount => Environment.TickCount;
public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable);
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) => Environment.GetEnvironmentVariable(variable, target);
public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables() => Environment.EnumerateEnvironmentVariables();
public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target) => Environment.EnumerateEnvironmentVariables(target);
public static void SetEnvironmentVariable(string variable, string value) => Environment.SetEnvironmentVariable(variable, value);
public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) => Environment.SetEnvironmentVariable(variable, value, target);
public static string StackTrace
{
[MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
get
{
return new StackTrace(1 /* skip this one frame */, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Internal.Runtime.Augments
{
/// <summary>For internal use only. Exposes runtime functionality to the Environments implementation in corefx.</summary>
public static class EnvironmentAugments
{
public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId;
public static void Exit(int exitCode) => Environment.Exit(exitCode);
public static int ExitCode { get { return Environment.ExitCode; } set { Environment.ExitCode = value; } }
public static void FailFast(string message, Exception error) => Environment.FailFast(message, error);
public static string[] GetCommandLineArgs() => Environment.GetCommandLineArgs();
public static bool HasShutdownStarted => Environment.HasShutdownStarted;
public static int TickCount => Environment.TickCount;
public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable);
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) => Environment.GetEnvironmentVariable(variable, target);
// TODO Perf: Once CoreCLR gets EnumerateEnvironmentVariables(), get rid of GetEnvironmentVariables() and have
// corefx call EnumerateEnvironmentVariables() instead so we don't have to create a dictionary just to copy it into
// another dictionary.
public static IDictionary GetEnvironmentVariables() => new Dictionary<string, string>(EnumerateEnvironmentVariables());
public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) => new Dictionary<string, string>(EnumerateEnvironmentVariables(target));
public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables() => Environment.EnumerateEnvironmentVariables();
public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target) => Environment.EnumerateEnvironmentVariables(target);
public static void SetEnvironmentVariable(string variable, string value) => Environment.SetEnvironmentVariable(variable, value);
public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) => Environment.SetEnvironmentVariable(variable, value, target);
public static string StackTrace
{
[MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
get
{
return new StackTrace(1 /* skip this one frame */, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
}
}
}
| mit | C# |
6358173e944de6fbcc0efa777f36aec517a249e9 | Fix naming of times for StandardInformation | LordMike/NtfsLib | NTFSLib/Objects/Attributes/AttributeStandardInformation.cs | NTFSLib/Objects/Attributes/AttributeStandardInformation.cs | using System;
using System.Diagnostics;
using System.IO;
using NTFSLib.Objects.Enums;
namespace NTFSLib.Objects.Attributes
{
public class AttributeStandardInformation : Attribute
{
public DateTime TimeCreated { get; set; }
public DateTime TimeModified { get; set; }
public DateTime TimeMftModified { get; set; }
public DateTime TimeAccessed { get; set; }
public FileAttributes DosPermissions { get; set; }
public uint MaxmiumVersions { get; set; }
public uint VersionNumber { get; set; }
public uint ClassId { get; set; }
public uint OwnerId { get; set; }
public uint SecurityId { get; set; }
public ulong QuotaCharged { get; set; }
public ulong USN { get; set; }
public override AttributeResidentAllow AllowedResidentStates
{
get
{
return AttributeResidentAllow.Resident;
}
}
internal override void ParseAttributeResidentBody(byte[] data, int maxLength, int offset)
{
base.ParseAttributeResidentBody(data, maxLength, offset);
Debug.Assert(maxLength >= 48);
TimeCreated = Utils.FromWinFileTime(data, offset);
TimeModified = Utils.FromWinFileTime(data, offset + 8);
TimeMftModified = Utils.FromWinFileTime(data, offset + 16);
TimeAccessed = Utils.FromWinFileTime(data, offset + 24);
DosPermissions = (FileAttributes)BitConverter.ToUInt32(data, offset + 32);
MaxmiumVersions = BitConverter.ToUInt32(data, offset + 36);
VersionNumber = BitConverter.ToUInt32(data, offset + 40);
ClassId = BitConverter.ToUInt32(data, offset + 44);
// The below fields are for version 3.0+
if (NonResidentFlag == ResidentFlag.Resident && ResidentHeader.ContentLength >= 72)
{
Debug.Assert(maxLength >= 72);
OwnerId = BitConverter.ToUInt32(data, offset + 48);
SecurityId = BitConverter.ToUInt32(data, offset + 52);
QuotaCharged = BitConverter.ToUInt64(data, offset + 56);
USN = BitConverter.ToUInt64(data, offset + 64);
}
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using NTFSLib.Objects.Enums;
namespace NTFSLib.Objects.Attributes
{
public class AttributeStandardInformation : Attribute
{
public DateTime CTime { get; set; }
public DateTime ATime { get; set; }
public DateTime MTime { get; set; }
public DateTime RTime { get; set; }
public FileAttributes DosPermissions { get; set; }
public uint MaxmiumVersions { get; set; }
public uint VersionNumber { get; set; }
public uint ClassId { get; set; }
public uint OwnerId { get; set; }
public uint SecurityId { get; set; }
public ulong QuotaCharged { get; set; }
public ulong USN { get; set; }
public override AttributeResidentAllow AllowedResidentStates
{
get
{
return AttributeResidentAllow.Resident;
}
}
internal override void ParseAttributeResidentBody(byte[] data, int maxLength, int offset)
{
base.ParseAttributeResidentBody(data, maxLength, offset);
Debug.Assert(maxLength >= 48);
CTime = Utils.FromWinFileTime(data, offset);
ATime = Utils.FromWinFileTime(data, offset + 8);
MTime = Utils.FromWinFileTime(data, offset + 16);
RTime = Utils.FromWinFileTime(data, offset + 24);
DosPermissions = (FileAttributes)BitConverter.ToUInt32(data, offset + 32);
MaxmiumVersions = BitConverter.ToUInt32(data, offset + 36);
VersionNumber = BitConverter.ToUInt32(data, offset + 40);
ClassId = BitConverter.ToUInt32(data, offset + 44);
// The below fields are for version 3.0+
if (NonResidentFlag == ResidentFlag.Resident && ResidentHeader.ContentLength >= 72)
{
Debug.Assert(maxLength >= 72);
OwnerId = BitConverter.ToUInt32(data, offset + 48);
SecurityId = BitConverter.ToUInt32(data, offset + 52);
QuotaCharged = BitConverter.ToUInt64(data, offset + 56);
USN = BitConverter.ToUInt64(data, offset + 64);
}
}
}
} | mit | C# |
08a7a8006efdb4ae3805270693b0cbbb6d589b0f | add distinct test | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | test/WeihanLi.Common.Test/ModelsTest/StringValueDictionaryTest.cs | test/WeihanLi.Common.Test/ModelsTest/StringValueDictionaryTest.cs | using Newtonsoft.Json;
using System.Collections.Generic;
using WeihanLi.Common.Models;
using Xunit;
namespace WeihanLi.Common.Test.ModelsTest
{
public class StringValueDictionaryTest
{
[Fact]
public void EqualsTest()
{
var abc = new { Id = 1, Name = "Tom" };
var dic1 = StringValueDictionary.Create(abc);
var dic2 = StringValueDictionary.Create(new Dictionary<string, object>()
{
{"Id", 1},
{"Name", "Tom" }
});
Assert.True(dic1 == dic2);
Assert.Equal(dic1, dic2);
}
[Fact]
public void DistinctTest()
{
var abc = new { Id = 1, Name = "Tom" };
var dic1 = StringValueDictionary.Create(abc);
var dic2 = StringValueDictionary.Create(new Dictionary<string, object>()
{
{"Id", 1},
{"Name", "Tom" }
});
var set = new HashSet<StringValueDictionary>();
set.Add(dic1);
set.Add(dic2);
Assert.Equal(1, set.Count);
}
record Person(int Id, string Name);
[Fact]
public void RecordTest()
{
var str1 = "{\"Id\":1, \"Name\":\"Tom\"}";
var p1 = JsonConvert.DeserializeObject<Person>(str1);
var str2 = "{\"Name\":\"Tom\",\"Id\":1}";
var p2 = JsonConvert.DeserializeObject<Person>(str2);
Assert.True(p1 == p2);
Assert.Equal(p1, p2);
}
[Fact]
public void ImplicitConvertTest()
{
var abc = new { Id = 1, Name = "Tom" };
var stringValueDictionary = StringValueDictionary.Create(abc);
Dictionary<string, string> dictionary = stringValueDictionary;
Assert.Equal(stringValueDictionary.Count, dictionary.Count);
var dic2 = StringValueDictionary.Create(dictionary);
Assert.Equal(dic2, stringValueDictionary);
Assert.True(dic2 == stringValueDictionary);
}
}
}
| using Newtonsoft.Json;
using System.Collections.Generic;
using WeihanLi.Common.Models;
using Xunit;
namespace WeihanLi.Common.Test.ModelsTest
{
public class StringValueDictionaryTest
{
[Fact]
public void EqualsTest()
{
var abc = new { Id = 1, Name = "Tom" };
var dic1 = StringValueDictionary.Create(abc);
var dic2 = StringValueDictionary.Create(new Dictionary<string, object>()
{
{"Id", 1},
{"Name", "Tom" }
});
Assert.True(dic1 == dic2);
Assert.Equal(dic1, dic2);
}
record Person(int Id, string Name);
[Fact]
public void RecordTest()
{
var str1 = "{\"Id\":1, \"Name\":\"Tom\"}";
var p1 = JsonConvert.DeserializeObject<Person>(str1);
var str2 = "{\"Name\":\"Tom\",\"Id\":1}";
var p2 = JsonConvert.DeserializeObject<Person>(str2);
Assert.True(p1 == p2);
Assert.Equal(p1, p2);
}
[Fact]
public void ImplicitConvertTest()
{
var abc = new { Id = 1, Name = "Tom" };
var stringValueDictionary = StringValueDictionary.Create(abc);
Dictionary<string, string> dictionary = stringValueDictionary;
Assert.Equal(stringValueDictionary.Count, dictionary.Count);
var dic2 = StringValueDictionary.Create(dictionary);
Assert.Equal(dic2, stringValueDictionary);
Assert.True(dic2 == stringValueDictionary);
}
}
}
| mit | C# |
c3932dad8fa4b5268560a5280024c806fae4c4f2 | Fix namespaces to share the code with MonoMac | mono/maccore,jorik041/maccore,cwensley/maccore | src/AVFoundation/AVCaptureConnection.cs | src/AVFoundation/AVCaptureConnection.cs | //
// AVCaptureConnection: Extensions to the class
//
// Authors:
// Miguel de Icaza
//
// Copyright 2011, Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using MonoMac.ObjCRuntime;
namespace MonoMac.AVFoundation {
public partial class AVCaptureConnection {
public bool SupportsVideoMinFrameDuration {
get {
if (RespondsToSelector (new Selector ("isVideoMinFrameDurationSupported")))
return SupportsVideoMinFrameDuration;
return false;
}
}
public bool SupportsVideoMaxFrameDuration {
get {
if (RespondsToSelector (new Selector ("isVideoMaxFrameDurationSupported")))
return SupportsVideoMinFrameDuration;
return false;
}
}
}
} | //
// AVCaptureConnection: Extensions to the class
//
// Authors:
// Miguel de Icaza
//
// Copyright 2011, Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using MonoTouch.ObjCRuntime;
namespace MonoTouch.AVFoundation {
public partial class AVCaptureConnection {
public bool SupportsVideoMinFrameDuration {
get {
if (RespondsToSelector (new Selector ("isVideoMinFrameDurationSupported")))
return SupportsVideoMinFrameDuration;
return false;
}
}
public bool SupportsVideoMaxFrameDuration {
get {
if (RespondsToSelector (new Selector ("isVideoMaxFrameDurationSupported")))
return SupportsVideoMinFrameDuration;
return false;
}
}
}
} | apache-2.0 | C# |
cd44a97a3f163cf2303d1996d3fa9a4ab2932e0a | Add last test in GameScoreTests.cs | sguzunov/Teamwork-HQC-Baloons-Pop-7 | Baloons-Pop-7/TestBalloonsPopGame/GameScoreTests/GameScoreTests.cs | Baloons-Pop-7/TestBalloonsPopGame/GameScoreTests/GameScoreTests.cs | namespace TestBalloonsPopGame
{
using Balloons.GamePlayer;
using Balloons.GameScore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
[TestClass]
public class GameScoreTests
{
public Player player;
[TestMethod]
public void PlayerIsNull()
{
Assert.IsNull(player);
}
[TestMethod]
public void PlayerIsNotNull()
{
var realPlayer = new Player();
realPlayer.Name = "Pesho";
realPlayer.Moves = 23;
Assert.IsNotNull(realPlayer);
}
[TestMethod]
public void AddPlayerInListOfGameScoreBoardTest()
{
var instanceScoreBoard = ScoreBoard.Instance;
instanceScoreBoard.AddPlayer(new Player());
Assert.IsNotNull(instanceScoreBoard);
}
[TestMethod]
public void GetSortedPlayersByMovesTest()
{
var randomGenerator = new Random();
var randomNum = randomGenerator.Next(1, 100);
var player1 = new Player("Pesho", randomNum);
var player2 = new Player("Gosho", randomNum);
var scoreBoard = ScoreBoard.Instance;
scoreBoard.AddPlayer(player1);
scoreBoard.AddPlayer(player2);
var sortedPlayer = scoreBoard.GetSortedPlayers;
for (int i = 0; i < sortedPlayer.Count - 1; i++)
{
Assert.IsTrue((sortedPlayer[i].Moves <= sortedPlayer[i + 1].Moves));
}
}
[TestMethod]
public void ScoreBoardIsSingle()
{
var instance1 = ScoreBoard.Instance;
var instance2 = ScoreBoard.Instance;
Assert.AreSame(instance1, instance2);
}
}
}
| namespace TestBalloonsPopGame
{
using Balloons.GamePlayer;
using Balloons.GameScore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
[TestClass]
public class GameScoreTests
{
public Player player;
[TestMethod]
public void PlayerIsNull()
{
Assert.IsNull(player);
}
[TestMethod]
public void PlayerIsNotNull()
{
var realPlayer = new Player();
realPlayer.Name = "Pesho";
realPlayer.Moves = 23;
Assert.IsNotNull(realPlayer);
}
[TestMethod]
public void AddPlayerInListTest()
{
var instanceScoreBoard = ScoreBoard.Instance;
instanceScoreBoard.AddPlayer(new Player());
Assert.IsNotNull(instanceScoreBoard);
}
[TestMethod]
public void GetSortedPlayersByPointsTest()
{
}
[TestMethod]
public void ScoreBoardIsSingle()
{
var instance1 = ScoreBoard.Instance;
var instance2 = ScoreBoard.Instance;
Assert.AreSame(instance1, instance2);
}
}
}
| mit | C# |
d82de35a2f98e83849563ef55ce5bd0db51f69df | change constraint of FindChild<T>() | TakeAsh/cs-WpfUtility | WpfUtility/DependencyObjectExtensionMethods.cs | WpfUtility/DependencyObjectExtensionMethods.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace WpfUtility {
public static class DependencyObjectExtensionMethods {
/// <summary>
/// Attempts to find and return an object that has the specified name. The search starts from the specified object and continues into subnodes of the logical tree.
/// </summary>
/// <typeparam name="T">The type of the object to find.</typeparam>
/// <param name="node">The object to start searching from. This object must be either a FrameworkElement or a FrameworkContentElement.</param>
/// <param name="name">The name of the object to find.</param>
/// <returns>The object with the matching name, if one is found; returns null if no matching name was found in the logical tree.</returns>
/// <remarks>
/// [LogicalTreeHelper.FindLogicalNode Method (System.Windows)](https://msdn.microsoft.com/en-us/library/system.windows.logicaltreehelper.findlogicalnode.aspx)
/// </remarks>
public static T FindChild<T>(this DependencyObject node, string name)
where T : DependencyObject {
return node != null ?
LogicalTreeHelper.FindLogicalNode(node, name) as T :
null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace WpfUtility {
public static class DependencyObjectExtensionMethods {
/// <summary>
/// Attempts to find and return an object that has the specified name. The search starts from the specified object and continues into subnodes of the logical tree.
/// </summary>
/// <typeparam name="T">The type of the object to find.</typeparam>
/// <param name="node">The object to start searching from. This object must be either a FrameworkElement or a FrameworkContentElement.</param>
/// <param name="name">The name of the object to find.</param>
/// <returns>The object with the matching name, if one is found; returns null if no matching name was found in the logical tree.</returns>
/// <remarks>
/// [LogicalTreeHelper.FindLogicalNode Method (System.Windows)](https://msdn.microsoft.com/en-us/library/system.windows.logicaltreehelper.findlogicalnode.aspx)
/// </remarks>
public static T FindChild<T>(this DependencyObject node, string name)
where T : class {
return node != null ?
LogicalTreeHelper.FindLogicalNode(node, name) as T :
null;
}
}
}
| mit | C# |
1e38e219b5a3b97c2832f8b6237f66b1b41a5ebf | Fix bug in Statement DTO mapper that expected bucket code to always have a value - it can be null. | Benrnz/BudgetAnalyser | BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs | BudgetAnalyser.Engine/Statement/Data/TransactionToTransactionDtoMapper.cs | using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket?.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
} | using System;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Budget;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement.Data
{
[AutoRegisterWithIoC]
internal partial class Mapper_TransactionDto_Transaction
{
private readonly IAccountTypeRepository accountRepo;
private readonly IBudgetBucketRepository bucketRepo;
private readonly ITransactionTypeRepository transactionTypeRepo;
public Mapper_TransactionDto_Transaction([NotNull] IAccountTypeRepository accountRepo, [NotNull] IBudgetBucketRepository bucketRepo, [NotNull] ITransactionTypeRepository transactionTypeRepo)
{
if (accountRepo == null) throw new ArgumentNullException(nameof(accountRepo));
if (bucketRepo == null) throw new ArgumentNullException(nameof(bucketRepo));
if (transactionTypeRepo == null) throw new ArgumentNullException(nameof(transactionTypeRepo));
this.accountRepo = accountRepo;
this.bucketRepo = bucketRepo;
this.transactionTypeRepo = transactionTypeRepo;
}
partial void ToDtoPostprocessing(ref TransactionDto dto, Transaction model)
{
dto.Account = model.Account.Name;
dto.BudgetBucketCode = model.BudgetBucket.Code;
dto.TransactionType = model.TransactionType.Name;
}
partial void ToModelPostprocessing(TransactionDto dto, ref Transaction model)
{
// TODO do these need to be added to the repo here?
model.Account = this.accountRepo.GetByKey(dto.Account);
model.BudgetBucket = this.bucketRepo.GetByCode(dto.BudgetBucketCode);
model.TransactionType = this.transactionTypeRepo.GetOrCreateNew(dto.TransactionType);
}
}
} | mit | C# |
9aa8855bb0874cf40b8b4391e69249309a22e5d1 | optimize access to dictionary | geofeedia/elasticsearch-net,TheFireCookie/elasticsearch-net,SeanKilleen/elasticsearch-net,cstlaurent/elasticsearch-net,robertlyson/elasticsearch-net,joehmchan/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,robrich/elasticsearch-net,azubanov/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,amyzheng424/elasticsearch-net,wawrzyn/elasticsearch-net,adam-mccoy/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,DavidSSL/elasticsearch-net,amyzheng424/elasticsearch-net,LeoYao/elasticsearch-net,mac2000/elasticsearch-net,DavidSSL/elasticsearch-net,alanprot/elasticsearch-net,starckgates/elasticsearch-net,tkirill/elasticsearch-net,abibell/elasticsearch-net,wawrzyn/elasticsearch-net,gayancc/elasticsearch-net,geofeedia/elasticsearch-net,robertlyson/elasticsearch-net,jonyadamit/elasticsearch-net,RossLieberman/NEST,alanprot/elasticsearch-net,mac2000/elasticsearch-net,robrich/elasticsearch-net,ststeiger/elasticsearch-net,junlapong/elasticsearch-net,jonyadamit/elasticsearch-net,junlapong/elasticsearch-net,Grastveit/NEST,gayancc/elasticsearch-net,junlapong/elasticsearch-net,robrich/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,Grastveit/NEST,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,LeoYao/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,starckgates/elasticsearch-net,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,abibell/elasticsearch-net,UdiBen/elasticsearch-net,adam-mccoy/elasticsearch-net,starckgates/elasticsearch-net,elastic/elasticsearch-net,alanprot/elasticsearch-net,CSGOpenSource/elasticsearch-net,amyzheng424/elasticsearch-net,SeanKilleen/elasticsearch-net,tkirill/elasticsearch-net,ststeiger/elasticsearch-net,CSGOpenSource/elasticsearch-net,geofeedia/elasticsearch-net,robertlyson/elasticsearch-net,tkirill/elasticsearch-net,ststeiger/elasticsearch-net,elastic/elasticsearch-net,alanprot/elasticsearch-net,RossLieberman/NEST,joehmchan/elasticsearch-net,azubanov/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,LeoYao/elasticsearch-net,Grastveit/NEST,jonyadamit/elasticsearch-net,RossLieberman/NEST | src/Nest/Resolvers/IndexNameResolver.cs | src/Nest/Resolvers/IndexNameResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Reflection;
using Elasticsearch.Net;
namespace Nest.Resolvers
{
public class IndexNameResolver
{
private readonly IConnectionSettingsValues _connectionSettings;
public IndexNameResolver(IConnectionSettingsValues connectionSettings)
{
connectionSettings.ThrowIfNull("hasDefaultIndices");
this._connectionSettings = connectionSettings;
}
public string GetIndexForType<T>()
{
return this.GetIndexForType(typeof(T));
}
public string GetIndexForType(Type type)
{
var defaultIndices = this._connectionSettings.DefaultIndices;
if (defaultIndices == null)
return this._connectionSettings.DefaultIndex;
string value;
if (defaultIndices.TryGetValue(type, out value) && !string.IsNullOrWhiteSpace(value))
return value;
return this._connectionSettings.DefaultIndex;
}
internal string GetIndexForType(IndexNameMarker i)
{
return i.Name ?? this.GetIndexForType(i.Type);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Reflection;
using Elasticsearch.Net;
namespace Nest.Resolvers
{
public class IndexNameResolver
{
private readonly IConnectionSettingsValues _connectionSettings;
public IndexNameResolver(IConnectionSettingsValues connectionSettings)
{
connectionSettings.ThrowIfNull("hasDefaultIndices");
this._connectionSettings = connectionSettings;
}
public string GetIndexForType<T>()
{
return this.GetIndexForType(typeof(T));
}
public string GetIndexForType(Type type)
{
var defaultIndices = this._connectionSettings.DefaultIndices;
if (defaultIndices == null)
return this._connectionSettings.DefaultIndex;
if (defaultIndices.ContainsKey(type) && !string.IsNullOrWhiteSpace(defaultIndices[type]))
return defaultIndices[type];
return this._connectionSettings.DefaultIndex;
}
internal string GetIndexForType(IndexNameMarker i)
{
return i.Name ?? this.GetIndexForType(i.Type);
}
}
}
| apache-2.0 | C# |
ae4f5fa7abf1f2e40c1e63ba089ceb99d2e47459 | Simplify ActionDictionnary by removing collection initializers | k94ll13nn3/Strinken | src/Strinken/Engine/ActionDictionary.cs | src/Strinken/Engine/ActionDictionary.cs | // stylecop.header
using System;
using System.Collections;
using System.Collections.Generic;
namespace Strinken.Engine
{
/// <summary>
/// Action dictionary used by the token stack to resolve the string.
/// </summary>
internal class ActionDictionary
{
/// <summary>
/// Internal dictionary containing the list of actions and the related <see cref="TokenType"/>.
/// </summary>
private readonly Dictionary<TokenType, Func<string[], string>> items;
/// <summary>
/// Initializes a new instance of the <see cref="ActionDictionary"/> class.
/// </summary>
public ActionDictionary()
{
this.items = new Dictionary<TokenType, Func<string[], string>>();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key, or null if the key is not present.</returns>
public Func<string[], string> this[TokenType key]
{
get { return this.items.ContainsKey(key) ? this.items[key] : null; }
set { this.items[key] = value; }
}
}
} | // stylecop.header
using System;
using System.Collections;
using System.Collections.Generic;
namespace Strinken.Engine
{
/// <summary>
/// Action dictionary used by the token stack to resolve the string.
/// </summary>
/// <remarks>Collection initializers can be used <see href="http://stackoverflow.com/a/2495801/3836163"/>.</remarks>
internal class ActionDictionary : IEnumerable<KeyValuePair<TokenType, Func<string[], string>>>
{
/// <summary>
/// Internal dictionary containing the list of actions and the related <see cref="TokenType"/>.
/// </summary>
private readonly Dictionary<TokenType, Func<string[], string>> items;
/// <summary>
/// Initializes a new instance of the <see cref="ActionDictionary"/> class.
/// </summary>
public ActionDictionary()
{
this.items = new Dictionary<TokenType, Func<string[], string>>();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key, or null if the key is not present.</returns>
public Func<string[], string> this[TokenType key]
{
get { return this.items.ContainsKey(key) ? this.items[key] : null; }
set { this.items[key] = value; }
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="ActionDictionary"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
public void Add(TokenType key, Func<string[], string> value)
{
this.items[key] = value;
}
/// <inheritdoc/>
public IEnumerator<KeyValuePair<TokenType, Func<string[], string>>> GetEnumerator() => this.items.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => this.items.GetEnumerator();
}
} | mit | C# |
b97ec37683c501fa7f1b371d71c61d6ef69012ea | Add Audio properties to IAudiomanagement | RickyGAkl/Vlc.DotNet,marcomeyer/Vlc.DotNet,marcomeyer/Vlc.DotNet,raydtang/Vlc.DotNet,someonehan/Vlc.DotNet,agherardi/Vlc.DotNet,xue-blood/wpfVlc,thephez/Vlc.DotNet,thephez/Vlc.DotNet,raydtang/Vlc.DotNet,RickyGAkl/Vlc.DotNet,ZeBobo5/Vlc.DotNet,jeremyVignelles/Vlc.DotNet,agherardi/Vlc.DotNet,xue-blood/wpfVlc,briancowan/Vlc.DotNet,someonehan/Vlc.DotNet,briancowan/Vlc.DotNet | src/Vlc.DotNet.Core/IAudioManagement.cs | src/Vlc.DotNet.Core/IAudioManagement.cs | namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
bool IsMute { get; set; }
void ToggleMute();
int Volume { get; set; }
ITracksManagement Tracks { get; }
int Channel { get; set; }
long Delay { get; set; }
}
}
| namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
}
}
| mit | C# |
9e973f96d173c11a57e7b3b28fcc5a3f0365b578 | Update GameEventHouseStatus.cs | ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE | Source/ACE.Server/Network/GameEvent/Events/GameEventHouseStatus.cs | Source/ACE.Server/Network/GameEvent/Events/GameEventHouseStatus.cs | using ACE.Entity.Enum;
using System;
namespace ACE.Server.Network.GameEvent.Events
{
public class GameEventHouseStatus : GameEventMessage
{
public GameEventHouseStatus(Session session, WeenieError weenieError = WeenieError.BadParam)
: base(GameEventType.HouseStatus, GameMessageGroup.UIQueue, session)
{
//Console.WriteLine("Sending 0x226 - HouseStatus");
//var noticeType = 2u; // type of message to display
Writer.Write((uint)weenieError);
}
}
}
| using ACE.Entity.Enum;
using System;
namespace ACE.Server.Network.GameEvent.Events
{
public class GameEventHouseStatus : GameEventMessage
{
public GameEventHouseStatus(Session session, WeenieError weenieError = WeenieError.BadParam)
: base(GameEventType.HouseStatus, GameMessageGroup.UIQueue, session)
{
//Console.WriteLine("Sending 0x226 - HouseStatus");
var noticeType = 2u; // type of message to display
Writer.Write((uint)weenieError);
}
}
}
| agpl-3.0 | C# |
d42b591fdf18eb6c682bdedc8c57ef71a83f50c0 | Convert constant string to nameof operator on GroundOverlay. | JKennedy24/Xamarin.Forms.GoogleMaps,amay077/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,quesera2/Xamarin.Forms.GoogleMaps | Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/GroundOverlay.cs | Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/GroundOverlay.cs |
using System;
namespace Xamarin.Forms.GoogleMaps
{
public sealed class GroundOverlay : BindableObject
{
public static readonly BindableProperty IconProperty = BindableProperty.Create(nameof(Icon), typeof(BitmapDescriptor), typeof(GroundOverlay), default(BitmapDescriptor));
public static readonly BindableProperty TransparencyProperty = BindableProperty.Create(nameof(Transparency), typeof(float), typeof(GroundOverlay), 0f);
public static readonly BindableProperty BoundsProperty = BindableProperty.Create(nameof(Bounds), typeof(Bounds), typeof(GroundOverlay), default(Bounds));
public static readonly BindableProperty BearingProperty = BindableProperty.Create(nameof(Bearing), typeof(float), typeof(GroundOverlay), 0f);
public static readonly BindableProperty IsClickableProperty = BindableProperty.Create(nameof(IsClickable), typeof(bool), typeof(GroundOverlay), false);
public BitmapDescriptor Icon
{
get { return (BitmapDescriptor)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public float Transparency
{
get { return (float)GetValue(TransparencyProperty); }
set { SetValue(TransparencyProperty, value); }
}
public Bounds Bounds
{
get { return (Bounds)GetValue(BoundsProperty); }
set { SetValue(BoundsProperty, value); }
}
public float Bearing
{
get { return (float)GetValue(BearingProperty); }
set { SetValue(BearingProperty, value); }
}
public bool IsClickable
{
get { return (bool)GetValue(IsClickableProperty); }
set { SetValue(IsClickableProperty, value); }
}
public object Tag { get; set; }
public object NativeObject { get; internal set; }
public event EventHandler Clicked;
internal bool SendTap()
{
EventHandler handler = Clicked;
if (handler == null)
return false;
handler(this, EventArgs.Empty);
return true;
}
}
} |
using System;
namespace Xamarin.Forms.GoogleMaps
{
public sealed class GroundOverlay : BindableObject
{
public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(BitmapDescriptor), typeof(GroundOverlay), default(BitmapDescriptor));
public static readonly BindableProperty TransparencyProperty = BindableProperty.Create("Transparency", typeof(float), typeof(GroundOverlay), 0f);
public static readonly BindableProperty BoundsProperty = BindableProperty.Create("Bounds", typeof(Bounds), typeof(GroundOverlay), default(Bounds));
public static readonly BindableProperty BearingProperty = BindableProperty.Create("Bearing", typeof(float), typeof(GroundOverlay), 0f);
public static readonly BindableProperty IsClickableProperty = BindableProperty.Create("IsClickable", typeof(bool), typeof(GroundOverlay), false);
public BitmapDescriptor Icon
{
get { return (BitmapDescriptor)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public float Transparency
{
get { return (float)GetValue(TransparencyProperty); }
set { SetValue(TransparencyProperty, value); }
}
public Bounds Bounds
{
get { return (Bounds)GetValue(BoundsProperty); }
set { SetValue(BoundsProperty, value); }
}
public float Bearing
{
get { return (float)GetValue(BearingProperty); }
set { SetValue(BearingProperty, value); }
}
public bool IsClickable
{
get { return (bool)GetValue(IsClickableProperty); }
set { SetValue(IsClickableProperty, value); }
}
public object Tag { get; set; }
public object NativeObject { get; internal set; }
public event EventHandler Clicked;
internal bool SendTap()
{
EventHandler handler = Clicked;
if (handler == null)
return false;
handler(this, EventArgs.Empty);
return true;
}
}
} | mit | C# |
78ce60094952393eaca69a574711799ad514dcfb | Use bare project name (without slash) + tree hash + ".zip" as zip file name | akrisiun/git-dot-aspx,linquize/git-dot-aspx,linquize/git-dot-aspx,akrisiun/git-dot-aspx,akrisiun/git-dot-aspx,linquize/git-dot-aspx | GitAspx/Views/DownloadView/Index.cshtml | GitAspx/Views/DownloadView/Index.cshtml | @model GitAspx.ViewModels.DownloadViewModel
@using GitAspx;
@using GitSharp;
@using ICSharpCode.SharpZipLib.Zip;
@functions{
void AddDirectoryToZip(ZipOutputStream aoZipStream, Tree aoTree, string asDirectory) {
foreach (Leaf loLeaf in aoTree.Leaves) {
ZipEntry loZipEntry = new ZipEntry(asDirectory + loLeaf.Name);
aoZipStream.PutNextEntry(loZipEntry);
aoZipStream.Write(loLeaf.RawData, 0, loLeaf.RawData.Length);
aoZipStream.CloseEntry();
}
foreach (Tree loTree in aoTree.Trees)
AddDirectoryToZip(aoZipStream, loTree, asDirectory + loTree.Name + "/");
}
}
@{
Response.Clear();
if (Model.File != null) {
Response.Cache.SetLastModified(Model.File.GetLastCommit().CommitDate.UtcDateTime);
Response.WriteBinary(Model.File.RawData, "application/" + Path.GetExtension(Model.File.Name));
}
else if (Model.Directory != null) {
string lsProject = Model.Project.SplitSlashes_OrEmpty().LastOrDefault();
string lsBareFileName = (!string.IsNullOrEmpty(Model.Directory.Name) ? Model.Directory.Name : lsProject) + "-" + Model.Commit.ShortHash + "-" + Model.Directory.ShortHash;
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("content-disposition", "attachment; filename=" + lsBareFileName+ ".zip");
Response.Flush();
string lsZipFile = Path.GetTempFileName();
using (ZipOutputStream loZipStream = new ZipOutputStream(File.Create(lsZipFile))) {
AddDirectoryToZip(loZipStream, Model.Directory, "");
loZipStream.Finish();
loZipStream.Close();
}
Response.BinaryWrite(File.ReadAllBytes(lsZipFile));
File.Delete(lsZipFile);
}
Response.End();
} | @model GitAspx.ViewModels.DownloadViewModel
@using GitSharp;
@using ICSharpCode.SharpZipLib.Zip;
@functions{
void AddDirectoryToZip(ZipOutputStream aoZipStream, Tree aoTree, string asDirectory) {
foreach (Leaf loLeaf in aoTree.Leaves) {
ZipEntry loZipEntry = new ZipEntry(asDirectory + loLeaf.Name);
aoZipStream.PutNextEntry(loZipEntry);
aoZipStream.Write(loLeaf.RawData, 0, loLeaf.RawData.Length);
aoZipStream.CloseEntry();
}
foreach (Tree loTree in aoTree.Trees)
AddDirectoryToZip(aoZipStream, loTree, asDirectory + loTree.Name + "/");
}
}
@{
Response.Clear();
if (Model.File != null) {
Response.Cache.SetLastModified(Model.File.GetLastCommit().CommitDate.UtcDateTime);
Response.WriteBinary(Model.File.RawData, "application/" + Path.GetExtension(Model.File.Name));
}
else if (Model.Directory != null) {
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("content-disposition", "attachment; filename=" + Model.Directory.Name + ".zip");
Response.Flush();
string lsZipFile = Path.GetTempFileName();
using (ZipOutputStream loZipStream = new ZipOutputStream(File.Create(lsZipFile))) {
AddDirectoryToZip(loZipStream, Model.Directory, "");
loZipStream.Finish();
loZipStream.Close();
}
Response.BinaryWrite(File.ReadAllBytes(lsZipFile));
File.Delete(lsZipFile);
}
Response.End();
} | apache-2.0 | C# |
658999b6b438eddbe68f3ca31c5fa30a21d6a22f | update formatting | designsbyjuan/UnityLib | TagEventTrigger.cs | TagEventTrigger.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class TagEventTrigger : ButtonEventTrigger {
protected void Awake()
{
base.Awake();
}
// Use this for initialization
protected void Start ()
{
base.Start();
}
protected override void OnPointerDownDelegate(PointerEventData data) { /* do nothing */ }
}
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class TagEventTrigger : ButtonEventTrigger {
protected void Awake()
{
base.Awake();
}
// Use this for initialization
protected void Start ()
{
base.Start();
}
protected override void OnPointerDownDelegate(PointerEventData data) { /* do nothing */ }
}
| mit | C# |
297a746548736324c02017dc51104d6cdbc264a4 | test fixing | leegould/MicroBlog,leegould/MicroBlog,leegould/MicroBlog | MicroBlog/BlogModule.cs | MicroBlog/BlogModule.cs | using MicroBlog.Interface;
using MicroBlog.Models;
using Nancy;
namespace MicroBlog
{
public class BlogModule : NancyModule
{
private IPostRepository postRepository;
public BlogModule(IPostRepository postrepository)
{
postRepository = postrepository;
Get["/{id:int}"] = x =>
{
Post item = postRepository.Get(x.id);
if (item != null)
{
return Response.AsJson(item);
}
return HttpStatusCode.NotFound;
};
}
}
} | using MicroBlog.Interface;
using MicroBlog.Models;
using Nancy;
namespace MicroBlog
{
public class BlogModule : NancyModule
{
private IPostRepository postRepository;
public BlogModule(IPostRepository postrepository)
{
postRepository = postrepository;
Get["/{id:int}"] = x =>
{
Post item = postRepository.Get(x.id);
return Response.AsJson(item);
};
}
}
} | mit | C# |
6fc3bdc4f2447bf8ce545d8bbf80535d6552244a | Fix UnreliablePongMessage type | chkn/Tempest | Desktop/Tempest/InternalProtocol/UnreliablePongMessage.cs | Desktop/Tempest/InternalProtocol/UnreliablePongMessage.cs | //
// UnreliablePongMessage.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2012 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Tempest.InternalProtocol
{
public sealed class UnreliablePongMessage
: TempestMessage
{
internal UnreliablePongMessage()
: base (TempestMessageType.UnreliablePong)
{
}
public override bool MustBeReliable
{
get { return false; }
}
public override bool PreferReliable
{
get { return false; }
}
public int Interval
{
get;
set;
}
public override void WritePayload (ISerializationContext context, IValueWriter writer)
{
writer.WriteInt32 (Interval);
}
public override void ReadPayload (ISerializationContext context, IValueReader reader)
{
Interval = reader.ReadInt32();
}
}
} | //
// UnreliablePongMessage.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2012 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Tempest.InternalProtocol
{
public sealed class UnreliablePongMessage
: TempestMessage
{
internal UnreliablePongMessage()
: base (TempestMessageType.UnreliablePing)
{
}
public override bool MustBeReliable
{
get { return false; }
}
public override bool PreferReliable
{
get { return false; }
}
public int Interval
{
get;
set;
}
public override void WritePayload (ISerializationContext context, IValueWriter writer)
{
writer.WriteInt32 (Interval);
}
public override void ReadPayload (ISerializationContext context, IValueReader reader)
{
Interval = reader.ReadInt32();
}
}
} | mit | C# |
b5e2f8b2e061f3c48430b03c4848abf9eef8af8e | Add ShowDialog | cH40z-Lord/Stylet,canton7/Stylet,cH40z-Lord/Stylet,canton7/Stylet | Stylet/WindowManager.cs | Stylet/WindowManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Navigation;
namespace Stylet
{
public interface IWindowManager
{
void ShowWindow(object viewModel);
bool? ShowDialog(object viewModel);
}
public class WindowManager : IWindowManager
{
public void ShowWindow(object viewModel)
{
this.CreateWindow(viewModel, false).Show();
}
public bool? ShowDialog(object viewModel)
{
return this.CreateWindow(viewModel, true).ShowDialog();
}
private Window CreateWindow(object viewModel, bool isDialog)
{
var view = ViewLocator.LocateForModel(viewModel) as Window;
if (view == null)
throw new Exception(String.Format("Tried to show {0} as a window, but it isn't a Window", view.GetType().Name));
ViewModelBinder.Bind(view, viewModel);
var haveDisplayName = viewModel as IHaveDisplayName;
if (haveDisplayName != null)
{
var binding = new Binding("DisplayName") { Mode = BindingMode.TwoWay };
view.SetBinding(Window.TitleProperty, binding);
}
if (isDialog)
{
var owner = this.InferOwnerOf(view);
if (owner != null)
view.Owner = owner;
}
return view;
}
private Window InferOwnerOf(Window window)
{
if (Application.Current == null)
return null;
var active = Application.Current.Windows.OfType<Window>().Where(x => x.IsActive).FirstOrDefault() ?? Application.Current.MainWindow;
return active == window ? null : active;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Navigation;
namespace Stylet
{
public interface IWindowManager
{
void ShowWindow(object viewModel);
}
public class WindowManager : IWindowManager
{
public void ShowWindow(object viewModel)
{
this.CreateWindow(viewModel, false).Show();
}
private Window CreateWindow(object viewModel, bool isDialog)
{
var view = ViewLocator.LocateForModel(viewModel) as Window;
if (view == null)
throw new Exception(String.Format("Tried to show {0} as a window, but it isn't a Window", view.GetType().Name));
ViewModelBinder.Bind(view, viewModel);
var haveDisplayName = viewModel as IHaveDisplayName;
if (haveDisplayName != null)
{
var binding = new Binding("DisplayName") { Mode = BindingMode.TwoWay };
view.SetBinding(Window.TitleProperty, binding);
}
if (isDialog)
{
var owner = this.InferOwnerOf(view);
if (owner != null)
view.Owner = owner;
}
return view;
}
private Window InferOwnerOf(Window window)
{
if (Application.Current == null)
return null;
var active = Application.Current.Windows.OfType<Window>().Where(x => x.IsActive).FirstOrDefault() ?? Application.Current.MainWindow;
return active == window ? null : active;
}
}
}
| mit | C# |
b2cf6c46f39669c894faab737a44635b170442b7 | fix postgre sql dialect | bgTeamDev/bgTeam.Core,bgTeamDev/bgTeam.Core | src/bgTeam.Impl.Dapper/Mapper/Sql/PostgreSqlDialect.cs | src/bgTeam.Impl.Dapper/Mapper/Sql/PostgreSqlDialect.cs | namespace DapperExtensions.Mapper.Sql
{
using System.Collections.Generic;
public class PostgreSqlDialect : SqlDialectBase
{
public override string GetIdentitySql(string tableName)
{
return "SELECT LASTVAL() AS Id";
}
public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary<string, object> parameters)
{
int startValue = page * resultsPerPage;
return GetSetSql(sql, startValue, resultsPerPage, parameters);
}
public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
{
string result = string.Format("{0} LIMIT @maxResults OFFSET @pageStartRowNbr", sql);
parameters.Add("@maxResults", maxResults);
parameters.Add("@pageStartRowNbr", firstResult /* * maxResults */); //HACK: fixing DapperExtensions bug
return result;
}
public override string GetColumnName(string prefix, string columnName, string alias)
{
return base.GetColumnName(null, columnName, alias);
}
}
}
| namespace DapperExtensions.Mapper.Sql
{
using System.Collections.Generic;
public class PostgreSqlDialect : SqlDialectBase
{
public override string GetIdentitySql(string tableName)
{
return "SELECT LASTVAL() AS Id";
}
public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary<string, object> parameters)
{
int startValue = page * resultsPerPage;
return GetSetSql(sql, startValue, resultsPerPage, parameters);
}
public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
{
string result = string.Format("{0} LIMIT @maxResults OFFSET @pageStartRowNbr", sql);
parameters.Add("@maxResults", maxResults);
parameters.Add("@pageStartRowNbr", firstResult /* * maxResults */); //HACK: fixing DapperExtensions bug
return result;
}
}
}
| mit | C# |
59a48f1a120727c90920ce483f3614565678f058 | Fix typo | asarium/FSOLauncher | Libraries/ModInstallation/Interfaces/IRemoteModManager.cs | Libraries/ModInstallation/Interfaces/IRemoteModManager.cs | #region Usings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using ModInstallation.Annotations;
using ModInstallation.Interfaces.Mods;
#endregion
namespace ModInstallation.Interfaces
{
public interface IRemoteModManager : INotifyPropertyChanged
{
[NotNull]
IEnumerable<IModRepository> Repositories { get; set; }
/// <summary>
/// Retrieves the modification groups, this may fetch the necessary information from the repositories if it is not
/// already available.
/// </summary>
/// <remarks>This function may run synchronously if the requested information is already present.</remarks>
/// <param name="progressReporter">The reporter used for notifying a listener of status updates</param>
/// <param name="force">If set to <c>true</c> the repositories will always be used to retrieve the information.</param>
/// <param name="token">A cancellation token that can be used to abort the operation</param>
/// <returns>The modification groups.</returns>
[NotNull]
Task<IEnumerable<IModGroup>> GetModGroupsAsync([NotNull] IProgress<string> progressReporter, bool force, CancellationToken token);
}
}
| #region Usings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using ModInstallation.Annotations;
using ModInstallation.Interfaces.Mods;
#endregion
namespace ModInstallation.Interfaces
{
public interface IRemoteModManager : INotifyPropertyChanged
{
[NotNull]
IEnumerable<IModRepository> Repositories { get; set; }
/// <summary>
/// Retrieves the modification groups, this may fetch the necessary information from the repositories if it is not
/// already available.
/// </summary>
/// <remarks>This function may run synchronously if the requested information is already present.</remarks>
/// <param name="progressReporter">The reporter used for notifying a listener of status updates</param>
/// <param name="force">If set to <c>true</c> the repositories will always be used to retrieve the information.</param>
/// <param name="token">A cancellation token that can be used to abort the operation</param>
/// <returns>The odification groups.</returns>
[NotNull]
Task<IEnumerable<IModGroup>> GetModGroupsAsync([NotNull] IProgress<string> progressReporter, bool force, CancellationToken token);
}
}
| mit | C# |
1cbd2bc0a1b9fe05c39dbd8672072fd57d5dd265 | Remove the "car" value | It423/tron,wrightg42/tron | Tron/Tron/CellValues.cs | Tron/Tron/CellValues.cs | // CellValues.cs
// <copyright file="CellValues.cs"> This code is protected under the MIT License. </copyright>
namespace Tron
{
/// <summary>
/// An enumeration to represent the possible values for a cell on the grid.
/// </summary>
public enum CellValues
{
/// <summary>
/// Nothing is on the cell.
/// </summary>
None = 0,
/// <summary>
/// Red is the colour of the cell.
/// </summary>
Red = 1,
/// <summary>
/// Green is the colour of the cell.
/// </summary>
Green = 2,
/// <summary>
/// Blue is the colour of the cell.
/// </summary>
Blue = 4,
/// <summary>
/// Yellow is the colour of the cell.
/// </summary>
Yellow = 8,
/// <summary>
/// White is the colour of the cell.
/// </summary>
White = 16,
/// <summary>
/// Black is the colour of the cell.
/// </summary>
Black = 32,
/// <summary>
/// Pink is the colour of the cell.
/// </summary>
Pink = 64,
/// <summary>
/// Orange is the colour of the cell.
/// </summary>
Orange = 128,
/// <summary>
/// Pink is the colour of the cell.
/// </summary>
Purple = 256,
/// <summary>
/// Brown is the colour of the cell.
/// </summary>
Brown = 512
}
}
| // CellValues.cs
// <copyright file="CellValues.cs"> This code is protected under the MIT License. </copyright>
namespace Tron
{
/// <summary>
/// An enumeration to represent the possible values for a cell on the grid.
/// </summary>
public enum CellValues
{
/// <summary>
/// Nothing is on the cell.
/// </summary>
None = 0,
/// <summary>
/// A car is on the cell.
/// </summary>
Car = 1,
/// <summary>
/// Red is the colour of the cell.
/// </summary>
Red = 2,
/// <summary>
/// Green is the colour of the cell.
/// </summary>
Green = 4,
/// <summary>
/// Blue is the colour of the cell.
/// </summary>
Blue = 8,
/// <summary>
/// Yellow is the colour of the cell.
/// </summary>
Yellow = 16,
/// <summary>
/// White is the colour of the cell.
/// </summary>
White = 32,
/// <summary>
/// Black is the colour of the cell.
/// </summary>
Black = 64,
/// <summary>
/// Pink is the colour of the cell.
/// </summary>
Pink = 128,
/// <summary>
/// Orange is the colour of the cell.
/// </summary>
Orange = 256,
/// <summary>
/// Pink is the colour of the cell.
/// </summary>
Purple = 512,
/// <summary>
/// Brown is the colour of the cell.
/// </summary>
Brown = 1024
}
}
| mit | C# |
d39c746b3d01ce380e30a401892b4949cf8dc9fc | delete items bug fixed, log improved | agileharbor/channelAdvisorAccess | src/ChannelAdvisorAccess/Services/Items/ItemsServiceDeleteItems.cs | src/ChannelAdvisorAccess/Services/Items/ItemsServiceDeleteItems.cs | using System;
using System.Threading.Tasks;
using ChannelAdvisorAccess.Exceptions;
using ChannelAdvisorAccess.Misc;
namespace ChannelAdvisorAccess.Services.Items
{
public partial class ItemsService: IItemsService
{
#region Delete item
public void DeleteItem( string sku, Mark mark = null )
{
if( mark.IsBlank() )
mark = Mark.CreateNew();
try
{
ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
AP.Submit.Do( () =>
{
ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
var resultOfBoolean = this._client.DeleteInventoryItem( this._credentials, this.AccountId, sku );
CheckCaSuccess( resultOfBoolean );
ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : resultOfBoolean.ToJson(), additionalInfo : this.AdditionalLogInfoString, methodParameters : this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : sku ) );
} );
ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
}
catch( Exception exception )
{
var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString ), exception );
ChannelAdvisorLogger.LogTraceException( channelAdvisorException );
throw channelAdvisorException;
}
}
public async Task DeleteItemAsync( string sku, Mark mark = null )
{
if( mark.IsBlank() )
mark = Mark.CreateNew();
try
{
ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
await AP.SubmitAsync.Do( async () =>
{
ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : sku ) );
var resultOfBoolean = await this._client.DeleteInventoryItemAsync( this._credentials, this.AccountId, sku ).ConfigureAwait( false );
CheckCaSuccess( resultOfBoolean.DeleteInventoryItemResult );
ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : resultOfBoolean.ToJson(), additionalInfo : this.AdditionalLogInfoString, methodParameters : this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : sku ) );
} ).ConfigureAwait( false );
ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
}
catch( Exception exception )
{
var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString ), exception );
ChannelAdvisorLogger.LogTraceException( channelAdvisorException );
throw channelAdvisorException;
}
}
#endregion}
}
} | using System;
using System.Threading.Tasks;
using ChannelAdvisorAccess.Exceptions;
using ChannelAdvisorAccess.Misc;
namespace ChannelAdvisorAccess.Services.Items
{
public partial class ItemsService: IItemsService
{
#region Delete item
public void DeleteItem( string sku, Mark mark = null )
{
if( mark.IsBlank() )
mark = Mark.CreateNew();
try
{
ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
AP.Submit.Do( () =>
{
ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
var resultOfBoolean = this._client.DeleteInventoryItem( this._credentials, this.AccountId, sku );
CheckCaSuccess( resultOfBoolean );
ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : resultOfBoolean.ToJson(), additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
} );
ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
}
catch( Exception exception )
{
var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString ), exception );
ChannelAdvisorLogger.LogTraceException( channelAdvisorException );
throw channelAdvisorException;
}
}
public async Task DeleteItemAsync( string sku, Mark mark = null )
{
if( mark.IsBlank() )
mark = Mark.CreateNew();
try
{
ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
await AP.SubmitAsync.Do( async () =>
{
ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
var resultOfBoolean = await this._client.DeleteInventoryItemAsync( this._credentials, this.AccountId, sku ).ConfigureAwait( false );
CheckCaSuccess( resultOfBoolean.DeleteInventoryItemResult );
ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : resultOfBoolean.ToJson(), additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
} ).ConfigureAwait( false );
ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString, methodParameters : sku ) );
}
catch( Exception exception )
{
var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfoString ), exception );
ChannelAdvisorLogger.LogTraceException( channelAdvisorException );
throw channelAdvisorException;
}
}
#endregion}
} | bsd-3-clause | C# |
49a9fac45c4c14d7a4fb61baae5c4f5f06b3e2f8 | Add IsAccessLimited property. | BibliothecaTeam/Bibliotheca.Server.Gateway,BibliothecaTeam/Bibliotheca.Server.Gateway | src/Bibliotheca.Server.Gateway.Core/DataTransferObjects/ProjectDto.cs | src/Bibliotheca.Server.Gateway.Core/DataTransferObjects/ProjectDto.cs | using System.Collections.Generic;
namespace Bibliotheca.Server.Gateway.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
public string AccessToken { get; set; }
public bool IsAccessLimited { get; set; }
}
} | using System.Collections.Generic;
namespace Bibliotheca.Server.Gateway.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
public string AccessToken { get; set; }
}
} | mit | C# |
46dcd212de340e75861b6ba9b3b8f1e2a9622d7a | Update AssemblyInfo.cs | idormenco/PolyBool.Net | Polybool.Net/Properties/AssemblyInfo.cs | Polybool.Net/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("Polybool.Net")]
[assembly: AssemblyDescription("Boolean operations on polygons (union, intersection, difference, xor) (this library is a port for .net of polybooljs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Polybool.Net")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5fb7c719-ba44-48da-8384-1796a5cf3ff6")]
// 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.5.1.0")]
[assembly: AssemblyFileVersion("1.5.1.0")]
| 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("Polybool.Net")]
[assembly: AssemblyDescription("Boolean operations on polygons (union, intersection, difference, xor) (this library is a port for .net of polybooljs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Polybool.Net")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5fb7c719-ba44-48da-8384-1796a5cf3ff6")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
| mit | C# |
bc64eb9b997b48085b469a0f07144623297568d8 | Fix LocalizeString docs | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.Extensions.Localization.Abstractions/LocalizedString.cs | src/Microsoft.Extensions.Localization.Abstractions/LocalizedString.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.
using System;
namespace Microsoft.Extensions.Localization
{
/// <summary>
/// A locale specific string.
/// </summary>
public class LocalizedString
{
/// <summary>
/// Creates a new <see cref="LocalizedString"/>.
/// </summary>
/// <param name="name">The name of the string in the resource it was loaded from.</param>
/// <param name="value">The actual string.</param>
public LocalizedString(string name, string value)
: this(name, value, resourceNotFound: false)
{
}
/// <summary>
/// Creates a new <see cref="LocalizedString"/>.
/// </summary>
/// <param name="name">The name of the string in the resource it was loaded from.</param>
/// <param name="value">The actual string.</param>
/// <param name="resourceNotFound">Whether the string was not found in a resource. Set this to <c>true</c> to indicate an alternate string value was used.</param>
public LocalizedString(string name, string value, bool resourceNotFound)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Name = name;
Value = value;
ResourceNotFound = resourceNotFound;
}
public static implicit operator string(LocalizedString localizedString)
{
return localizedString?.Value;
}
/// <summary>
/// The name of the string in the resource it was loaded from.
/// </summary>
public string Name { get; }
/// <summary>
/// The actual string.
/// </summary>
public string Value { get; }
/// <summary>
/// Whether the string was not found in a resource. If <c>true</c>, an alternate string value was used.
/// </summary>
public bool ResourceNotFound { get; }
/// <summary>
/// Returns the actual string.
/// </summary>
/// <returns>The actual string.</returns>
public override string ToString() => Value;
}
} | // 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.
using System;
namespace Microsoft.Extensions.Localization
{
/// <summary>
/// A locale specific string.
/// </summary>
public class LocalizedString
{
/// <summary>
/// Creates a new <see cref="LocalizedString"/>.
/// </summary>
/// <param name="name">The name of the string in the resource it was loaded from.</param>
/// <param name="value">The actual string.</param>
public LocalizedString(string name, string value)
: this(name, value, resourceNotFound: false)
{
}
/// <summary>
/// Creates a new <see cref="LocalizedString"/>.
/// </summary>
/// <param name="name">The name of the string in the resource it was loaded from.</param>
/// <param name="value">The actual string.</param>
/// <param name="resourceNotFound">Whether the string was found in a resource. Set this to <c>false</c> to indicate an alternate string value was used.</param>
public LocalizedString(string name, string value, bool resourceNotFound)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Name = name;
Value = value;
ResourceNotFound = resourceNotFound;
}
public static implicit operator string(LocalizedString localizedString)
{
return localizedString?.Value;
}
/// <summary>
/// The name of the string in the resource it was loaded from.
/// </summary>
public string Name { get; }
/// <summary>
/// The actual string.
/// </summary>
public string Value { get; }
/// <summary>
/// Whether the string was found in a resource. If <c>false</c>, an alternate string value was used.
/// </summary>
public bool ResourceNotFound { get; }
/// <summary>
/// Returns the actual string.
/// </summary>
/// <returns>The actual string.</returns>
public override string ToString() => Value;
}
} | apache-2.0 | C# |
f6d08f54e6e950f4784087012fe27cd3e566a22c | Use the oldest user config file available when there happens to be multiple config files available. | UselessToucan/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/IO/StableStorage.cs | osu.Game/IO/StableStorage.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
var songsDirectoryPath = Path.Combine(BasePath, stable_default_songs_path);
// enumerate the user config files available in case the user migrated their files from another pc / operating system.
var foundConfigFiles = GetFiles(".", "osu!.*.cfg");
// if more than one config file is found, let's use the oldest one (where the username in the filename doesn't match the local username).
var configFile = foundConfigFiles.Count() > 1 ? foundConfigFiles.FirstOrDefault(filename => !filename[5..^4].Contains(Environment.UserName, StringComparison.Ordinal)) : foundConfigFiles.FirstOrDefault();
if (configFile == null)
return songsDirectoryPath;
using (var stream = GetStream(configFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase))
{
var directory = line.Split('=')[1].TrimStart();
if (Path.IsPathFullyQualified(directory))
songsDirectoryPath = directory;
break;
}
}
}
return songsDirectoryPath;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
var songsDirectoryPath = Path.Combine(BasePath, stable_default_songs_path);
var configFile = GetFiles(".", "osu!.*.cfg").SingleOrDefault();
if (configFile == null)
return songsDirectoryPath;
using (var stream = GetStream(configFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase))
{
var directory = line.Split('=')[1].TrimStart();
if (Path.IsPathFullyQualified(directory))
songsDirectoryPath = directory;
break;
}
}
}
return songsDirectoryPath;
}
}
}
| mit | C# |
70cda655c8ef00c9de57ead8cb4d7f7b88f10186 | Improve text control black list | JetBrains/resharper-presentation-assistant | src/dotnet/ReSharperPlugin.PresentationAssistant/ActionIdBlacklist.cs | src/dotnet/ReSharperPlugin.PresentationAssistant/ActionIdBlacklist.cs | using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
"TextControl.Left", "TextControl.Right",
"TextControl.Left.Selection", "TextControl.Right.Selection",
"TextControl.Up", "TextControl.Down",
"TextControl.Up.Selection", "TextControl.Down.Selection",
"TextControl.Home", "TextControl.End",
"TextControl.Home.Selection", "TextControl.End.Selection",
"TextControl.PageUp", "TextControl.PageDown",
"TextControl.PageUp.Selection", "TextControl.PageDown.Selection",
"TextControl.PreviousWord", "TextControl.NextWord",
"TextControl.PreviousWord.Selection", "TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
} | using System.Collections.Generic;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
public static class ActionIdBlacklist
{
private static readonly HashSet<string> ActionIds = new HashSet<string>
{
// These are the only actions that should be hidden
"TextControl.Backspace",
"TextControl.Delete",
"TextControl.Cut",
"TextControl.Paste",
"TextControl.Copy",
// Used when code completion window is visible
"TextControl.Up", "TextControl.Down",
"TextControl.PageUp", "TextControl.PageDown",
// If camel humps are enabled in the editor
"TextControl.PreviousWord",
"TextControl.PreviousWord.Selection",
"TextControl.NextWord",
"TextControl.NextWord.Selection",
// VS commands, not R# commands
"Edit.Up", "Edit.Down", "Edit.Left", "Edit.Right", "Edit.PageUp", "Edit.PageDown",
// Make sure we don't try to show the presentation assistant popup just as we're
// killing the popups
PresentationAssistantAction.ActionId
};
public static bool IsBlacklisted(string actionId)
{
return ActionIds.Contains(actionId);
}
}
} | apache-2.0 | C# |
59679ad98ca5f1f1c30e05434390cd5c62b71f62 | Update UnsafeDelegate.cs | NMSLanX/Natasha | test/NatashaBenchmark/UnsafeDelegate.cs | test/NatashaBenchmark/UnsafeDelegate.cs | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Mathematics;
using BenchmarkDotNet.Order;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace NatashaBenchmark
{
[MemoryDiagnoser, MarkdownExporter, RPlotExporter]
[MinColumn, MaxColumn, MeanColumn, MedianColumn]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn(NumeralSystem.Arabic)]
[CategoriesColumn]
public unsafe class UnsafeDelegate
{
public FuncHandler<int, int, string> func;
public Func<int, int, string> func2;
public delegate* managed<int, int, string> point;
public delegate*<int, int, string> point1;
public UnsafeDelegate()
{
func = new FuncHandler<int, int, string>();
func.Invoke = &(TestModel.Get);
func2 = TestModel.Get;
point = &(TestModel.Get);
}
public string Get(int a,int b)
{
return default;
}
[Benchmark(Description = "delegate*(packed)")]
public void UsePackagePoint()
{
func.Invoke(10, 10);
}
[Benchmark(Description = "delegate*")]
public void UseDirectPoint()
{
point(10, 10);
}
[Benchmark(Description = "system")]
public void UseSystem()
{
func2(10, 10);
}
[Benchmark(Description = "origin")]
public void UseOrigin()
{
TestModel.Get(10, 10);
}
}
public unsafe class ActionHandler<T1,T2>
{
public delegate* managed<T1, T2, void> Invoke;
}
public unsafe class FuncHandler<T1, T2, T3>
{
public delegate* managed<T1,T2,T3> Invoke;
}
public static class TestModel
{
public static string Get(int a,int b)
{
return a.ToString();
}
//[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
//public static string Get2(int a,int b)
//{
// return a.ToString();
//}
}
}
| using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Mathematics;
using BenchmarkDotNet.Order;
using System;
using System.Collections.Generic;
using System.Text;
namespace NatashaBenchmark
{
[MemoryDiagnoser, MarkdownExporter, RPlotExporter]
[MinColumn, MaxColumn, MeanColumn, MedianColumn]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn(NumeralSystem.Arabic)]
[CategoriesColumn]
public unsafe class UnsafeDelegate
{
public FuncHandler<int, int, string> func;
public Func<int, int, string> func2;
public delegate* managed<int, int, string> point;
public delegate*<int, int, string> point1;
public UnsafeDelegate()
{
func = new FuncHandler<int, int, string>();
func.Invoke = &(TestModel.Get);
func2 = TestModel.Get;
point = &(TestModel.Get);
}
public string Get(int a,int b)
{
return default;
}
[Benchmark(Description = "delegate*(packed)")]
public void UsePackagePoint()
{
func.Invoke(10, 10);
}
[Benchmark(Description = "delegate*")]
public void UseDirectPoint()
{
point(10, 10);
}
[Benchmark(Description = "system")]
public void UseSystem()
{
func2(10, 10);
}
[Benchmark(Description = "origin")]
public void UseOrigin()
{
TestModel.Get(10, 10);
}
}
public unsafe class ActionHandler<T1,T2>
{
public delegate* managed<T1, T2, void> Invoke;
}
public unsafe class FuncHandler<T1, T2, T3>
{
public delegate* managed<T1,T2,T3> Invoke;
}
public static class TestModel
{
public static string Get(int a,int b)
{
//return (a + b).ToString();
return default;
}
}
}
| mpl-2.0 | C# |
185abdfdfe56874f4e7aba4afdef7e5b8d9d4f22 | fix merge conflicts from signin | crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin | SignInCheckIn/SignInCheckIn/App_Start/AutoMapperConfig.cs | SignInCheckIn/SignInCheckIn/App_Start/AutoMapperConfig.cs | using AutoMapper;
using MinistryPlatform.Translation.Models.DTO;
using SignInCheckIn.Models.DTO;
namespace SignInCheckIn.App_Start
{
public static class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(CreateMappings);
}
private static void CreateMappings(IMapperConfigurationExpression config)
{
config.CreateMap<MpEventRoomDto, EventRoomDto>().ReverseMap();
config.CreateMap<MpEventDto, EventDto>().ForMember(dest => dest.EventSite,
opts => opts.MapFrom(src => src.CongregationName)).ReverseMap().ForMember(dest => dest.CongregationName,
opts => opts.MapFrom(src => src.EventSite));
config.CreateMap<MpKioskConfigDto, KioskConfigDto>().ReverseMap();
config.CreateMap<MpParticipantDto, ParticipantDto>();
}
}
}
| using AutoMapper;
using MinistryPlatform.Translation.Models.DTO;
using SignInCheckIn.Models.DTO;
namespace SignInCheckIn.App_Start
{
public static class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(CreateMappings);
}
private static void CreateMappings(IMapperConfigurationExpression config)
{
config.CreateMap<MpEventRoomDto, EventRoomDto>().ReverseMap();
config.CreateMap<MpEventDto, EventDto>().ForMember(dest => dest.EventSite,
opts => opts.MapFrom(src => src.CongregationName)).ReverseMap().ForMember(dest => dest.CongregationName,
opts => opts.MapFrom(src => src.EventSite));
<<<<<<< HEAD
config.CreateMap<MpKioskConfigDto, KioskConfigDto>().ReverseMap();
=======
config.CreateMap<MpParticipantDto, ParticipantDto>();
>>>>>>> development
}
}
} | bsd-2-clause | C# |
cc30002ef98d6b9fb38957f1b2f9ce3d66e3095b | build number must be .0 | Haacked/Subtext,jeuvin/Subtext,jeuvin/Subtext,jeuvin/Subtext,jeuvin/Subtext,Haacked/Subtext,jeuvin/Subtext,Haacked/Subtext,Haacked/Subtext,Haacked/Subtext | SubtextSolution/VersionInfo.Designer.cs | SubtextSolution/VersionInfo.Designer.cs | using System;
using System.Reflection;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
[assembly: AssemblyVersionAttribute("1.0.4.0")]
| using System;
using System.Reflection;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
[assembly: AssemblyVersionAttribute("1.0.4.9")]
| mit | C# |
d8e4426edb1e36a6107dbcc2af13e2c4adaff87b | Improve test coverage for the AccountKey class | openchain/openchain | test/Openchain.Infrastructure.Tests/AccountKeyTests.cs | test/Openchain.Infrastructure.Tests/AccountKeyTests.cs | // Copyright 2015 Coinprism, 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 Openchain.Infrastructure.Tests
{
public class AccountKeyTests
{
[Fact]
public void AccountKey_Success()
{
AccountKey result = new AccountKey(LedgerPath.Parse("/path/"), LedgerPath.Parse("/asset/"));
Assert.Equal("/path/", result.Account.FullPath);
Assert.Equal("/asset/", result.Asset.FullPath);
}
[Fact]
public void AccountKey_ArgumentNullException()
{
ArgumentNullException exception;
exception = Assert.Throws<ArgumentNullException>(() => new AccountKey(null, LedgerPath.Parse("/asset/")));
Assert.Equal("account", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => new AccountKey(LedgerPath.Parse("/path/"), null));
Assert.Equal("asset", exception.ParamName);
}
[Fact]
public void Equals_Success()
{
Assert.True(AccountKey.Parse("/abc/", "/def/").Equals(AccountKey.Parse("/abc/", "/def/")));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(AccountKey.Parse("/abc/", "/ghi/")));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(null));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(100));
}
[Fact]
public void Equals_Object()
{
Assert.True(AccountKey.Parse("/abc/", "/def/").Equals((object)AccountKey.Parse("/abc/", "/def/")));
}
[Fact]
public void GetHashCode_Success()
{
Assert.Equal(AccountKey.Parse("/abc/", "/def/").GetHashCode(), AccountKey.Parse("/abc/", "/def/").GetHashCode());
}
}
}
| // Copyright 2015 Coinprism, 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 Openchain.Infrastructure.Tests
{
public class AccountKeyTests
{
[Fact]
public void AccountKey_Success()
{
AccountKey result = new AccountKey(LedgerPath.Parse("/path/"), LedgerPath.Parse("/asset/"));
Assert.Equal("/path/", result.Account.FullPath);
Assert.Equal("/asset/", result.Asset.FullPath);
}
[Fact]
public void AccountKey_ArgumentNullException()
{
ArgumentNullException exception;
exception = Assert.Throws<ArgumentNullException>(() => new AccountKey(null, LedgerPath.Parse("/asset/")));
Assert.Equal("account", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => new AccountKey(LedgerPath.Parse("/path/"), null));
Assert.Equal("asset", exception.ParamName);
}
[Fact]
public void Equals_Success()
{
Assert.True(AccountKey.Parse("/abc/", "/def/").Equals(AccountKey.Parse("/abc/", "/def/")));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(AccountKey.Parse("/abc/", "/ghi/")));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(null));
Assert.False(AccountKey.Parse("/abc/", "/def/").Equals(100));
}
[Fact]
public void GetHashCode_Success()
{
Assert.Equal(AccountKey.Parse("/abc/", "/def/").GetHashCode(), AccountKey.Parse("/abc/", "/def/").GetHashCode());
}
}
}
| apache-2.0 | C# |
b2445b0b0cf63211affc53163f74348d4baf7f19 | Remove doc_values fielddata format for strings | elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Modules/Indices/Fielddata/String/StringFielddataFormat.cs | src/Nest/Modules/Indices/Fielddata/String/StringFielddataFormat.cs | using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "disabled")]
Disabled
}
}
| using System.Runtime.Serialization;
namespace Nest
{
public enum StringFielddataFormat
{
[EnumMember(Value = "paged_bytes")]
PagedBytes,
[EnumMember(Value = "doc_values")]
DocValues,
[EnumMember(Value = "disabled")]
Disabled
}
}
| apache-2.0 | C# |
900d8a58f03f326708c33aba47d68d5daf3720b3 | Add copyright information to IPatternParser. | zaccharles/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,nodatime/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,malcolmr/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,jskeet/nodatime | src/NodaTime/Text/Patterns/IPatternParser.cs | src/NodaTime/Text/Patterns/IPatternParser.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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
using NodaTime.Globalization;
namespace NodaTime.Text.Patterns
{
internal interface IPatternParser<T>
{
PatternParseResult<T> ParsePattern(string pattern, NodaFormatInfo formatInfo, ParseStyles parseStyles);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using NodaTime.Globalization;
namespace NodaTime.Text.Patterns
{
internal interface IPatternParser<T>
{
PatternParseResult<T> ParsePattern(string pattern, NodaFormatInfo formatInfo, ParseStyles parseStyles);
}
}
| apache-2.0 | C# |
de1f26a2de16c7ee37b05afc1d47d3e0e3173c21 | fix typo | mans0954/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,mono/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,Yetangitu/f-spot,dkoeb/f-spot,dkoeb/f-spot,Yetangitu/f-spot,dkoeb/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,Sanva/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,Yetangitu/f-spot,Yetangitu/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,Sanva/f-spot,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,dkoeb/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,mono/f-spot,mono/f-spot,Sanva/f-spot,GNOME/f-spot,GNOME/f-spot,mans0954/f-spot,Yetangitu/f-spot,GNOME/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,dkoeb/f-spot,mono/f-spot,mans0954/f-spot | src/DCRawFile.cs | src/DCRawFile.cs | using System.Diagnostics;
using System.IO;
using System;
namespace FSpot {
public class Pipe : System.IO.Stream {
// This class is a hack to make sure mono doesn't dispose the process
// and by extension the stream from the pipe when we are still using the
// the stream.
Process process;
Stream stream;
public override bool CanRead {
get { return stream.CanRead; }
}
public override bool CanSeek {
get { return stream.CanSeek; }
}
public override bool CanWrite {
get { return stream.CanWrite; }
}
public override long Length {
get { return stream.Length; }
}
public override long Position {
get { return stream.Position; }
set { stream.Position = value; }
}
public Pipe (Process p, Stream stream)
{
this.process = p;
this.stream = stream;
}
public override void Flush ()
{
stream.Flush ();
}
public override int Read (byte [] b, int s, int l)
{
return stream.Read (b, s, l);
}
public override long Seek (long l, SeekOrigin origin)
{
return stream.Seek(l, origin);
}
public override void SetLength (long l)
{
stream.SetLength (l);
}
public override void Write (byte [] b, int s, int l)
{
stream.Write (b, s, l);
}
public void Dispose ()
{
stream = null;
process = null;
}
}
public class DCRawFile : ImageFile {
public DCRawFile (string path) : base (path) {}
public override System.IO.Stream PixbufStream ()
{
return RawPixbufStream (this.path);
}
public static System.IO.Stream RawPixbufStream (string path)
{
// FIXME this filename quoting is super lame
string args = System.String.Format ("-h -w -c \"{0}\"", path);
System.Diagnostics.Process process = new System.Diagnostics.Process ();
process.StartInfo = new System.Diagnostics.ProcessStartInfo ("dcraw", args);
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start ();
return new Pipe (process, process.StandardOutput.BaseStream);
}
public static Gdk.Pixbuf Load (string path, string args)
{
// FIXME this filename quoting is super lame
args = System.String.Format ("-h -w -c \"{0}\"", path);
System.Console.WriteLine ("path = {0}, args = \"{1}\"", path, args);
using (System.Diagnostics.Process process = new System.Diagnostics.Process ()) {
process.StartInfo = new System.Diagnostics.ProcessStartInfo ("dcraw", args);
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start ();
return PixbufUtils.LoadFromStream (process.StandardOutput.BaseStream);
}
}
}
}
| using System.Diagnostics;
using System.IO;
using System;
namespace FSpot {
public class Pipe : System.IO.Stream {
// This class is a hack to make sure mono doesn't dispose the process
// and by extension the stream from the pipe when we are still using the
// the stream.
Process process;
Stream stream;
public override bool CanRead {
get { return stream.CanRead; }
}
public override bool CanSeek {
get { return stream.CanSeek; }
}
public override bool CanWrite {
get { return stream.CanWrite; }
}
public override long Length {
get { return stream.Length; }
}
public override long Position {
get { return stream.Position; }
set { stream.Position = value; }
}
public Pipe (Process p, Stream stream)
{
this.process = p;
this.stream = stream;
}
public override void Flush ()
{
stream.Flush ();
}
public override int Read (byte [] b, int s, int l)
{
return stream.Read (b, s, l);
}
public override long Seek (long l, SeekOrigin origin)
{
return stream.Seek(l, origin);
}
public override void SetLength (long l)
{
stream.SetLength (l);
}
public override void Write (byte [] b, int s, int l)
{
stream.Write (b, s, l);
}
public void Dispose ()
{
stream = null;
process = null;
}
}
public class DCRawFile : ImageFile {
public DCRawFile (string path) : base (path) {}
public override System.IO.Stream PixbufStream ()
{
return new RawPixbufStream (this.path);
}
public static System.IO.Stream RawPixbufStream (string path)
{
// FIXME this filename quoting is super lame
string args = System.String.Format ("-h -w -c \"{0}\"", path);
System.Diagnostics.Process process = new System.Diagnostics.Process ();
process.StartInfo = new System.Diagnostics.ProcessStartInfo ("dcraw", args);
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start ();
return new Pipe (process, process.StandardOutput.BaseStream);
}
public static Gdk.Pixbuf Load (string path, string args)
{
// FIXME this filename quoting is super lame
args = System.String.Format ("-h -w -c \"{0}\"", path);
System.Console.WriteLine ("path = {0}, args = \"{1}\"", path, args);
using (System.Diagnostics.Process process = new System.Diagnostics.Process ()) {
process.StartInfo = new System.Diagnostics.ProcessStartInfo ("dcraw", args);
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start ();
return PixbufUtils.LoadFromStream (process.StandardOutput.BaseStream);
}
}
}
}
| mit | C# |
1de348ea8bd307a1ce6026007d014d36b177db62 | Revert "VertexDrawRange Tweaks" | AdamsLair/duality,Barsonax/duality,SirePi/duality,BraveSirAndrew/duality | Source/Core/Duality/Drawing/VertexData/VertexDrawRange.cs | Source/Core/Duality/Drawing/VertexData/VertexDrawRange.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Duality.Resources;
using Duality.Backend;
namespace Duality.Drawing
{
/// <summary>
/// Describes a continuous range of vertex indices to be rendered.
/// </summary>
/// <see cref="DrawBatch"/>
public struct VertexDrawRange
{
/// <summary>
/// Index of the first vertex to be rendered.
/// </summary>
public int Index;
/// <summary>
/// The number of vertices to be rendered, starting from <see cref="Index"/>.
/// </summary>
public int Count;
public override string ToString()
{
return string.Format(
"[{0} - {1}]",
this.Index,
this.Index + this.Count - 1);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Duality.Resources;
using Duality.Backend;
namespace Duality.Drawing
{
/// <summary>
/// Describes a continuous range of vertex indices to be rendered.
/// </summary>
/// <see cref="DrawBatch"/>
public struct VertexDrawRange
{
/// <summary>
/// Index of the first vertex to be rendered.
/// </summary>
public ushort Index;
/// <summary>
/// The number of vertices to be rendered, starting from <see cref="Index"/>.
/// </summary>
public ushort Count;
public override string ToString()
{
return string.Format(
"[{0} - {1}]",
this.Index,
this.Index + this.Count - 1);
}
}
}
| mit | C# |
da09bc98facb628e871dc584d67a2d6fe2313b42 | Update Program.cs | TomPeters/Maybe | ConsoleApplication2/Program.cs | ConsoleApplication2/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
IMaybe<MyUser> maybeUser = Maybe.Just(new MyUser());
IMaybe<IEnumerable<UserGroup>> maybeGroups = maybeUser.Select(user => user.Groups);
// if you need to check if it has value, use this extension method, but probably don't do this often.
if (maybeGroups.HasValue())
{
Console.WriteLine("We have groups");
}
else
{
Console.WriteLine("No groups");
}
// null coalescing equivalent
IEnumerable<UserGroup> groupsForDisplay = maybeGroups.Or(Enumerable.Empty<UserGroup>());
foreach (var group in groupsForDisplay)
{
Console.WriteLine(group);
}
// or better yet...
maybeGroups.Do(groups =>
{
Console.WriteLine("We have groups");
foreach (var group in groups)
{
Console.WriteLine(group);
}
}, () => Console.WriteLine("No groups"));
// or maybe you only want to do something if you have a value
maybeGroups.Do(groups =>
{
foreach (var group in groups)
{
Console.WriteLine(group);
}
});
maybeUser
.If(u => u.Name.Length < 5)
.Do(user => Console.WriteLine($"User {user.Name} has a short name"));
}
}
public class MyUser
{
public string Name => "Foo";
public IEnumerable<UserGroup> Groups { get { yield return new UserGroup(); } }
}
public class UserGroup
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
IMaybe<MyUser> maybeUser = Maybe.Just(new MyUser());
IMaybe<IEnumerable<UserGroup>> maybeGroups = maybeUser.Safe(user => user.Groups);
// if you need to check if it has value, use this extension method, but probably don't do this often.
if (maybeGroups.HasValue())
{
Console.WriteLine("We have groups");
}
else
{
Console.WriteLine("No groups");
}
// null coalescing equivalent
IEnumerable<UserGroup> groupsForDisplay = maybeGroups.Coalesce(Enumerable.Empty<UserGroup>());
foreach (var group in groupsForDisplay)
{
Console.WriteLine(group);
}
// or better yet...
maybeGroups.Do(groups =>
{
Console.WriteLine("We have groups");
foreach (var group in groups)
{
Console.WriteLine(group);
}
}, () => Console.WriteLine("No groups"));
// or maybe you only want to do something if you have a value
maybeGroups.Do(groups =>
{
foreach (var group in groups)
{
Console.WriteLine(group);
}
});
maybeUser
.If(u => u.Name.Length < 5)
.Do(user => Console.WriteLine($"User {user.Name} has a short name"));
}
}
public class MyUser
{
public string Name => "Foo";
public IEnumerable<UserGroup> Groups { get { yield return new UserGroup(); } }
}
public class UserGroup
{
}
}
| mit | C# |
4c0c2b920bca23782861c4420b7907dfe674ddeb | Change the link to zkSNACKs. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Tabs/AboutViewModel.cs | WalletWasabi.Gui/Tabs/AboutViewModel.cs | using Avalonia.Diagnostics.ViewModels;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.ViewModels;
using System.IO;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Tabs
{
internal class AboutViewModel : WasabiDocumentTabViewModel
{
public ReactiveCommand<string, Unit> OpenBrowserCommand { get; }
public AboutViewModel(Global global) : base(global, "About")
{
Version = Constants.ClientVersion;
OpenBrowserCommand = ReactiveCommand.Create<string>(x =>
{
try
{
IoHelpers.OpenBrowser(x);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
});
}
public Version Version { get; }
public string VersionText => $"v{Version}";
public string ClearnetLink => "https://wasabiwallet.io/";
public string TorLink => "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion";
public string SourceCodeLink => "https://github.com/zkSNACKs/WalletWasabi/";
public string StatusPageLink => "https://stats.uptimerobot.com/YQqGyUL8A7";
public string CustomerSupportLink => "https://www.reddit.com/r/WasabiWallet/";
public string BugReportLink => "https://github.com/zkSNACKs/WalletWasabi/issues/";
public string FAQLink => "https://docs.wasabiwallet.io/FAQ/";
public string DocsLink => "https://docs.wasabiwallet.io/";
}
}
| using Avalonia.Diagnostics.ViewModels;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.ViewModels;
using System.IO;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Tabs
{
internal class AboutViewModel : WasabiDocumentTabViewModel
{
public ReactiveCommand<string, Unit> OpenBrowserCommand { get; }
public AboutViewModel(Global global) : base(global, "About")
{
Version = Constants.ClientVersion;
OpenBrowserCommand = ReactiveCommand.Create<string>(x =>
{
try
{
IoHelpers.OpenBrowser(x);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
});
}
public Version Version { get; }
public string VersionText => $"v{Version}";
public string ClearnetLink => "https://wasabiwallet.io/";
public string TorLink => "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion";
public string SourceCodeLink => "https://github.com/zkSNACKs/WalletWasabi/";
public string StatusPageLink => "https://stats.uptimerobot.com/W7q65in4y";
public string CustomerSupportLink => "https://www.reddit.com/r/WasabiWallet/";
public string BugReportLink => "https://github.com/zkSNACKs/WalletWasabi/issues/";
public string FAQLink => "https://docs.wasabiwallet.io/FAQ/";
public string DocsLink => "https://docs.wasabiwallet.io/";
}
}
| mit | C# |
d2eec2366ff341290a74ce64653730a700105deb | add comment explaining implementation divergence | mavasani/roslyn,bartdesmet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,weltkante/roslyn,mavasani/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn | src/VisualStudio/CSharp/Impl/ProjectSystemShim/EntryPointFinder.cs | src/VisualStudio/CSharp/Impl/ProjectSystemShim/EntryPointFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
internal class EntryPointFinder : AbstractEntryPointFinder
{
protected override bool MatchesMainMethodName(string name)
=> name == "Main";
public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol)
{
// This differs from the VB implementation (Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.EntryPointFinder)
// because we don't ever consider forms entry points.
// Techinically, this is wrong but it just doesn't matter since the
// ref assemblies are unlikely to have a random Main() method that matches
var visitor = new EntryPointFinder();
visitor.Visit(symbol);
return visitor.EntryPoints;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
internal class EntryPointFinder : AbstractEntryPointFinder
{
protected override bool MatchesMainMethodName(string name)
=> name == "Main";
public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol)
{
var visitor = new EntryPointFinder();
visitor.Visit(symbol);
return visitor.EntryPoints;
}
}
}
| mit | C# |
a477d1546622a8f21713d5bb6dcad576c4fcccc0 | fix script error on ajax messages if not ajax call | dfensgmbh/biz.dfch.CS.Appclusive.UI,dfensgmbh/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI,dfch/biz.dfch.CS.Appclusive.UI | src/biz.dfch.CS.Appclusive.UI/Views/Shared/AjaxNotification.cshtml | src/biz.dfch.CS.Appclusive.UI/Views/Shared/AjaxNotification.cshtml | @model IEnumerable<biz.dfch.CS.Appclusive.UI.Models.AjaxNotificationViewModel>
@{
biz.dfch.CS.Appclusive.UI.Controllers.IExtendedController extController = ViewContext.Controller as biz.dfch.CS.Appclusive.UI.Controllers.IExtendedController;
}
@if (null != extController && extController.IsAjaxRequest)
{
foreach (biz.dfch.CS.Appclusive.UI.Models.AjaxNotificationViewModel note in Model)
{
if (string.IsNullOrEmpty(note.ElementId))
{
<script type="text/javascript">
$.notify("@note.Message.Replace("\r\n", " ")", "@note.Level");
</script>
}
else
{
<script type="text/javascript">
$("#@note.ElementId").notify("@note.Message.Replace("\r\n", " ")", "@note.Level");
</script>
}
}
} | @model IEnumerable<biz.dfch.CS.Appclusive.UI.Models.AjaxNotificationViewModel>
@foreach(biz.dfch.CS.Appclusive.UI.Models.AjaxNotificationViewModel note in Model){
if (string.IsNullOrEmpty(note.ElementId))
{
<script type="text/javascript">
$.notify("@note.Message.Replace("\r\n", " ")", "@note.Level");
</script>
}
else
{
<script type="text/javascript">
$("#@note.ElementId").notify("@note.Message.Replace("\r\n", " ")", "@note.Level");
</script>
}
}
| apache-2.0 | C# |
c3e07e45ea4fc2d783fab8d7b5c813f2a81015f0 | Fix of previous commit | vigoo/bari,vigoo/bari,vigoo/bari,Psychobilly87/bari,Psychobilly87/bari,Psychobilly87/bari,vigoo/bari,Psychobilly87/bari | src/core/Bari.Core/cs/Build/Statistics/DefaultBuilderStatistics.cs | src/core/Bari.Core/cs/Build/Statistics/DefaultBuilderStatistics.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Bari.Core.Build.Statistics
{
public class DefaultBuilderStatistics: IBuilderStatistics
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DefaultBuilderStatistics));
private readonly IDictionary<Type, BuilderStats> builderStats = new Dictionary<Type, BuilderStats>();
public void Add(Type builderType, string description, TimeSpan elapsed)
{
BuilderStats stats;
if (!builderStats.TryGetValue(builderType, out stats))
{
stats = new BuilderStats(builderType);
builderStats.Add(builderType, stats);
}
stats.Add(description, elapsed);
}
public void Dump()
{
log.Debug("Builder performance statistics");
log.Debug("----");
var byTotal = builderStats.OrderByDescending(kv => kv.Value.Total);
foreach (var item in byTotal)
{
log.DebugFormat("# {0} ({1}x) => total: {2:F3}s, average: {3:F3}s", item.Key.Name, item.Value.Count, item.Value.Total.TotalSeconds, item.Value.Average.TotalSeconds);
var records = item.Value.All.OrderByDescending(r => r.Length);
foreach (var record in records)
{
log.DebugFormat(" - {0}: {1:F3}s", record.Id, record.Length.TotalSeconds);
}
}
log.Debug("----");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Bari.Core.Build.Statistics
{
public class DefaultBuilderStatistics: IBuilderStatistics
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DefaultBuilderStatistics));
private readonly IDictionary<Type, BuilderStats> builderStats = new Dictionary<Type, BuilderStats>();
public void Add(Type builderType, string description, TimeSpan elapsed)
{
BuilderStats stats;
if (!builderStats.TryGetValue(builderType, out stats))
{
stats = new BuilderStats(builderType);
builderStats.Add(builderType, stats);
}
stats.Add(description, elapsed);
}
public void Dump()
{
log.Debug("Builder performance statistics");
log.Debug("----");
var byTotal = builderStats.OrderByDescending(kv => kv.Value.Total);
foreach (var item in byTotal)
{
log.DebugFormat("# {0} ({1}x) => total: {1:F}s, average: {2:F}s", item.Key.Name, item.Value.Count, item.Value.Total.TotalSeconds, item.Value.Average.TotalSeconds);
var records = item.Value.All.OrderByDescending(r => r.Length);
foreach (var record in records)
{
log.DebugFormat(" - {0}: {1:F}s", record.Id, record.Length);
}
}
log.Debug("----");
}
}
}
| apache-2.0 | C# |
9055b2f0b09590afd179b6efe73cb52fe21219fc | Add dbus method to clear queue (bgo#635292) | GNOME/banshee,arfbtwn/banshee,GNOME/banshee,dufoli/banshee,lamalex/Banshee,stsundermann/banshee,ixfalia/banshee,GNOME/banshee,Dynalon/banshee-osx,arfbtwn/banshee,babycaseny/banshee,ixfalia/banshee,lamalex/Banshee,dufoli/banshee,mono-soc-2011/banshee,dufoli/banshee,ixfalia/banshee,stsundermann/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,ixfalia/banshee,Carbenium/banshee,Carbenium/banshee,dufoli/banshee,dufoli/banshee,GNOME/banshee,Dynalon/banshee-osx,ixfalia/banshee,mono-soc-2011/banshee,dufoli/banshee,dufoli/banshee,stsundermann/banshee,mono-soc-2011/banshee,lamalex/Banshee,babycaseny/banshee,Dynalon/banshee-osx,arfbtwn/banshee,babycaseny/banshee,Dynalon/banshee-osx,stsundermann/banshee,Carbenium/banshee,ixfalia/banshee,Carbenium/banshee,arfbtwn/banshee,Dynalon/banshee-osx,dufoli/banshee,stsundermann/banshee,lamalex/Banshee,ixfalia/banshee,babycaseny/banshee,arfbtwn/banshee,mono-soc-2011/banshee,GNOME/banshee,lamalex/Banshee,ixfalia/banshee,stsundermann/banshee,Dynalon/banshee-osx,lamalex/Banshee,mono-soc-2011/banshee,Carbenium/banshee,GNOME/banshee,GNOME/banshee,babycaseny/banshee,Carbenium/banshee,arfbtwn/banshee,arfbtwn/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,babycaseny/banshee,babycaseny/banshee,stsundermann/banshee,babycaseny/banshee,arfbtwn/banshee,GNOME/banshee,stsundermann/banshee | src/Extensions/Banshee.PlayQueue/Banshee.PlayQueue/IPlayQueue.cs | src/Extensions/Banshee.PlayQueue/Banshee.PlayQueue/IPlayQueue.cs | //
// IPlayQueue.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using NDesk.DBus;
namespace Banshee.PlayQueue
{
[Interface ("org.bansheeproject.Banshee.PlayQueue")]
public interface IPlayQueue
{
void EnqueueUri (string uri, bool prepend);
void Clear ();
}
}
| //
// IPlayQueue.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using NDesk.DBus;
namespace Banshee.PlayQueue
{
[Interface ("org.bansheeproject.Banshee.PlayQueue")]
public interface IPlayQueue
{
void EnqueueUri (string uri, bool prepend);
}
}
| mit | C# |
5bb0a21d9d683a76a0d611a658e0290c7f6bb9c3 | include 'source_type': The source balance this transfer came from. One of card, bank_account, bitcoin_receiver, or alipay_account (#692) | richardlawley/stripe.net,stripe/stripe-dotnet | src/Stripe.net/Services/Transfers/StripeTransferCreateOptions.cs | src/Stripe.net/Services/Transfers/StripeTransferCreateOptions.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeTransferCreateOptions
{
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("application_fee")]
public int? ApplicationFee { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[Obsolete("Use Destination or Connect instead.")]
[JsonProperty("recipient")]
public string Recipient { get; set; }
[JsonProperty("destination")]
public string Destination { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("bank_account")]
public string BankAccountId { get; set; }
[JsonProperty("card")]
public string CardId { get; set; }
[JsonProperty("statement_descriptor")]
public string StatementDescriptor { get; set; }
[JsonProperty("source_transaction")]
public string SourceTransaction { get; set; }
[JsonProperty("source_type")]
public string SourceType { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
}
}
| using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeTransferCreateOptions
{
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("application_fee")]
public int? ApplicationFee { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[Obsolete("Use Destination or Connect instead.")]
[JsonProperty("recipient")]
public string Recipient { get; set; }
[JsonProperty("destination")]
public string Destination { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("bank_account")]
public string BankAccountId { get; set; }
[JsonProperty("card")]
public string CardId { get; set; }
[JsonProperty("statement_descriptor")]
public string StatementDescriptor { get; set; }
[JsonProperty("source_transaction")]
public string SourceTransaction { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
}
}
| apache-2.0 | C# |
cc59f6f35c4f9162ad7d341726ad4c8eb73dbe83 | make BaseModelGuid abstract | Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017 | PhotoArtSystem/Data/PhotoArtSystem.Data.Common/Models/BaseModelGuid.cs | PhotoArtSystem/Data/PhotoArtSystem.Data.Common/Models/BaseModelGuid.cs | namespace PhotoArtSystem.Data.Common.Models
{
using System;
public abstract class BaseModelGuid : BaseModel<Guid>, IBaseModel<Guid>, IAuditInfo, IDeletableEntity
{
public BaseModelGuid()
{
this.Id = Guid.NewGuid();
}
}
}
| namespace PhotoArtSystem.Data.Common.Models
{
using System;
public class BaseModelGuid : BaseModel<Guid>, IBaseModel<Guid>, IAuditInfo, IDeletableEntity
{
public BaseModelGuid()
{
this.Id = Guid.NewGuid();
}
}
}
| mit | C# |
194f41eb0d90a390eb9c376218d44cc1599dfbbc | Add esimate query class. | bigfont/webapi-cors | CORS/Controllers/ValuesController.cs | CORS/Controllers/ValuesController.cs | using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
public class EstimateQuery
{
public string username { get; set; }
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
return new string[] { "This is a CORS request.", "That works from any origin." };
}
}
}
| using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
return new string[] { "This is a CORS request.", "That works from any origin." };
}
}
}
| mit | C# |
44007de31c3c77280b6564cf286582a81f3d89ae | Simplify the code that ensures a birthday is in the future. | jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes | ConsoleApps/Repack/Repack/Program.cs | ConsoleApps/Repack/Repack/Program.cs | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay - DateTime.Now;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
span = span.Add(TimeSpan.FromDays((years + 1) * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
if (birthDay < DateTime.Now)
{
if (birthDay.Year < DateTime.Now.Year)
{
return GetSpan(new DateTime(DateTime.Now.Year, birthDay.Month, birthDay.Day));
}
else
{
return GetSpan(new DateTime(DateTime.Now.Year + 1, birthDay.Month, birthDay.Day));
}
}
var span = birthDay - DateTime.Now;
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} | mit | C# |
558b6d74a3198756d5f5a1910f37f09802825393 | Check for null before calling Path.Combine on remoteDebug proxy folder. closes #746 | paladique/nodejstools,AustinHull/nodejstools,munyirik/nodejstools,AustinHull/nodejstools,mousetraps/nodejstools,mjbvz/nodejstools,kant2002/nodejstools,mjbvz/nodejstools,avitalb/nodejstools,mousetraps/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,mousetraps/nodejstools,avitalb/nodejstools,mjbvz/nodejstools,mjbvz/nodejstools,munyirik/nodejstools,munyirik/nodejstools,paladique/nodejstools,Microsoft/nodejstools,mousetraps/nodejstools,paulvanbrenk/nodejstools,avitalb/nodejstools,AustinHull/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,kant2002/nodejstools,paladique/nodejstools,avitalb/nodejstools,mjbvz/nodejstools,mousetraps/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,avitalb/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,AustinHull/nodejstools,paladique/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,AustinHull/nodejstools | Nodejs/Product/Nodejs/Commands/OpenRemoteDebugProxyFolderCommand.cs | Nodejs/Product/Nodejs/Commands/OpenRemoteDebugProxyFolderCommand.cs | //*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualStudioTools;
namespace Microsoft.NodejsTools.Commands {
internal sealed class OpenRemoteDebugProxyFolderCommand : Command {
private const string remoteDebugJsFileName = "RemoteDebug.js";
public override void DoCommand(object sender, EventArgs args) {
// Open explorer to folder
var remoteDebugProxyFolder = NodejsPackage.RemoteDebugProxyFolder;
if (string.IsNullOrWhiteSpace(remoteDebugProxyFolder)) {
MessageBox.Show("Could not find RemoteDebugProxyFolder", "Node.js Tools for Visual Studio");
return;
}
var filePath = Path.Combine(remoteDebugProxyFolder, remoteDebugJsFileName);
if (!File.Exists(filePath)) {
MessageBox.Show(String.Format("Remote Debug Proxy \"{0}\" does not exist.", filePath), "Node.js Tools for Visual Studio");
} else {
Process.Start("explorer", string.Format("/e,/select,{0}", filePath));
}
}
public override int CommandId {
get { return (int)PkgCmdId.cmdidOpenRemoteDebugProxyFolder; }
}
}
}
| //*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualStudioTools;
namespace Microsoft.NodejsTools.Commands {
internal sealed class OpenRemoteDebugProxyFolderCommand : Command {
public override void DoCommand(object sender, EventArgs args) {
// Open explorer to folder
var filePath = Path.Combine(NodejsPackage.RemoteDebugProxyFolder, "RemoteDebug.js");
if (!File.Exists(filePath)) {
MessageBox.Show(String.Format("Remote Debug Proxy \"{0}\" does not exist.", filePath), "Node.js Tools for Visual Studio");
} else {
Process.Start("explorer", string.Format("/e,/select,{0}", filePath));
}
}
public override int CommandId {
get { return (int)PkgCmdId.cmdidOpenRemoteDebugProxyFolder; }
}
}
}
| apache-2.0 | C# |
205e2a85607d242f182f7ff474b83d82b1805acb | Update demo | sunkaixuan/SqlSugar | Src/Asp.NetCore2/SqlSeverTest/SqliteTest/Demo/Demo5_SqlQueryable.cs | Src/Asp.NetCore2/SqlSeverTest/SqliteTest/Demo/Demo5_SqlQueryable.cs |
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class Demo5_SqlQueryable
{
public static void Init()
{
Console.WriteLine("");
Console.WriteLine("#### SqlQueryable Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.Sqlite,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
int total = 0;
var list = db.SqlQueryable<Order>("select * from `order`").ToPageList(1, 2, ref total);
//by expression
var list2 = db.SqlQueryable<Order>("select * from `order`").Where(it => it.Id == 1).ToPageList(1, 2);
//by sql
var list3 = db.SqlQueryable<Order>("select * from `order`").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
Console.WriteLine("#### SqlQueryable End ####");
}
}
}
|
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class Demo5_SqlQueryable
{
public static void Init()
{
Console.WriteLine("");
Console.WriteLine("#### SqlQueryable Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.Sqlite,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
int total = 0;
var list = db.SqlQueryable<Student>("select * from `order`").ToPageList(1, 2, ref total);
//by expression
var list2 = db.SqlQueryable<Student>("select * from `order`").Where(it => it.Id == 1).ToPageList(1, 2);
//by sql
var list3 = db.SqlQueryable<Student>("select * from `order`").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
Console.WriteLine("#### SqlQueryable End ####");
}
}
}
| apache-2.0 | C# |
e269d2e10bc15e07beb87d2a162617a0ed74eb86 | Update AssemblyInfo.cs | DHancock/Countdown | Countdown/Properties/AssemblyInfo.cs | Countdown/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Countdown")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Countdown => [email protected]")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("3.3.*")]
[assembly: AssemblyFileVersion("3.3.0.0")]
// make internal types visible to unit test project
[assembly: InternalsVisibleTo("Countdown.UnitTests")]
// keep the code analyzer happy
[assembly: CLSCompliant(true)]
| using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Countdown")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Countdown => [email protected]")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("3.2.*")]
[assembly: AssemblyFileVersion("3.2.0.0")]
// make internal types visible to unit test project
[assembly: InternalsVisibleTo("Countdown.UnitTests")]
// keep the code analyzer happy
[assembly: CLSCompliant(true)]
| unlicense | C# |
447b962ae6e5152dcbac8bd97b1d800537edb944 | Increase Version | cap9/EEPhysics | EEPhysics/Properties/AssemblyInfo.cs | EEPhysics/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("EEPhysics")]
[assembly: AssemblyDescription("A helper library for the game Everybody Edits for simulating player physics.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[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("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.4.4")]
[assembly: AssemblyFileVersion("1.4.4.4")]
| 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("EEPhysics")]
[assembly: AssemblyDescription("A helper library for the game Everybody Edits for simulating player physics.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[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("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.4.3")]
[assembly: AssemblyFileVersion("1.4.4.3")]
| mit | C# |
7e4f29cf7ca2c4284b5f61f485af0a1b23d66347 | Fix assembly autoincrementing. | kylegregory/EmmaSharp,MikeSmithDev/EmmaSharp | EmmaSharp/Properties/AssemblyInfo.cs | EmmaSharp/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("EmmaSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmmaSharp")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d4cb7bd-6721-4512-8c7e-c27dd68758f8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EmmaSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmmaSharp")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d4cb7bd-6721-4512-8c7e-c27dd68758f8")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.*")]
| mit | C# |
86e42c767916fd740a9ab388b41a68d7b9e81d48 | Improve comments. | weltkante/roslyn,gafter/roslyn,bartdesmet/roslyn,davkean/roslyn,bartdesmet/roslyn,brettfo/roslyn,gafter/roslyn,sharwell/roslyn,agocke/roslyn,sharwell/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,davkean/roslyn,genlu/roslyn,mavasani/roslyn,mavasani/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,eriawan/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,abock/roslyn,reaction1989/roslyn,tannergooding/roslyn,diryboy/roslyn,abock/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,genlu/roslyn,stephentoub/roslyn,physhi/roslyn,nguerrera/roslyn,eriawan/roslyn,tannergooding/roslyn,gafter/roslyn,heejaechang/roslyn,jmarolf/roslyn,diryboy/roslyn,genlu/roslyn,reaction1989/roslyn,mavasani/roslyn,physhi/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,heejaechang/roslyn,abock/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,tmat/roslyn,tmat/roslyn,agocke/roslyn,brettfo/roslyn,aelij/roslyn,stephentoub/roslyn,wvdd007/roslyn,AmadeusW/roslyn,tmat/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,agocke/roslyn,jmarolf/roslyn,physhi/roslyn,weltkante/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,aelij/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,davkean/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,wvdd007/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,eriawan/roslyn,jasonmalinowski/roslyn | src/Features/Core/Portable/CodeRefactorings/IRefactoringHelpersService.cs | src/Features/Core/Portable/CodeRefactorings/IRefactoringHelpersService.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 System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface IRefactoringHelpersService : ILanguageService
{
/// <summary>
/// <para>
/// Returns an array of <typeparamref name="TSyntaxNode"/> instances for refactoring given specified selection in document.
/// </para>
/// <para>
/// A <typeparamref name="TSyntaxNode"/> instance is returned if:
/// - Selection is zero-width and inside/touching a Token with direct parent of type <typeparamref name="TSyntaxNode"/>.
/// - Selection is zero-width and touching a Token whose ancestor of type <typeparamref name="TSyntaxNode"/> ends/starts precisely on current selection.
/// - Selection is zero-width and in whitespace that corresponds to a Token whose direct ancestor is of type of type <typeparamref name="TSyntaxNode"/>.
/// - Selection is zero-width and in a header (defined by ISyntaxFacts helpers) of an node of type of type <typeparamref name="TSyntaxNode"/>.
/// - Token whose direct parent of type <typeparamref name="TSyntaxNode"/> is selected.
/// - Selection is zero-width and wanted node is an expression / argument with selection within such syntax node (arbitrarily deep) on its first line.
/// - Whole node of a type <typeparamref name="TSyntaxNode"/> is selected.
/// </para>
/// <para>
/// Attempts extracting a Node of type <typeparamref name="TSyntaxNode"/> for each Node it considers (see above).
/// E.g. extracts initializer expressions from declarations and assignments, Property declaration from any header node, etc.
/// </para>
/// <para>
/// Note: this function trims all whitespace from both the beginning and the end of given <paramref name="selection"/>.
/// The trimmed version is then used to determine relevant <see cref="SyntaxNode"/>. It also handles incomplete selections
/// of tokens gracefully. Over-selection containing leading comments is also handled correctly.
/// </para>
/// </summary>
Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>(Document document, TextSpan selection, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode;
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface IRefactoringHelpersService : ILanguageService
{
/// <summary>
/// <para>
/// Returns an array of <typeparamref name="TSyntaxNode"/> instances for refactoring given specified selection in document.
/// </para>
/// <para>
/// A <typeparamref name="TSyntaxNode"/> instance is returned if:
/// - Selection is zero-width and inside/touching a Token with direct parent of type <typeparamref name="TSyntaxNode"/>.
/// - Selection is zero-width and touching a Token whose ancestor of type <typeparamref name="TSyntaxNode"/> ends/starts precisely on current selection.
/// - Selection is zero-width and in whitespace that corresponds to a Token whose direct ancestor is of type of type <typeparamref name="TSyntaxNode"/>.
/// - Selection is zero-width and in a header (defined by ISyntaxFacts helpers) of an node of type of type <typeparamref name="TSyntaxNode"/>.
/// - Token whose direct parent of type <typeparamref name="TSyntaxNode"/> is selected.
/// - Wanted node is an expression / argument and curent empty selection is within such syntax node (arbitrarily deep) on its first line.
/// - Whole node of a type <typeparamref name="TSyntaxNode"/> is selected.
/// </para>
/// <para>
/// Attempts extracting a Node of type <typeparamref name="TSyntaxNode"/> for each Node it considers (see above).
/// E.g. extracts initializer expressions from declarations and assignments, Property declaration from any header node, etc.
/// </para>
/// <para>
/// Note: this function trims all whitespace from both the beginning and the end of given <paramref name="selection"/>.
/// The trimmed version is then used to determine relevant <see cref="SyntaxNode"/>. It also handles incomplete selections
/// of tokens gracefully. Over-selection containing leading comments is also handled correctly.
/// </para>
/// </summary>
Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>(Document document, TextSpan selection, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode;
}
}
| mit | C# |
744c6e3cfe8a967400aaf17f93c0e86ffdbc3a97 | add more columns to admin summary | vankooch/BrockAllen.MembershipReboot,tomascassidy/BrockAllen.MembershipReboot,rajendra1809/BrockAllen.MembershipReboot,vinneyk/BrockAllen.MembershipReboot,DosGuru/MembershipReboot,rvdkooy/BrockAllen.MembershipReboot,brockallen/BrockAllen.MembershipReboot,eric-swann-q2/BrockAllen.MembershipReboot | BrockAllen.MembershipReboot.Mvc/Areas/Admin/Views/Home/Index.cshtml | BrockAllen.MembershipReboot.Mvc/Areas/Admin/Views/Home/Index.cshtml | @{
ViewBag.Title = "Index";
}
<h2>Accounts</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Tenant</th>
<th>Email</th>
<th>Created</th>
<th>Verified</th>
<th>Login Allowed</th>
<th>Account Closed</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
int id = item.ID;
string name = item.Username;
<tr>
<td>@Html.ActionLink(name, "Detail", new { id = id })</td>
<td>@item.Tenant</td>
<td>@item.Email</td>
<td>@item.Created</td>
<td>@item.IsAccountVerified</td>
<td>@item.IsLoginAllowed</td>
<td>@item.IsAccountClosed</td>
</tr>
}
</tbody>
</table>
| @{
ViewBag.Title = "Index";
}
<h2>Accounts</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Tenant</th>
<th>Email</th>
<th>Created</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
int id = item.ID;
string name = item.Username;
<tr>
<td>@Html.ActionLink(name, "Detail", new { id = id })</td>
<td>@item.Tenant</td>
<td>@item.Email</td>
<td>@item.Created</td>
</tr>
}
</tbody>
</table>
| bsd-3-clause | C# |
a1617d27efde531ec2b251cf7c63b8d51167d751 | revert new changes to quartz config related to persistence | linkelf/GridDomain,andreyleskov/GridDomain | GridDomain.Scheduling/Quartz/Configuration/PersistedQuartzConfig.cs | GridDomain.Scheduling/Quartz/Configuration/PersistedQuartzConfig.cs | using System;
using System.Collections.Specialized;
using GridDomain.Scheduling.Quartz.Retry;
namespace GridDomain.Scheduling.Quartz.Configuration
{
public class PersistedQuartzConfig : IQuartzConfig
{
private const string QuartzConnectionStringName = "Quartz";
public string ConnectionString => Environment.GetEnvironmentVariable(QuartzConnectionStringName)
?? "Server=localhost,1400; Database = Quartz; User = sa; Password = P@ssw0rd1; MultipleActiveResultSets = True";
public string StorageType => "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
public NameValueCollection Settings
=>
new NameValueCollection
{
["quartz.jobStore.type"] = StorageType,
["quartz.jobStore.clustered"] = "false",
["quartz.jobStore.dataSource"] = "default",
["quartz.jobStore.tablePrefix"] = "QRTZ_",
// ["quartz.jobStore.useProperties"] = "true",
["quartz.jobStore.lockHandler.type"] =
"Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz",
["quartz.dataSource.default.connectionString"] = ConnectionString,
["quartz.dataSource.default.provider"] = "SqlServer",
["quartz.scheduler.instanceId"] = "ScheduledEvents",
["quartz.serializer.type"] = "json"
};
public string Name { get; }
public IRetrySettings RetryOptions { get; set; } = new InMemoryRetrySettings();
}
} | using System;
using System.Collections.Specialized;
using GridDomain.Scheduling.Quartz.Retry;
namespace GridDomain.Scheduling.Quartz.Configuration
{
public class PersistedQuartzConfig : IQuartzConfig
{
private const string QuartzConnectionStringName = "Quartz";
public string ConnectionString => Environment.GetEnvironmentVariable(QuartzConnectionStringName)
?? "Server=localhost,1400; Database = Quartz; User = sa; Password = P@ssw0rd1; MultipleActiveResultSets = True";
public string StorageType => "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
public NameValueCollection Settings
=>
new NameValueCollection
{
["quartz.jobStore.type"] = StorageType,
["quartz.jobStore.clustered"] = "false",
["quartz.jobStore.dataSource"] = "default",
["quartz.jobStore.tablePrefix"] = "QRTZ_",
["quartz.jobStore.useProperties"] = "true",
["quartz.jobStore.lockHandler.type"] =
"Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz",
["quartz.dataSource.default.connectionString"] = ConnectionString,
["quartz.dataSource.default.provider"] = "SqlServer",
["quartz.scheduler.instanceId"] = "ScheduledEvents",
["quartz.serializer.type"] = "json"
};
public string Name { get; }
public IRetrySettings RetryOptions { get; set; } = new InMemoryRetrySettings();
}
} | apache-2.0 | C# |
e350d2c54f2d4e6bd81d8c93b927c2395349d641 | set save folder of ark as initial folder when selecting save file to import | cadon/ARKStatsExtractor | ARKBreedingStats/settings/ATImportFileLocationDialog.cs | ARKBreedingStats/settings/ATImportFileLocationDialog.cs | using System;
using System.IO;
using System.Windows.Forms;
using ARKBreedingStats.utils;
namespace ARKBreedingStats.settings
{
public partial class ATImportFileLocationDialog : Form
{
public ATImportFileLocation AtImportFileLocation
{
get => new ATImportFileLocation(textBox_ConvenientName.Text,
textBox_ServerName.Text, textBox_FileLocation.Text.Trim());
set
{
textBox_ConvenientName.Text = value.ConvenientName;
textBox_ServerName.Text = value.ServerName;
textBox_FileLocation.Text = value.FileLocation;
}
}
public ATImportFileLocationDialog(ATImportFileLocation fileLocation = null)
{
InitializeComponent();
if (fileLocation != null)
{
AtImportFileLocation = fileLocation;
}
}
private void button_FileSelect_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
if (!string.IsNullOrWhiteSpace(textBox_FileLocation.Text))
{
dlg.InitialDirectory = Path.GetDirectoryName(textBox_FileLocation.Text);
}
else if (ExportFolderLocation.GetListOfExportFolders(out var folders, out _))
{
foreach (var f in folders)
{
var savesFolderPath = Directory.GetParent(f.path)?.Parent?.FullName;
if (savesFolderPath != null && Directory.Exists(savesFolderPath))
{
dlg.InitialDirectory = savesFolderPath;
break;
}
}
}
dlg.FileName = Path.GetFileName(textBox_FileLocation.Text);
dlg.Filter = "ARK savegame (*.ark)|*.ark|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox_FileLocation.Text = dlg.FileName;
}
}
}
}
}
| using System;
using System.IO;
using System.Windows.Forms;
namespace ARKBreedingStats.settings
{
public partial class ATImportFileLocationDialog : Form
{
public ATImportFileLocation AtImportFileLocation
{
get => new ATImportFileLocation(textBox_ConvenientName.Text,
textBox_ServerName.Text, textBox_FileLocation.Text.Trim());
set
{
textBox_ConvenientName.Text = value.ConvenientName;
textBox_ServerName.Text = value.ServerName;
textBox_FileLocation.Text = value.FileLocation;
}
}
public ATImportFileLocationDialog(ATImportFileLocation fileLocation = null)
{
InitializeComponent();
if (fileLocation != null)
{
AtImportFileLocation = fileLocation;
}
}
private void button_FileSelect_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
if (!string.IsNullOrWhiteSpace(textBox_FileLocation.Text))
dlg.InitialDirectory = Path.GetDirectoryName(textBox_FileLocation.Text);
dlg.FileName = Path.GetFileName(textBox_FileLocation.Text);
dlg.Filter = "ARK savegame (*.ark)|*.ark|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox_FileLocation.Text = dlg.FileName;
}
}
}
}
}
| mit | C# |
4dcba802e8ec68a9ae5f7f30e3e2bb317c8850b5 | Add new command option "skipDetect" | cloudfoundry/windows_app_lifecycle,cloudfoundry-incubator/windows_app_lifecycle,stefanschneider/windows_app_lifecycle | Builder/Options.cs | Builder/Options.cs | using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[Option('k', "skipDetect", Required = false, HelpText = "")]
public string skipDetect { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
| using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Builder
{
public class Options
{
[Option('a', "buildDir", Required = true, HelpText = "")]
public string BuildDir { get; set; }
[Option('b', "buildArtifactsCacheDir", Required = false, HelpText = "")]
public string BuildArtifactsCacheDir { get; set; }
[Option('o', "buildpackOrder", Required = false, HelpText = "")]
public string BuildpackOrder { get; set; }
[Option('e', "buildpacksDir", Required = false, HelpText = "")]
public string BuildpacksDir { get; set; }
[Option('c', "outputBuildArtifactsCache", Required = false, HelpText = "")]
public string OutputBuildArtifactsCache { get; set; }
[Option('d', "outputDroplet", Required = true, HelpText = "")]
public string OutputDroplet { get; set; }
[Option('m', "outputMetadata", Required = true, HelpText = "")]
public string OutputMetadata { get; set; }
[Option('s', "skipCertVerify", Required = false, HelpText = "")]
public string SkipCertVerify { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
| apache-2.0 | C# |
31a76e20f1a7cbd0e26ca206cb91796b9919037d | Add note hit clip and tie audio to Time.timeScale | NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare,uulltt/NitoriWare | Assets/Resources/Microgames/RockBand/Scripts/RockBandContoller.cs | Assets/Resources/Microgames/RockBand/Scripts/RockBandContoller.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RockBandContoller : MonoBehaviour
{
public static RockBandContoller instance;
public RockBandNote[] notes;
public Animator kyoani, mystiaAnimator;
public RockBandLight[] lights;
public AudioClip victoryClip, failureClip, noteHitClip;
private AudioSource _audioSource;
private State state;
public enum State
{
Default,
Victory,
Failure,
Hit
}
void Awake()
{
instance = this;
_audioSource = GetComponent<AudioSource>();
_audioSource.pitch = Time.timeScale;
}
public void victory()
{
setState(State.Victory);
MicrogameController.instance.setVictory(true, true);
foreach (RockBandLight light in lights)
{
light.onVictory();
}
_audioSource.PlayOneShot(victoryClip);
}
public void failure()
{
setState(State.Failure);
MicrogameController.instance.setVictory(false, true);
for (int i = 0; i < notes.Length; i++)
{
notes[i].gameObject.SetActive(false);
}
_audioSource.PlayOneShot(failureClip);
}
void hitNote()
{
setState(State.Hit);
foreach (RockBandLight light in lights)
{
light.onHit();
}
_audioSource.PlayOneShot(noteHitClip);
}
void Update ()
{
if (state == State.Hit)
setState(State.Default);
if (state == State.Default && MicrogameTimer.instance.beatsLeft < 7f)
checkForInput();
}
void checkForInput()
{
if (Input.GetKeyDown(KeyCode.RightArrow)
|| Input.GetKeyDown(KeyCode.UpArrow)
|| Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.DownArrow))
{
for (int i = 0; i < notes.Length; i++)
{
if (notes[i].state == RockBandNote.State.InRange)
{
if (Input.GetKeyDown(notes[i].key))
{
notes[i].playNote();
if (i == notes.Length - 1)
victory();
else
{
hitNote();
}
}
else
{
failure();
}
return;
}
}
failure();
}
}
void setState(State state)
{
this.state = state;
kyoani.SetInteger("state", (int)state);
mystiaAnimator.SetInteger("state", (int)state);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RockBandContoller : MonoBehaviour
{
public static RockBandContoller instance;
public RockBandNote[] notes;
public Animator kyoani, mystiaAnimator;
public RockBandLight[] lights;
public AudioClip victoryClip, failureClip;
private AudioSource _audioSource;
private State state;
public enum State
{
Default,
Victory,
Failure,
Hit
}
void Awake()
{
instance = this;
_audioSource = GetComponent<AudioSource>();
}
public void victory()
{
setState(State.Victory);
MicrogameController.instance.setVictory(true, true);
foreach (RockBandLight light in lights)
{
light.onVictory();
}
_audioSource.PlayOneShot(victoryClip);
}
public void failure()
{
setState(State.Failure);
MicrogameController.instance.setVictory(false, true);
for (int i = 0; i < notes.Length; i++)
{
notes[i].gameObject.SetActive(false);
}
_audioSource.PlayOneShot(failureClip);
}
void hitNote()
{
setState(State.Hit);
foreach (RockBandLight light in lights)
{
light.onHit();
}
}
void Update ()
{
if (state == State.Hit)
setState(State.Default);
if (state == State.Default && MicrogameTimer.instance.beatsLeft < 7f)
checkForInput();
}
void checkForInput()
{
if (Input.GetKeyDown(KeyCode.RightArrow)
|| Input.GetKeyDown(KeyCode.UpArrow)
|| Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.DownArrow))
{
for (int i = 0; i < notes.Length; i++)
{
if (notes[i].state == RockBandNote.State.InRange)
{
if (Input.GetKeyDown(notes[i].key))
{
notes[i].playNote();
if (i == notes.Length - 1)
victory();
else
{
hitNote();
}
}
else
{
failure();
}
return;
}
}
failure();
}
}
void setState(State state)
{
this.state = state;
kyoani.SetInteger("state", (int)state);
mystiaAnimator.SetInteger("state", (int)state);
}
}
| mit | C# |
5f02daec4e3344553a035418414025e603440322 | Fix explosions with same source, and target pos (#5530) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs | Content.Server/Explosion/Components/ExplosionLaunchedComponent.cs | using Content.Server.Throwing;
using Content.Shared.Acts;
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
namespace Content.Server.Explosion.Components
{
[RegisterComponent]
public class ExplosionLaunchedComponent : Component, IExAct
{
public override string Name => "ExplosionLaunched";
void IExAct.OnExplosion(ExplosionEventArgs eventArgs)
{
if (Owner.Deleted)
return;
var sourceLocation = eventArgs.Source;
var targetLocation = Owner.EntityManager.GetComponent<TransformComponent>(eventArgs.Target).Coordinates;
if (sourceLocation.Equals(targetLocation)) return;
var offset = (targetLocation.ToMapPos(Owner.EntityManager) - sourceLocation.ToMapPos(Owner.EntityManager));
//Don't throw if the direction is center (0,0)
if (offset == Vector2.Zero) return;
var direction = offset.Normalized;
var throwForce = eventArgs.Severity switch
{
ExplosionSeverity.Heavy => 30,
ExplosionSeverity.Light => 20,
_ => 0,
};
Owner.TryThrow(direction, throwForce);
}
}
}
| using Content.Server.Throwing;
using Content.Shared.Acts;
using Robust.Shared.GameObjects;
namespace Content.Server.Explosion.Components
{
[RegisterComponent]
public class ExplosionLaunchedComponent : Component, IExAct
{
public override string Name => "ExplosionLaunched";
void IExAct.OnExplosion(ExplosionEventArgs eventArgs)
{
if (Owner.Deleted)
return;
var sourceLocation = eventArgs.Source;
var targetLocation = Owner.EntityManager.GetComponent<TransformComponent>(eventArgs.Target).Coordinates;
if (sourceLocation.Equals(targetLocation)) return;
var direction = (targetLocation.ToMapPos(Owner.EntityManager) - sourceLocation.ToMapPos(Owner.EntityManager)).Normalized;
var throwForce = eventArgs.Severity switch
{
ExplosionSeverity.Heavy => 30,
ExplosionSeverity.Light => 20,
_ => 0,
};
Owner.TryThrow(direction, throwForce);
}
}
}
| mit | C# |
bb41728c8ee5565e25b5284296535f56e2b576a1 | use int instead of uint | timothydonato/PnP,selossej/PnP,PaoloPia/PnP,jlsfernandez/PnP,IDTimlin/PnP,SimonDoy/PnP,SimonDoy/PnP,durayakar/PnP,ebbypeter/PnP,vnathalye/PnP,OfficeDev/PnP,Anil-Lakhagoudar/PnP,MaurizioPz/PnP,andreasblueher/PnP,edrohler/PnP,spdavid/PnP,BartSnyckers/PnP,perolof/PnP,werocool/PnP,brennaman/PnP,afsandeberg/PnP,werocool/PnP,dalehhirt/PnP,sndkr/PnP,rbarten/PnP,OfficeDev/PnP,JilleFloridor/PnP,ebbypeter/PnP,sandhyagaddipati/PnPSamples,JBeerens/PnP,srirams007/PnP,briankinsella/PnP,bstenberg64/PnP,zrahui/PnP,Rick-Kirkham/PnP,brennaman/PnP,sjuppuh/PnP,biste5/PnP,NavaneethaDev/PnP,weshackett/PnP,Chowdarysandhya/PnPTest,srirams007/PnP,vman/PnP,GSoft-SharePoint/PnP,comblox/PnP,JBeerens/PnP,vnathalye/PnP,bstenberg64/PnP,valt83/PnP,erwinvanhunen/PnP,sndkr/PnP,8v060htwyc/PnP,gautekramvik/PnP,markcandelora/PnP,Chowdarysandhya/PnPTest,valt83/PnP,Anil-Lakhagoudar/PnP,OneBitSoftware/PnP,IDTimlin/PnP,jeroenvanlieshout/PnP,hildabarbara/PnP,sjuppuh/PnP,comblox/PnP,darei-fr/PnP,russgove/PnP,PaoloPia/PnP,OzMakka/PnP,baldswede/PnP,durayakar/PnP,lamills1/PnP,svarukala/PnP,selossej/PnP,gavinbarron/PnP,erwinvanhunen/PnP,selossej/PnP,JBeerens/PnP,weshackett/PnP,PieterVeenstra/PnP,joaopcoliveira/PnP,biste5/PnP,OfficeDev/PnP,Claire-Hindhaugh/PnP,worksofwisdom/PnP,GSoft-SharePoint/PnP,vnathalye/PnP,timschoch/PnP,markcandelora/PnP,NavaneethaDev/PnP,Claire-Hindhaugh/PnP,bhoeijmakers/PnP,baldswede/PnP,SteenMolberg/PnP,patrick-rodgers/PnP,edrohler/PnP,mauricionr/PnP,yagoto/PnP,IvanTheBearable/PnP,dalehhirt/PnP,gautekramvik/PnP,briankinsella/PnP,IvanTheBearable/PnP,comblox/PnP,chrisobriensp/PnP,MaurizioPz/PnP,SteenMolberg/PnP,afsandeberg/PnP,svarukala/PnP,BartSnyckers/PnP,zrahui/PnP,8v060htwyc/PnP,sjuppuh/PnP,jlsfernandez/PnP,ebbypeter/PnP,yagoto/PnP,briankinsella/PnP,hildabarbara/PnP,sandhyagaddipati/PnPSamples,nishantpunetha/PnP,gautekramvik/PnP,rbarten/PnP,JilleFloridor/PnP,IDTimlin/PnP,joaopcoliveira/PnP,zrahui/PnP,rbarten/PnP,8v060htwyc/PnP,hildabarbara/PnP,IvanTheBearable/PnP,Chowdarysandhya/PnPTest,sandhyagaddipati/PnPSamples,tomvr2610/PnP,BartSnyckers/PnP,perolof/PnP,SimonDoy/PnP,gavinbarron/PnP,OzMakka/PnP,jeroenvanlieshout/PnP,OfficeDev/PnP,aammiitt2/PnP,vman/PnP,pdfshareforms/PnP,NexploreDev/PnP-PowerShell,aammiitt2/PnP,andreasblueher/PnP,erwinvanhunen/PnP,russgove/PnP,r0ddney/PnP,baldswede/PnP,timschoch/PnP,OneBitSoftware/PnP,valt83/PnP,SuryaArup/PnP,patrick-rodgers/PnP,tomvr2610/PnP,machadosantos/PnP,gavinbarron/PnP,spdavid/PnP,SteenMolberg/PnP,nishantpunetha/PnP,rroman81/PnP,jeroenvanlieshout/PnP,chrisobriensp/PnP,afsandeberg/PnP,MaurizioPz/PnP,GSoft-SharePoint/PnP,svarukala/PnP,machadosantos/PnP,brennaman/PnP,tomvr2610/PnP,SuryaArup/PnP,durayakar/PnP,r0ddney/PnP,OneBitSoftware/PnP,vman/PnP,bhoeijmakers/PnP,rroman81/PnP,machadosantos/PnP,russgove/PnP,OzMakka/PnP,andreasblueher/PnP,perolof/PnP,Claire-Hindhaugh/PnP,worksofwisdom/PnP,yagoto/PnP,SuryaArup/PnP,sndkr/PnP,pascalberger/PnP,Anil-Lakhagoudar/PnP,rroman81/PnP,timothydonato/PnP,nishantpunetha/PnP,r0ddney/PnP,worksofwisdom/PnP,spdavid/PnP,NexploreDev/PnP-PowerShell,weshackett/PnP,rgueldenpfennig/PnP,PaoloPia/PnP,dalehhirt/PnP,lamills1/PnP,srirams007/PnP,8v060htwyc/PnP,NexploreDev/PnP-PowerShell,aammiitt2/PnP,timschoch/PnP,edrohler/PnP,JilleFloridor/PnP,bhoeijmakers/PnP,Rick-Kirkham/PnP,werocool/PnP,rgueldenpfennig/PnP,pdfshareforms/PnP,OneBitSoftware/PnP,patrick-rodgers/PnP,markcandelora/PnP,lamills1/PnP,jlsfernandez/PnP,darei-fr/PnP,yagoto/PnP,pdfshareforms/PnP,NavaneethaDev/PnP,timothydonato/PnP,PieterVeenstra/PnP,joaopcoliveira/PnP,pascalberger/PnP,PaoloPia/PnP,biste5/PnP,mauricionr/PnP,PieterVeenstra/PnP,rgueldenpfennig/PnP,Rick-Kirkham/PnP,pascalberger/PnP,chrisobriensp/PnP,darei-fr/PnP,bstenberg64/PnP,mauricionr/PnP | OfficeDevPnP.Core/OfficeDevPnP.Core/Entities/StructuralNavigationEntity.cs | OfficeDevPnP.Core/OfficeDevPnP.Core/Entities/StructuralNavigationEntity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeDevPnP.Core.Entities
{
public class StructuralNavigationEntity
{
public StructuralNavigationEntity()
{
MaxDynamicItems = 20;
ShowSubsites = true;
ShowPages = false;
}
public bool ManagedNavigation { get; internal set; }
public bool ShowSubsites { get; set; }
public bool ShowPages { get; set; }
public int MaxDynamicItems { get; set; }
public bool ShowSiblings { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeDevPnP.Core.Entities
{
public class StructuralNavigationEntity
{
public StructuralNavigationEntity()
{
MaxDynamicItems = 20;
ShowSubsites = true;
ShowPages = false;
}
public bool ManagedNavigation { get; internal set; }
public bool ShowSubsites { get; set; }
public bool ShowPages { get; set; }
public uint MaxDynamicItems { get; set; }
public bool ShowSiblings { get; set; }
}
}
| mit | C# |
3a4d34aa021841f608192e82e6068af72a1272e6 | Update ModelManager.cs | wangyaron/VRProject | TestGit/Assets/ModelManager.cs | TestGit/Assets/ModelManager.cs | using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 5;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
| using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 2;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
| apache-2.0 | C# |
539b2acbe3319ef19576bf754b3e01e9acb809ff | Fix NRE on app start | hongnguyenpro/monotouch-samples,kingyond/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,sakthivelnagarajan/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,W3SS/monotouch-samples,W3SS/monotouch-samples,robinlaide/monotouch-samples,labdogg1003/monotouch-samples,labdogg1003/monotouch-samples,markradacz/monotouch-samples,a9upam/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nervevau2/monotouch-samples,haithemaraissia/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,xamarin/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,xamarin/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,albertoms/monotouch-samples,andypaul/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,sakthivelnagarajan/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,albertoms/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples | CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs | CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs | using System;
using System.Collections.Generic;
using CoreGraphics;
using CoreGraphics;
using Foundation;
using UIKit;
namespace CollectionViewTransition {
public class APLStackLayout : UICollectionViewLayout {
const int stackCount = 5;
List<float> angles;
List<UICollectionViewLayoutAttributes> attributesArray;
public APLStackLayout ()
{
angles = new List<float> (stackCount * 10);
}
public override void PrepareLayout ()
{
CGSize size = CollectionView.Bounds.Size;
CGPoint center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f);
int itemCount = (int)CollectionView.NumberOfItemsInSection (0);
if (attributesArray == null)
attributesArray = new List<UICollectionViewLayoutAttributes> (itemCount);
angles.Clear ();
float maxAngle = (float) (1 / Math.PI / 3.0f);
float minAngle = -maxAngle;
float diff = maxAngle - minAngle;
angles.Add (0);
for (int i = 1; i < stackCount * 10; i++) {
int hash = (int) (i * 2654435761 % 2 ^ 32);
hash = (int)(hash * 2654435761 % 2 ^ 32);
float currentAngle = (float) ((hash % 1000) / 1000.0 * diff) + minAngle;
angles.Add (currentAngle);
}
for (int i = 0; i < itemCount; i++) {
int angleIndex = i % (stackCount * 10);
float angle = angles [angleIndex];
var path = NSIndexPath.FromItemSection (i, 0);
UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path);
attributes.Size = new CGSize (150, 200);
attributes.Center = center;
attributes.Transform = CGAffineTransform.MakeRotation (angle);
attributes.Alpha = (i > stackCount) ? 0.0f : 1.0f;
attributes.ZIndex = (itemCount - i);
attributesArray.Add (attributes);
}
}
public override void InvalidateLayout ()
{
if (attributesArray != null) {
attributesArray.Clear ();
attributesArray = null;
}
}
public override CGSize CollectionViewContentSize {
get {
return CollectionView.Bounds.Size;
}
}
public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath indexPath)
{
return attributesArray [(int)indexPath.Item];
}
public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect)
{
return attributesArray.ToArray ();
}
}
}
| using System;
using System.Collections.Generic;
using CoreGraphics;
using CoreGraphics;
using Foundation;
using UIKit;
namespace CollectionViewTransition {
public class APLStackLayout : UICollectionViewLayout {
const int stackCount = 5;
List<float> angles;
List<UICollectionViewLayoutAttributes> attributesArray;
public APLStackLayout ()
{
angles = new List<float> (stackCount * 10);
}
public override void PrepareLayout ()
{
CGSize size = CollectionView.Bounds.Size;
CGPoint center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f);
int itemCount = (int)CollectionView.NumberOfItemsInSection (0);
if (attributesArray == null)
attributesArray = new List<UICollectionViewLayoutAttributes> (itemCount);
angles.Clear ();
float maxAngle = (float) (1 / Math.PI / 3.0f);
float minAngle = -maxAngle;
float diff = maxAngle - minAngle;
angles.Add (0);
for (int i = 1; i < stackCount * 10; i++) {
int hash = (int) (i * 2654435761 % 2 ^ 32);
hash = (int)(hash * 2654435761 % 2 ^ 32);
float currentAngle = (float) ((hash % 1000) / 1000.0 * diff) + minAngle;
angles.Add (currentAngle);
}
for (int i = 0; i < itemCount; i++) {
int angleIndex = i % (stackCount * 10);
float angle = angles [angleIndex];
var path = NSIndexPath.FromItemSection (i, 0);
UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path);
attributes.Size = new CGSize (150, 200);
attributes.Center = center;
attributes.Transform = CGAffineTransform.MakeRotation (angle);
attributes.Alpha = (i > stackCount) ? 0.0f : 1.0f;
attributes.ZIndex = (itemCount - i);
attributesArray.Add (attributes);
}
}
public override void InvalidateLayout ()
{
attributesArray.Clear ();
attributesArray = null;
}
public override CGSize CollectionViewContentSize {
get { return CollectionView.Bounds.Size; }
}
public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath indexPath)
{
return attributesArray [(int)indexPath.Item];
}
public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect)
{
return attributesArray.ToArray ();
}
}
}
| mit | C# |
dd53aa50bc0fa38839cbc0471bc8a6debe399013 | Add a method to get the assignments from a particular literal when it's used as a predicate | Logicalshift/Reason | LogicalShift.Reason/Solvers/SimpleSingleClauseSolver.cs | LogicalShift.Reason/Solvers/SimpleSingleClauseSolver.cs | using LogicalShift.Reason.Api;
using LogicalShift.Reason.Assignment;
using LogicalShift.Reason.Literals;
using LogicalShift.Reason.Unification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Represents a solver that can solve a single clause
/// </summary>
public class SimpleSingleClauseSolver : ISolver
{
/// <summary>
/// The clause that this will solve
/// </summary>
private readonly IClause _clause;
/// <summary>
/// The solver that will be used for subclauses
/// </summary>
private readonly ISolver _subclauseSolver;
public SimpleSingleClauseSolver(IClause clause, ISolver subclauseSolver)
{
if (clause == null) throw new ArgumentNullException("clause");
if (subclauseSolver == null) throw new ArgumentNullException("subclauseSolver");
_clause = clause;
_subclauseSolver = subclauseSolver;
}
/// <summary>
/// Retrieves an object representing the assignments for a particular literal when used as a predicate
/// </summary>
private PredicateAssignmentList GetAssignmentsFromPredicate(ILiteral predicate)
{
var result = new PredicateAssignmentList();
if (predicate.UnificationKey != null)
{
foreach (var argument in predicate.Dependencies)
{
result.AddArgument(argument);
}
}
return result;
}
public Task<IQueryResult> Solve(IEnumerable<ILiteral> goals)
{
throw new NotImplementedException();
}
public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
{
throw new NotImplementedException();
}
}
}
| using LogicalShift.Reason.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Represents a solver that can solve a single clause
/// </summary>
public class SimpleSingleClauseSolver : ISolver
{
/// <summary>
/// The clause that this will solve
/// </summary>
private readonly IClause _clause;
/// <summary>
/// The solver that will be used for subclauses
/// </summary>
private readonly ISolver _subclauseSolver;
public SimpleSingleClauseSolver(IClause clause, ISolver subclauseSolver)
{
if (clause == null) throw new ArgumentNullException("clause");
if (subclauseSolver == null) throw new ArgumentNullException("subclauseSolver");
_clause = clause;
_subclauseSolver = subclauseSolver;
}
public Task<IQueryResult> Solve(IEnumerable<ILiteral> goals)
{
throw new NotImplementedException();
}
public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
805c01ba52f27f5baab660c79d8104ee5d94f14a | Add base.Update call to Asteroid | iridinite/shiftdrive | Client/Asteroid.cs | Client/Asteroid.cs | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 7f;
}
public override void Update(GameState world, float deltaTime) {
base.Update(world, deltaTime);
}
public override bool IsTerrain() {
return true;
}
}
} | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 7f;
}
public override void Update(GameState world, float deltaTime) {
}
public override bool IsTerrain() {
return true;
}
}
} | bsd-3-clause | C# |
9a2374c81ce420c5dc8cce88d0c807d3dee4c9ff | Correct data extraction validator | SlicingDice/slicingdice-dot-net | Slicer/Utils/Validators/DataExtractionQueryValidator.cs | Slicer/Utils/Validators/DataExtractionQueryValidator.cs | using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Slicer.Utils.Validators
{
// Validates data extraction queries
public class DataExtractionQueryValidator
{
Dictionary<string, dynamic> Query;
public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
{
this.Query = query;
}
// Validate data extraction query, if the query is valid will return true
public bool Validator()
{
if (this.Query.ContainsKey("columns"))
{
var columns = this.Query["columns"];
if (columns is List<string>)
{
if (columns.Count > 10) {
throw new InvalidQueryException("The key 'columns' in data extraction result must have up to 10 columns.");
}
} else if(columns is string && columns != "all") {
throw new InvalidQueryException("The key 'columns' in data extraction result should be a list of columns or the 'all' keyword.");
}
}
return true;
}
}
}
| using Slicer.Utils.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Slicer.Utils.Validators
{
// Validates data extraction queries
public class DataExtractionQueryValidator
{
Dictionary<string, dynamic> Query;
public DataExtractionQueryValidator(Dictionary<string, dynamic> query)
{
this.Query = query;
}
// Validate data extraction query, if the query is valid will return true
public bool Validator()
{
if (this.Query.ContainsKey("columns"))
{
var columns = this.Query["columns"];
if (columns.Count > 10)
{
throw new InvalidQueryException("The key 'columns' in data extraction result must have up to 10 columns.");
}
}
return true;
}
}
}
| mit | C# |
c7a288eae65d61f4ddeb6f92a50ef79541764d37 | Add flag to enable/disable launching of IB each test | AnshulYADAV007/Lean,young-zhang/Lean,squideyes/Lean,Mendelone/forex_trading,AlexCatarino/Lean,young-zhang/Lean,Phoenix1271/Lean,mabeale/Lean,AlexCatarino/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,bizcad/Lean,AnshulYADAV007/Lean,bizcad/LeanJJN,andrewhart098/Lean,JKarathiya/Lean,devalkeralia/Lean,FrancisGauthier/Lean,bizcad/LeanJJN,kaffeebrauer/Lean,AnObfuscator/Lean,kaffeebrauer/Lean,bdilber/Lean,jameschch/Lean,Mendelone/forex_trading,Obawoba/Lean,dpavlenkov/Lean,tomhunter-gh/Lean,tomhunter-gh/Lean,young-zhang/Lean,squideyes/Lean,Jay-Jay-D/LeanSTP,bizcad/Lean,squideyes/Lean,bdilber/Lean,tomhunter-gh/Lean,redmeros/Lean,bizcad/LeanJJN,dpavlenkov/Lean,mabeale/Lean,Phoenix1271/Lean,mabeale/Lean,young-zhang/Lean,squideyes/Lean,kaffeebrauer/Lean,devalkeralia/Lean,QuantConnect/Lean,bizcad/Lean,QuantConnect/Lean,kaffeebrauer/Lean,bizcad/Lean,Mendelone/forex_trading,AnObfuscator/Lean,jameschch/Lean,jameschch/Lean,QuantConnect/Lean,AnshulYADAV007/Lean,Obawoba/Lean,Jay-Jay-D/LeanSTP,bdilber/Lean,dpavlenkov/Lean,Mendelone/forex_trading,Jay-Jay-D/LeanSTP,JKarathiya/Lean,StefanoRaggi/Lean,FrancisGauthier/Lean,AnObfuscator/Lean,AnshulYADAV007/Lean,bizcad/LeanJJN,andrewhart098/Lean,jameschch/Lean,jameschch/Lean,Obawoba/Lean,andrewhart098/Lean,Jay-Jay-D/LeanSTP,Phoenix1271/Lean,bdilber/Lean,JKarathiya/Lean,AnObfuscator/Lean,tomhunter-gh/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,devalkeralia/Lean,redmeros/Lean,Phoenix1271/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,FrancisGauthier/Lean,devalkeralia/Lean,QuantConnect/Lean,dpavlenkov/Lean,andrewhart098/Lean,kaffeebrauer/Lean,mabeale/Lean,redmeros/Lean,Obawoba/Lean,FrancisGauthier/Lean,AnshulYADAV007/Lean,JKarathiya/Lean,redmeros/Lean,StefanoRaggi/Lean | Tests/Brokerages/InteractiveBrokers/InteractiveBrokersOrderTests.cs | Tests/Brokerages/InteractiveBrokers/InteractiveBrokersOrderTests.cs | using System;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Brokerages.InteractiveBrokers;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Brokerages.InteractiveBrokers
{
[TestFixture, Ignore("These tests require the IBController and IB TraderWorkstation to be installed.")]
public class InteractiveBrokersForexOrderTests : BrokerageTests
{
// set to true to disable launch of gateway from tests
private const bool _manualGatewayControl = false;
private static bool _gatewayLaunched;
[TestFixtureSetUp]
public void InitializeBrokerage()
{
}
[TestFixtureTearDown]
public void DisposeBrokerage()
{
InteractiveBrokersGatewayRunner.Stop();
}
protected override Symbol Symbol
{
get { return Symbols.USDJPY; }
}
protected override SecurityType SecurityType
{
get { return SecurityType.Forex; }
}
protected override decimal HighPrice
{
get { return 10000m; }
}
protected override decimal LowPrice
{
get { return 0.01m; }
}
protected override decimal GetAskPrice(Symbol symbol)
{
throw new NotImplementedException();
}
protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, IHoldingsProvider holdingsProvider)
{
if (!_manualGatewayControl && !_gatewayLaunched)
{
_gatewayLaunched = true;
InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"),
Config.Get("ib-tws-dir"),
Config.Get("ib-user-name"),
Config.Get("ib-password"),
Config.GetBool("ib-use-tws")
);
}
return new InteractiveBrokersBrokerage(orderProvider);
}
protected override void DisposeBrokerage(IBrokerage brokerage)
{
if (!_manualGatewayControl && brokerage != null)
{
brokerage.Disconnect();
}
}
}
}
| using System;
using NUnit.Framework;
using QuantConnect.Brokerages.InteractiveBrokers;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Brokerages.InteractiveBrokers
{
[TestFixture, Ignore("These tests require the IBController and IB TraderWorkstation to be installed.")]
public class InteractiveBrokersForexOrderTests : BrokerageTests
{
private static bool _gatewayLaunched;
[TestFixtureSetUp]
public void InitializeBrokerage()
{
}
[TestFixtureTearDown]
public void DisposeBrokerage()
{
InteractiveBrokersGatewayRunner.Stop();
}
protected override Symbol Symbol
{
get { return Symbols.USDJPY; }
}
protected override SecurityType SecurityType
{
get { return SecurityType.Forex; }
}
protected override decimal HighPrice
{
get { return 10000m; }
}
protected override decimal LowPrice
{
get { return 0.01m; }
}
protected override decimal GetAskPrice(Symbol symbol)
{
throw new NotImplementedException();
}
protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, IHoldingsProvider holdingsProvider)
{
if (!_gatewayLaunched)
{
_gatewayLaunched = true;
InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"),
Config.Get("ib-tws-dir"),
Config.Get("ib-user-name"),
Config.Get("ib-password"),
Config.GetBool("ib-use-tws")
);
}
return new InteractiveBrokersBrokerage(orderProvider);
}
protected override void DisposeBrokerage(IBrokerage brokerage)
{
if (brokerage != null)
{
brokerage.Disconnect();
}
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.