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
00b82a215d30ceedb464360443eafb12a3a3a3a5
fix unit tests.
SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,grokys/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia
tests/Avalonia.Controls.UnitTests/WindowingPlatformMock.cs
tests/Avalonia.Controls.UnitTests/WindowingPlatformMock.cs
using System; using Moq; using Avalonia.Platform; namespace Avalonia.Controls.UnitTests { public class WindowingPlatformMock : IWindowingPlatform { private readonly Func<IWindowImpl> _windowImpl; private readonly Func<IPopupImpl> _popupImpl; public WindowingPlatformMock(Func<IWindowImpl> windowImpl = null, Func<IPopupImpl> popupImpl = null ) { _windowImpl = windowImpl; _popupImpl = popupImpl; } public IWindowImpl CreateWindow() { return _windowImpl?.Invoke() ?? Mock.Of<IWindowImpl>(x => x.RenderScaling == 1); } public IWindowImpl CreateEmbeddableWindow() { throw new NotImplementedException(); } public ITrayIconImpl CreateTrayIcon() { throw new NotImplementedException(); } public IPopupImpl CreatePopup() => _popupImpl?.Invoke() ?? Mock.Of<IPopupImpl>(x => x.RenderScaling == 1); } }
using System; using Moq; using Avalonia.Platform; namespace Avalonia.Controls.UnitTests { public class WindowingPlatformMock : IWindowingPlatform { private readonly Func<IWindowImpl> _windowImpl; private readonly Func<IPopupImpl> _popupImpl; public WindowingPlatformMock(Func<IWindowImpl> windowImpl = null, Func<IPopupImpl> popupImpl = null ) { _windowImpl = windowImpl; _popupImpl = popupImpl; } public IWindowImpl CreateWindow() { return _windowImpl?.Invoke() ?? Mock.Of<IWindowImpl>(x => x.RenderScaling == 1); } public IWindowImpl CreateEmbeddableWindow() { throw new NotImplementedException(); } public IPopupImpl CreatePopup() => _popupImpl?.Invoke() ?? Mock.Of<IPopupImpl>(x => x.RenderScaling == 1); } }
mit
C#
f52417298076dadb6238801be9861b872b3e4b65
Fix unit test build
helix-toolkit/helix-toolkit,JeremyAnsel/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using HelixToolkit.Wpf.SharpDX.Controls; using HelixToolkit.Wpf.SharpDX.Core2D; using HelixToolkit.Wpf.SharpDX.Model; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { using SharpDX.Utilities; class CanvasMock : IRenderCanvas { public IRenderHost RenderHost { private set; get; } = new DefaultRenderHost(); public double DpiScale { set; get; } public bool EnableDpiScale { set; get; } public event EventHandler<RelayExceptionEventArgs> ExceptionOccurred; public CanvasMock() { RenderHost.EffectsManager = new DefaultEffectsManager(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using HelixToolkit.Wpf.SharpDX.Controls; using HelixToolkit.Wpf.SharpDX.Core2D; using HelixToolkit.Wpf.SharpDX.Model; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { using SharpDX.Utilities; class CanvasMock : IRenderCanvas { public IRenderHost RenderHost { private set; get; } = new DefaultRenderHost(); public event EventHandler<RelayExceptionEventArgs> ExceptionOccurred; public CanvasMock() { RenderHost.EffectsManager = new DefaultEffectsManager(); } } }
mit
C#
32b3ea70b966e4087d70d72f1306f55b4fa8b264
Fix both covers showing if cover is not fully opaque
peppy/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu
osu.Game/Beatmaps/Drawables/UpdateableBeatmapSetCover.cs
osu.Game/Beatmaps/Drawables/UpdateableBeatmapSetCover.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; namespace osu.Game.Beatmaps.Drawables { public class UpdateableBeatmapSetCover : ModelBackedDrawable<BeatmapSetInfo> { private readonly BeatmapSetCoverType coverType; public BeatmapSetInfo BeatmapSet { get => Model; set => Model = value; } public new bool Masking { get => base.Masking; set => base.Masking = value; } public UpdateableBeatmapSetCover(BeatmapSetCoverType coverType = BeatmapSetCoverType.Cover) { this.coverType = coverType; InternalChild = new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(0.2f), }; } protected override double TransformDuration => 400.0; protected override DelayedLoadWrapper CreateDelayedLoadWrapper(Func<Drawable> createContentFunc, double timeBeforeLoad) => new DelayedLoadUnloadWrapper(createContentFunc, timeBeforeLoad); // by default, ModelBackedDrawable hides the old drawable only after the new one has been fully loaded. // this can lead to weird appearance if the cover is not fully opaque, so fade out as soon as a new load is requested in this particular case. protected override void OnLoadStarted() => ApplyHideTransforms(DisplayedDrawable); protected override Drawable CreateDrawable(BeatmapSetInfo model) { if (model == null) return null; return new BeatmapSetCover(model, coverType) { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; namespace osu.Game.Beatmaps.Drawables { public class UpdateableBeatmapSetCover : ModelBackedDrawable<BeatmapSetInfo> { private readonly BeatmapSetCoverType coverType; public BeatmapSetInfo BeatmapSet { get => Model; set => Model = value; } public new bool Masking { get => base.Masking; set => base.Masking = value; } public UpdateableBeatmapSetCover(BeatmapSetCoverType coverType = BeatmapSetCoverType.Cover) { this.coverType = coverType; InternalChild = new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(0.2f), }; } protected override double TransformDuration => 400.0; protected override DelayedLoadWrapper CreateDelayedLoadWrapper(Func<Drawable> createContentFunc, double timeBeforeLoad) => new DelayedLoadUnloadWrapper(createContentFunc, timeBeforeLoad); protected override Drawable CreateDrawable(BeatmapSetInfo model) { if (model == null) return null; return new BeatmapSetCover(model, coverType) { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, }; } } }
mit
C#
0ebd217236e3248e9837c70ca365522cf69a78be
Update AddingPictures.cs
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
Examples/CSharp/DrawingObjects/Pictures/AddingPictures.cs
Examples/CSharp/DrawingObjects/Pictures/AddingPictures.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.DrawingObjects.Pictures { public class AddingPictures { public static void Main(string[] args) { //Exstart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Workbook object int sheetIndex = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[sheetIndex]; //Adding a picture at the location of a cell whose row and column indices //are 5 in the worksheet. It is "F6" cell worksheet.Pictures.Add(5, 5, dataDir + "logo.jpg"); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.DrawingObjects.Pictures { public class AddingPictures { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Workbook object int sheetIndex = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[sheetIndex]; //Adding a picture at the location of a cell whose row and column indices //are 5 in the worksheet. It is "F6" cell worksheet.Pictures.Add(5, 5, dataDir + "logo.jpg"); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls"); } } }
mit
C#
9ee1d141ebf2fcfb9417a1d2d03f9435d4c88d21
fix build error
ObjectivityBSS/Test.Automation,ObjectivityLtd/Test.Automation
Objectivity.Test.Automation.Tests.PageObjects/PageObjects/TheInternet/BasicAuthPage.cs
Objectivity.Test.Automation.Tests.PageObjects/PageObjects/TheInternet/BasicAuthPage.cs
/* The MIT License (MIT) Copyright (c) 2015 Objectivity Bespoke Software Specialists Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Objectivity.Test.Automation.Tests.PageObjects.PageObjects.TheInternet { using System; using System.Globalization; using System.IO; using NLog; using Objectivity.Test.Automation.Common; using Objectivity.Test.Automation.Common.Extensions; using Objectivity.Test.Automation.Common.Helpers; using Objectivity.Test.Automation.Common.Types; using Objectivity.Test.Automation.Tests.PageObjects; public class BasicAuthPage : ProjectPageBase { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); /// <summary> /// Locators for elements /// </summary> private readonly ElementLocator downloadPageHeader = new ElementLocator(Locator.XPath, "//h3[.='Basic Auth']"), congratulationsInfo = new ElementLocator(Locator.CssSelector, ".example>p"); public BasicAuthPage(DriverContext driverContext) : base(driverContext) { Logger.Info("Waiting for File Download page to open"); this.Driver.IsElementPresent(this.downloadPageHeader, BaseConfiguration.ShortTimeout); } public string GetCongratulationsInfo { get { var text = this.Driver.GetElement(this.congratulationsInfo).Text; Logger.Info(CultureInfo.CurrentCulture, "Text from page '{0}'", text); return text; } } } }
/* The MIT License (MIT) Copyright (c) 2015 Objectivity Bespoke Software Specialists Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Objectivity.Test.Automation.Tests.PageObjects.PageObjects.TheInternet { using System; using System.Globalization; using System.IO; using NLog; using Objectivity.Test.Automation.Common; using Objectivity.Test.Automation.Common.Extensions; using Objectivity.Test.Automation.Common.Helpers; using Objectivity.Test.Automation.Common.Types; using Objectivity.Test.Automation.Tests.PageObjects; public class BasicAuthPage : ProjectPageBase { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); /// <summary> /// Locators for elements /// </summary> private readonly ElementLocator downloadPageHeader = new ElementLocator(Locator.XPath, "//h3[.='Basic Auth']"), congratulationsInfo = new ElementLocator(Locator.CssSelector, ".example>p"); public BasicAuthPage(DriverContext driverContext) : base(driverContext) { Logger.Info("Waiting for File Download page to open"); this.Driver.IsElementPresent(this.downloadPageHeader, BaseConfiguration.ShortTimeout); } public string GetcongratulationsInfo { get { var text = this.Driver.GetElement(this.congratulationsInfo).Text; Logger.Info("Text from page '{0}'", text); return text; } } } }
mit
C#
f2e9d40f9672ad4cc610f4f23c71beb8a423735c
Make the factory available.
adz21c/miles
Miles.MassTransit.Unity/UnityCompensateActivityFactory.cs
Miles.MassTransit.Unity/UnityCompensateActivityFactory.cs
using GreenPipes; using MassTransit; using MassTransit.Courier; using MassTransit.Courier.Hosts; using MassTransit.Logging; using MassTransit.Util; using Microsoft.Practices.Unity; using System; using System.Threading.Tasks; namespace Miles.MassTransit.Unity { public class UnityCompensateActivityFactory<TActivity, TLog> : CompensateActivityFactory<TActivity, TLog> where TActivity : class, CompensateActivity<TLog> where TLog : class { private static readonly ILog log = Logger.Get<UnityCompensateActivityFactory<TActivity, TLog>>(); private readonly IUnityContainer container; public UnityCompensateActivityFactory(IUnityContainer container) { this.container = container; } public async Task<ResultContext<CompensationResult>> Compensate(CompensateContext<TLog> context, IRequestPipe<CompensateActivityContext<TActivity, TLog>, CompensationResult> next) { using (var childContainer = container.CreateChildContainer()) { childContainer.RegisterInstance<ConsumeContext>(context.ConsumeContext) .RegisterInstance<IPublishEndpoint>(context) .RegisterInstance<ISendEndpointProvider>(context); var activity = childContainer.Resolve<TActivity>(); if (activity == null) throw new Exception($"Unable to resolve consumer type '{typeof(TActivity).FullName}'."); // TODO: Better exception if (log.IsDebugEnabled) log.DebugFormat("CompensateActivityFactory: Executing: {0}", TypeMetadataCache<TActivity>.ShortName); var activityContext = new HostCompensateActivityContext<TActivity, TLog>(activity, context); return await next.Send(activityContext).ConfigureAwait(false); } } } }
using GreenPipes; using MassTransit; using MassTransit.Courier; using MassTransit.Courier.Hosts; using MassTransit.Logging; using MassTransit.Util; using Microsoft.Practices.Unity; using System; using System.Threading.Tasks; namespace Miles.MassTransit.Unity { class UnityCompensateActivityFactory<TActivity, TLog> : CompensateActivityFactory<TActivity, TLog> where TActivity : class, CompensateActivity<TLog> where TLog : class { private static readonly ILog log = Logger.Get<UnityCompensateActivityFactory<TActivity, TLog>>(); private readonly IUnityContainer container; public UnityCompensateActivityFactory(IUnityContainer container) { this.container = container; } public async Task<ResultContext<CompensationResult>> Compensate(CompensateContext<TLog> context, IRequestPipe<CompensateActivityContext<TActivity, TLog>, CompensationResult> next) { using (var childContainer = container.CreateChildContainer()) { childContainer.RegisterInstance<ConsumeContext>(context.ConsumeContext) .RegisterInstance<IPublishEndpoint>(context) .RegisterInstance<ISendEndpointProvider>(context); var activity = childContainer.Resolve<TActivity>(); if (activity == null) throw new Exception($"Unable to resolve consumer type '{typeof(TActivity).FullName}'."); // TODO: Better exception if (log.IsDebugEnabled) log.DebugFormat("CompensateActivityFactory: Executing: {0}", TypeMetadataCache<TActivity>.ShortName); var activityContext = new HostCompensateActivityContext<TActivity, TLog>(activity, context); return await next.Send(activityContext).ConfigureAwait(false); } } } }
apache-2.0
C#
f90cb2a0096658d42933281e19d79d51f37a204a
add walletname property.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AddWalletPageViewModel.cs
WalletWasabi.Fluent/ViewModels/AddWalletPageViewModel.cs
using Avalonia.Input; using ReactiveUI; using WalletWasabi.Gui.Validation; namespace WalletWasabi.Fluent.ViewModels { public class AddWalletPageViewModel : NavBarItemViewModel { private string _walletName = ""; public AddWalletPageViewModel(IScreen screen) : base(screen) { Title = "Add Wallet"; } public override string IconName => "add_circle_regular"; public string WalletName { get => _walletName; set => this.RaiseAndSetIfChanged(ref _walletName, value); } } }
using ReactiveUI; namespace WalletWasabi.Fluent.ViewModels { public class AddWalletPageViewModel : NavBarItemViewModel { public AddWalletPageViewModel(IScreen screen) : base(screen) { Title = "Add Wallet"; } public override string IconName => "add_circle_regular"; } }
mit
C#
078dc05c3dcc72deb880bbfbf71a865f74936a4b
Fix delete Index #449 (#450)
xkproject/Orchard2,yiji/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,xkproject/Orchard2,jtkech/Orchard2,yiji/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,lukaskabrt/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,jtkech/Orchard2,yiji/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,lukaskabrt/Orchard2
src/Orchard.Cms.Web/Modules/Lucene/Views/Admin/Index.cshtml
src/Orchard.Cms.Web/Modules/Lucene/Views/Admin/Index.cshtml
@model AdminIndexViewModel <h1>@RenderTitleSegments(T["Indexes"])</h1> <nav class="admin-toolbar"> <div class="nav navbar-nav"> <a asp-route-action="Create" class="btn btn-primary" role="button">@T["Add Index"]</a> </div> </nav> <form asp-action="Index"> @* the form is nessecary to generate and antiforgery token for the delete action *@ @if (Model.Indexes.Any()) { <ul class="list-group"> @foreach (var entry in Model.Indexes) { <li class="list-group-item"> <div class="properties"> <div class="related float-xs-right"> <a asp-action="Query" asp-route-IndexName="@entry.Name" class="btn btn-success btn-sm" >@T["Query"]</a> <a asp-action="Reset" asp-route-id="@entry.Name" class="btn btn-primary btn-sm" data-message="@T["This will restart the indexing of all content items. Continue?"]" itemprop="UnsafeUrl">@T["Reset"]</a> <a asp-action="Rebuild" asp-route-id="@entry.Name" class="btn btn-warning btn-sm" data-message="@T["You index will be rebuilt, which might alter some services during the process. Continue?"]" itemprop="UnsafeUrl">@T["Rebuild"]</a> <a asp-action="Delete" asp-route-IndexName="@entry.Name" class="btn btn-danger btn-sm" itemprop="RemoveUrl UnsafeUrl">@T["Delete"]</a> </div> </div> <h5>@entry.Name</h5> </li> } </ul> } else { <div class="alert alert-info" role="alert"> @T["<strong>Nothing here!</strong> There are no indexes for the moment."] </div> } </form>
@model AdminIndexViewModel <h1>@RenderTitleSegments(T["Indexes"])</h1> <nav class="admin-toolbar"> <div class="nav navbar-nav"> <a asp-route-action="Create" class="btn btn-primary" role="button">@T["Add Index"]</a> </div> </nav> <form asp-action="Index"> @* the form is nessecary to generate and antiforgery token for the delete action *@ @if (Model.Indexes.Any()) { <ul class="list-group"> @foreach (var entry in Model.Indexes) { <li class="list-group-item"> <div class="properties"> <div class="related float-xs-right"> <a asp-action="Query" asp-route-IndexName="@entry.Name" class="btn btn-success btn-sm" >@T["Query"]</a> <a asp-action="Reset" asp-route-id="@entry.Name" class="btn btn-primary btn-sm" data-message="@T["This will restart the indexing of all content items. Continue?"]" itemprop="UnsafeUrl">@T["Reset"]</a> <a asp-action="Rebuild" asp-route-id="@entry.Name" class="btn btn-warning btn-sm" data-message="@T["You index will rebuilt, which might alter some services during the process. Continue?"]" itemprop="UnsafeUrl">@T["Rebuild"]</a> <a asp-action="Delete" asp-route-id="@entry.Name" class="btn btn-danger btn-sm" itemprop="RemoveUrl UnsafeUrl">@T["Delete"]</a> </div> </div> <h5>@entry.Name</h5> </li> } </ul> } else { <div class="alert alert-info" role="alert"> @T["<strong>Nothing here!</strong> There are no indexes for the moment."] </div> } </form>
bsd-3-clause
C#
1f4bea817f68f6dd8e1d1b600ad9e591dc22547c
Fix typo in Asp.Net 4.5 Sample app (Simple4)
SteelToeOSS/Configuration,SteelToeOSS/Configuration,SteelToeOSS/Configuration
samples/Simple4/Simple4/Views/Home/ConfigServerSettings.cshtml
samples/Simple4/Simple4/Views/Home/ConfigServerSettings.cshtml
@{ ViewBag.Title = "Configuration Settings for Spring Cloud Config Server"; } <h2>@ViewBag.Title.</h2> <h4>spring:cloud:config:enabled = @ViewBag.Enabled</h4> <h4>spring:cloud:config:env = @ViewBag.Environment</h4> <h4>spring:cloud:config:failFast = @ViewBag.FailFast</h4> <h4>spring:cloud:config:name = @ViewBag.Name</h4> <h4>spring:cloud:config:label = @ViewBag.Label</h4> <h4>spring:cloud:config:username = @ViewBag.Username</h4> <h4>spring:cloud:config:password = @ViewBag.Password</h4> <h4>spring:cloud:config:validate_certificates = @ViewBag.ValidateCertificates</h4>
@{ ViewBag.Title = "Configuration Settings for Spring Cloud Config Server"; } <h2>@ViewBag.Title.</h2> <h4>spring:cloud:config:enabled = @ViewBag.Enabled</h4> <h4>spring:cloud:config:env = @ViewBag.Environment</h4> <h4>spring:cloud:config:failFast = @ViewBag,FailFast</h4> <h4>spring:cloud:config:name = @ViewBag.Name</h4> <h4>spring:cloud:config:label = @ViewBag.Label</h4> <h4>spring:cloud:config:username = @ViewBag.Username</h4> <h4>spring:cloud:config:password = @ViewBag.Password</h4> <h4>spring:cloud:config:validate_certificates = @ViewBag.ValidateCertificates</h4>
apache-2.0
C#
aed69634f2a1e3c7b223af7bd7871ed109a8e2de
Introduce Null Argument check if context is null on RequestIgnorerManager
peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs
src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Http; namespace Glimpse.Agent.Web { public class DefaultRequestIgnorerManager : IRequestIgnorerManager { public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor) { RequestIgnorers = requestIgnorerProvider.Instances; HttpContextAccessor = httpContextAccessor; } private IEnumerable<IRequestIgnorer> RequestIgnorers { get; } private IHttpContextAccessor HttpContextAccessor { get; } public bool ShouldIgnore() { return ShouldIgnore(HttpContextAccessor.HttpContext); } public bool ShouldIgnore(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (RequestIgnorers.Any()) { foreach (var policy in RequestIgnorers) { if (policy.ShouldIgnore(context)) { return true; } } } return false; } } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Http; namespace Glimpse.Agent.Web { public class DefaultRequestIgnorerManager : IRequestIgnorerManager { public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor) { RequestIgnorers = requestIgnorerProvider.Instances; HttpContextAccessor = httpContextAccessor; } private IEnumerable<IRequestIgnorer> RequestIgnorers { get; } private IHttpContextAccessor HttpContextAccessor { get; } public bool ShouldIgnore() { return ShouldIgnore(HttpContextAccessor.HttpContext); } public bool ShouldIgnore(HttpContext context) { if (RequestIgnorers.Any()) { foreach (var policy in RequestIgnorers) { if (policy.ShouldIgnore(context)) { return true; } } } return false; } } }
mit
C#
0b2da4747b652a180f320851e13f420c16f67e3e
Make HelpCommand implement ICommand
appharbor/appharbor-cli
src/AppHarbor/HelpCommand.cs
src/AppHarbor/HelpCommand.cs
using System; namespace AppHarbor { public class HelpCommand : ICommand { public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
namespace AppHarbor { public class HelpCommand { } }
mit
C#
c72822227ee1cffe535370708c7d66813bc8f217
Fix AutomapHelper to only return assemblies decorated with IgnitionAutomapAttribute
sitecoreignition/Ignition.Foundation
Ignition.Foundation.Core/Automap/IgnitionAutomapHelper.cs
Ignition.Foundation.Core/Automap/IgnitionAutomapHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Ignition.Foundation.Core.Automap { public static class IgnitionAutomapHelper { public static IEnumerable<Assembly> GetAutomappedAssemblies() { var automappedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies() .Select(Assembly.Load) .Where(IsAutomappedAssembly) .ToList(); // load possible standalone assemblies automappedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies() .Where(IsAutomappedAssembly) .Where(a => !automappedAssemblies.Contains(a)) .Select(a => Assembly.Load(a.FullName))); return automappedAssemblies.ToList(); } public static IEnumerable<Assembly> GetAutomappedAssembliesInCurrentDomain() { var automappedAssemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(IsAutomappedAssembly) .Select(a => Assembly.Load(a.FullName)); return automappedAssemblies.ToList(); } public static bool IsAutomappedAssembly(Assembly assembly) { return assembly.GetCustomAttributes(typeof(IgnitionAutomapAttribute)).Any(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Ignition.Foundation.Core.Automap { public static class IgnitionAutomapHelper { public static IEnumerable<Assembly> GetAutomappedAssemblies() { var automappedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(Assembly.Load).ToList(); // load possible standalone assemblies automappedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies() .Where(IsAutomappedAssembly) .Where(a => !automappedAssemblies.Contains(a)) .Select(a => Assembly.Load(a.FullName))); return automappedAssemblies.ToList(); } public static IEnumerable<Assembly> GetAutomappedAssembliesInCurrentDomain() { var automappedAssemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(IsAutomappedAssembly) .Select(a => Assembly.Load(a.FullName)); return automappedAssemblies.ToList(); } public static bool IsAutomappedAssembly(Assembly assembly) { return assembly.GetCustomAttributes(typeof(IgnitionAutomapAttribute)).Any(); } } }
mit
C#
1662ac057c60789674ee699976d4c6b2e82ad725
Make internal property non-public.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatchCommand.cs
src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatchCommand.cs
using System.Data; using MySqlConnector.Core; namespace MySql.Data.MySqlClient { public sealed class MySqlBatchCommand : IMySqlCommand { public MySqlBatchCommand() : this(null) { } public MySqlBatchCommand(string? commandText) { CommandText = commandText; CommandType = CommandType.Text; } public string? CommandText { get; set; } public CommandType CommandType { get; set; } public CommandBehavior CommandBehavior { get; set; } public int RecordsAffected { get; set; } public MySqlParameterCollection Parameters => m_parameterCollection ??= new MySqlParameterCollection(); bool IMySqlCommand.AllowUserVariables => false; MySqlParameterCollection? IMySqlCommand.RawParameters => m_parameterCollection; MySqlConnection? IMySqlCommand.Connection => Batch?.Connection; long IMySqlCommand.LastInsertedId => m_lastInsertedId; PreparedStatements? IMySqlCommand.TryGetPreparedStatements() => null; void IMySqlCommand.SetLastInsertedId(long lastInsertedId) => m_lastInsertedId = lastInsertedId; MySqlParameterCollection? IMySqlCommand.OutParameters { get; set; } MySqlParameter? IMySqlCommand.ReturnParameter { get; set; } ICancellableCommand IMySqlCommand.CancellableCommand => Batch!; internal MySqlBatch? Batch { get; set; } MySqlParameterCollection? m_parameterCollection; long m_lastInsertedId; } }
using System.Data; using MySqlConnector.Core; namespace MySql.Data.MySqlClient { public sealed class MySqlBatchCommand : IMySqlCommand { public MySqlBatchCommand() : this(null) { } public MySqlBatchCommand(string? commandText) { CommandText = commandText; CommandType = CommandType.Text; } public string? CommandText { get; set; } public CommandType CommandType { get; set; } public bool AllowUserVariables => false; public CommandBehavior CommandBehavior { get; set; } public int RecordsAffected { get; set; } public MySqlParameterCollection Parameters => m_parameterCollection ??= new MySqlParameterCollection(); MySqlParameterCollection? IMySqlCommand.RawParameters => m_parameterCollection; MySqlConnection? IMySqlCommand.Connection => Batch?.Connection; long IMySqlCommand.LastInsertedId => m_lastInsertedId; PreparedStatements? IMySqlCommand.TryGetPreparedStatements() => null; void IMySqlCommand.SetLastInsertedId(long lastInsertedId) => m_lastInsertedId = lastInsertedId; MySqlParameterCollection? IMySqlCommand.OutParameters { get; set; } MySqlParameter? IMySqlCommand.ReturnParameter { get; set; } ICancellableCommand IMySqlCommand.CancellableCommand => Batch!; internal MySqlBatch? Batch { get; set; } MySqlParameterCollection? m_parameterCollection; long m_lastInsertedId; } }
mit
C#
0519330b59b8dcc536a4f8f4f31d4043aa48f5fe
Update CompositeTraceTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/CompositeTraceTelemeter.cs
TIKSN.Core/Analytics/Telemetry/CompositeTraceTelemeter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeTraceTelemeter : ITraceTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<ITraceTelemeter> traceTelemeters; public CompositeTraceTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<ITraceTelemeter> traceTelemeters) { this.commonConfiguration = commonConfiguration; this.traceTelemeters = traceTelemeters; } public async Task TrackTraceAsync(string message) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTraceAsync(message).ConfigureAwait(false); } catch (Exception ex) { Debug.WriteLine(ex); } } } } public async Task TrackTraceAsync(string message, TelemetrySeverityLevel severityLevel) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTraceAsync(message, severityLevel).ConfigureAwait(false); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeTraceTelemeter : ITraceTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<ITraceTelemeter> traceTelemeters; public CompositeTraceTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<ITraceTelemeter> traceTelemeters) { this.commonConfiguration = commonConfiguration; this.traceTelemeters = traceTelemeters; } public async Task TrackTrace(string message) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTrace(message); } catch (Exception ex) { Debug.WriteLine(ex); } } } } public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTrace(message, severityLevel); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
mit
C#
98329e42a2ee62ab2586007d4eba6dc98b355840
undo filtering non-Uri which doesn't work right
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Agent/Infrastructure/Repositories/UrlRepository.cs
src/FilterLists.Agent/Infrastructure/Repositories/UrlRepository.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using FilterLists.Agent.Core.Interfaces; using FilterLists.Agent.Features.Urls.Models.DataFileUrls; using FilterLists.Agent.Infrastructure.Clients; using RestSharp; namespace FilterLists.Agent.Infrastructure.Repositories { public class UrlRepository : IUrlRepository { private static readonly Dictionary<string, string> EntityUrlsEndpoints = new Dictionary<string, string> { {nameof(LicenseUrls), "licenses"}, {nameof(ListUrls), "lists"}, {nameof(MaintainerUrls), "maintainers"}, {nameof(SoftwareUrls), "software"}, {nameof(SyntaxUrls), "syntaxes"} }; private readonly IFilterListsApiClient _apiClient; public UrlRepository(IFilterListsApiClient apiClient) { _apiClient = apiClient; } public async Task<IEnumerable<Uri>> GetAllAsync<TModel>() { if (!EntityUrlsEndpoints.ContainsKey(typeof(TModel).Name)) throw new InvalidEnumArgumentException("The type of TModel is not valid."); var request = new RestRequest($"{EntityUrlsEndpoints[typeof(TModel).Name]}/seed"); var response = await _apiClient.ExecuteAsync<IEnumerable<TModel>>(request); return response.SelectMany(r => r.GetType().GetProperties().Where(p => p.GetValue(r) != null).Select(p => (Uri)p.GetValue(r))); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using FilterLists.Agent.Core.Interfaces; using FilterLists.Agent.Features.Urls.Models.DataFileUrls; using FilterLists.Agent.Infrastructure.Clients; using RestSharp; namespace FilterLists.Agent.Infrastructure.Repositories { public class UrlRepository : IUrlRepository { private static readonly Dictionary<string, string> EntityUrlsEndpoints = new Dictionary<string, string> { {nameof(LicenseUrls), "licenses"}, {nameof(ListUrls), "lists"}, {nameof(MaintainerUrls), "maintainers"}, {nameof(SoftwareUrls), "software"}, {nameof(SyntaxUrls), "syntaxes"} }; private readonly IFilterListsApiClient _apiClient; public UrlRepository(IFilterListsApiClient apiClient) { _apiClient = apiClient; } public async Task<IEnumerable<Uri>> GetAllAsync<TModel>() { if (!EntityUrlsEndpoints.ContainsKey(typeof(TModel).Name)) throw new InvalidEnumArgumentException("The type of TModel is not valid."); var request = new RestRequest($"{EntityUrlsEndpoints[typeof(TModel).Name]}/seed"); var response = await _apiClient.ExecuteAsync<IEnumerable<TModel>>(request); return response.SelectMany(r => r.GetType().GetProperties().Where(p => p.GetType() == typeof(Uri) && p.GetValue(r) != null) .Select(p => (Uri)p.GetValue(r))); } } }
mit
C#
87fd77708be4f25275aa42bb3e13690f2f5d64fd
Fix delay bug on resetting
Curdflappers/UltimateTicTacToe
Assets/Resources/Scripts/game/controller/GameController.cs
Assets/Resources/Scripts/game/controller/GameController.cs
using UnityEngine; public class GameController : MonoBehaviour { GlobalGame game; public float previewTime, previewTimer, confirmTime, confirmTimer; public GlobalGame Game { get { return game; } set { game = value; } } public void Confirm() { game.Confirm(); } public void Undo() { game.Undo(); } public void Redo() { game.Redo(); } public void Reset() { confirmTimer = confirmTime; previewTimer = previewTime; GetComponent<GameInitialization>().ResetGame(); } void Update() { if (game.ActivePlayer() is AI && !game.GameOver()) { if(game.HasNextMove) { if (confirmTimer <= 0) { Game.Confirm(); confirmTimer = confirmTime; return; } else { confirmTimer -= Time.deltaTime; return; } } else { if (previewTimer <= 0) { Game.Preview(((AI)game.ActivePlayer()).BestMove()); previewTimer = previewTime; return; } else { previewTimer -= Time.deltaTime; return; } } } else { confirmTimer = confirmTime; previewTimer = previewTime; } } }
using UnityEngine; public class GameController : MonoBehaviour { GlobalGame game; public float previewTime, previewTimer, confirmTime, confirmTimer; public GlobalGame Game { get { return game; } set { game = value; } } public void Confirm() { game.Confirm(); } public void Undo() { game.Undo(); } public void Redo() { game.Redo(); } public void Reset() { GetComponent<GameInitialization>().ResetGame(); } void Update() { if (game.ActivePlayer() is AI && !game.GameOver()) { if(game.HasNextMove) { if (confirmTimer <= 0) { Game.Confirm(); confirmTimer = confirmTime; return; } else { confirmTimer -= Time.deltaTime; return; } } else { if (previewTimer <= 0) { Game.Preview(((AI)game.ActivePlayer()).BestMove()); previewTimer = previewTime; return; } else { previewTimer -= Time.deltaTime; return; } } } else { confirmTimer = confirmTime; previewTimer = previewTime; } } }
mit
C#
8527b470e810059d36fccf6979ef6582e09d5e77
Add comments, better error handling to new class.
andyfmiller/LtiLibrary
LtiLibrary.AspNet/Outcomes/v1/ImsxXmlMediaTypeModelBinder.cs
LtiLibrary.AspNet/Outcomes/v1/ImsxXmlMediaTypeModelBinder.cs
using LtiLibrary.Core.Outcomes.v1; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.IO; using System.Threading.Tasks; using System.Xml.Serialization; namespace LtiLibrary.AspNet.Outcomes.v1 { /// <summary> /// Use this ModelBinder to deserialize imsx_POXEnvelopeRequest XML. For example, /// <code>public ImsxXmlMediaTypeResult Post([ModelBinder(BinderType = typeof(ImsxXmlMediaTypeModelBinder))] imsx_POXEnvelopeType request)</code> /// </summary> public class ImsxXmlMediaTypeModelBinder : IModelBinder { private static readonly XmlSerializer ImsxRequestSerializer = new XmlSerializer(typeof(imsx_POXEnvelopeType), null, null, new XmlRootAttribute("imsx_POXEnvelopeRequest"), "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0"); public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); if (bindingContext.HttpContext?.Request == null || !bindingContext.HttpContext.Request.ContentType.Equals("application/xml")) { bindingContext.Result = ModelBindingResult.Failed(); } else { try { using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body)) { var model = ImsxRequestSerializer.Deserialize(reader); bindingContext.Result = ModelBindingResult.Success(model); } } catch { bindingContext.Result = ModelBindingResult.Failed(); } } return null; } } }
using System; using System.Threading.Tasks; using System.Xml.Serialization; using LtiLibrary.Core.Outcomes.v1; using Microsoft.AspNetCore.Mvc.ModelBinding; using System.IO; namespace LtiLibrary.AspNet.Outcomes.v1 { public class ImsxXmlMediaTypeModelBinder : IModelBinder { private static readonly XmlSerializer ImsxRequestSerializer = new XmlSerializer(typeof(imsx_POXEnvelopeType), null, null, new XmlRootAttribute("imsx_POXEnvelopeRequest"), "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0"); public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body)) { var model = ImsxRequestSerializer.Deserialize(reader); bindingContext.Result = ModelBindingResult.Success(model); } return null; } } }
apache-2.0
C#
c8ac4dbe21d5354032b8afda9e59ced7a212a620
Reduce contention on pointless lock
HelloKitty/317refactor
src/Rs317.Client.OpenTK/Rendering/OpenTKImageProducer.cs
src/Rs317.Client.OpenTK/Rendering/OpenTKImageProducer.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.CompilerServices; namespace Rs317.Sharp { public sealed class OpenTKImageProducer : BaseRsImageProducer<OpenTKRsGraphicsContext>, IOpenTKImageRenderable { private Bitmap image { get; } private FasterPixel FasterPixel { get; } public bool isDirty { get; private set; } = false; public IntPtr ImageDataPointer { get; } public Rectangle ImageLocation { get; private set; } public object SyncObject { get; } = new object(); private bool accessedPixelBuffer { get; set; } = false; public OpenTKImageProducer(int width, int height) : base(width, height) { image = new Bitmap(width, height); BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, image.PixelFormat); ImageDataPointer = data.Scan0; image.UnlockBits(data); FasterPixel = new FasterPixel(image); initDrawingArea(); ImageLocation = new Rectangle(0, 0, width, height); } public void ConsumeDirty() { lock (SyncObject) isDirty = false; } public override int[] pixels { get { accessedPixelBuffer = true; return base.pixels; } } protected override void OnBeforeInternalDrawGraphics(int x, int z) { method239(); } protected override void InternalDrawGraphics(int x, int y, IRSGraphicsProvider<OpenTKRsGraphicsContext> rsGraphicsProvider) { ImageLocation = new Rectangle(x, y, width, height); //It's only dirty if they accessed the pixel buffer. //TODO: We can optimize around this in the client itself. lock (SyncObject) { if(accessedPixelBuffer) isDirty = true; accessedPixelBuffer = false; } } private void method239() { FasterPixel.Lock(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { //Important to call base pixels here, 20% of time spent //in this loop was due to locking on the child pixels. int value = base.pixels[x + y * width]; //fastPixel.SetPixel(x, y, Color.FromArgb((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)); FasterPixel.SetPixel(x, y, (byte)(value >> 16), (byte)(value >> 8), (byte)value, 255); } } FasterPixel.Unlock(true); } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.CompilerServices; namespace Rs317.Sharp { public sealed class OpenTKImageProducer : BaseRsImageProducer<OpenTKRsGraphicsContext>, IOpenTKImageRenderable { private Bitmap image { get; } private FasterPixel FasterPixel { get; } public bool isDirty { get; private set; } = false; public IntPtr ImageDataPointer { get; } public Rectangle ImageLocation { get; private set; } public object SyncObject { get; } = new object(); private bool accessedPixelBuffer { get; set; } = false; public OpenTKImageProducer(int width, int height) : base(width, height) { image = new Bitmap(width, height); BitmapData data = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, image.PixelFormat); ImageDataPointer = data.Scan0; image.UnlockBits(data); FasterPixel = new FasterPixel(image); initDrawingArea(); ImageLocation = new Rectangle(0, 0, width, height); } public void ConsumeDirty() { lock (SyncObject) isDirty = false; } public override int[] pixels { get { lock (SyncObject) accessedPixelBuffer = true; return base.pixels; } } protected override void OnBeforeInternalDrawGraphics(int x, int z) { method239(); } protected override void InternalDrawGraphics(int x, int y, IRSGraphicsProvider<OpenTKRsGraphicsContext> rsGraphicsProvider) { ImageLocation = new Rectangle(x, y, width, height); //It's only dirty if they accessed the pixel buffer. //TODO: We can optimize around this in the client itself. lock (SyncObject) { if(accessedPixelBuffer) isDirty = true; accessedPixelBuffer = false; } } private void method239() { FasterPixel.Lock(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { int value = pixels[x + y * width]; //fastPixel.SetPixel(x, y, Color.FromArgb((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)); FasterPixel.SetPixel(x, y, (byte)(value >> 16), (byte)(value >> 8), (byte)value, 255); } } FasterPixel.Unlock(true); } } }
mit
C#
c67093ab9732fba87441c7d95eccebb7ac90637c
Add error message.
VSadov/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xasx/roslyn,MichalStrehovsky/roslyn,tmeschter/roslyn,sharwell/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,panopticoncentral/roslyn,dotnet/roslyn,davkean/roslyn,gafter/roslyn,bartdesmet/roslyn,stephentoub/roslyn,tannergooding/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,diryboy/roslyn,jmarolf/roslyn,paulvanbrenk/roslyn,dpoeschl/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,cston/roslyn,genlu/roslyn,DustinCampbell/roslyn,jcouv/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,aelij/roslyn,agocke/roslyn,tmat/roslyn,tmat/roslyn,VSadov/roslyn,diryboy/roslyn,wvdd007/roslyn,reaction1989/roslyn,tannergooding/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,DustinCampbell/roslyn,tmat/roslyn,nguerrera/roslyn,abock/roslyn,genlu/roslyn,weltkante/roslyn,physhi/roslyn,genlu/roslyn,tmeschter/roslyn,jcouv/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,abock/roslyn,AmadeusW/roslyn,nguerrera/roslyn,dotnet/roslyn,gafter/roslyn,OmarTawfik/roslyn,xasx/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,agocke/roslyn,wvdd007/roslyn,cston/roslyn,brettfo/roslyn,dpoeschl/roslyn,AlekseyTs/roslyn,diryboy/roslyn,davkean/roslyn,MichalStrehovsky/roslyn,jamesqo/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,weltkante/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,physhi/roslyn,nguerrera/roslyn,KirillOsenkov/roslyn,bkoelman/roslyn,mavasani/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,paulvanbrenk/roslyn,jamesqo/roslyn,eriawan/roslyn,bartdesmet/roslyn,wvdd007/roslyn,jamesqo/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,stephentoub/roslyn,bkoelman/roslyn,swaroop-sridhar/roslyn,cston/roslyn,OmarTawfik/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,davkean/roslyn,xasx/roslyn,DustinCampbell/roslyn,brettfo/roslyn,tannergooding/roslyn,tmeschter/roslyn,CyrusNajmabadi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,bkoelman/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mavasani/roslyn,agocke/roslyn,AmadeusW/roslyn,physhi/roslyn,jcouv/roslyn,abock/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,dpoeschl/roslyn
src/Workspaces/Core/Portable/VirtualChars/VirtualChar.cs
src/Workspaces/Core/Portable/VirtualChars/VirtualChar.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.VirtualChars { /// <summary> /// The Regex parser wants to work over an array of characters, however this array of characters /// is not the same as the array of characters a user types into a string in C# or VB. For example /// In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z" /// and the same as "\\\u007a". However, as these all have wildly different presentations for the /// user, there needs to be a way to map back the characters it sees ( '\' and 'z' ) back to the /// ranges of characters the user wrote. /// /// VirtualChar serves this purpose. It contains the interpretted value of any language character/ /// character-escape-sequence, as well as the original SourceText span where that interpretted /// character was created from. This allows the regex engine to both process regexes from any /// language uniformly, but then also produce trees and diagnostics that map back properly to /// the original source text locations that make sense to the user. /// </summary> internal struct VirtualChar : IEquatable<VirtualChar> { public readonly char Char; public readonly TextSpan Span; public VirtualChar(char @char, TextSpan span) { if (span.IsEmpty) { throw new ArgumentException("Span should not be empty.", nameof(span)); } Char = @char; Span = span; } public override bool Equals(object obj) => obj is VirtualChar vc && Equals(vc); public bool Equals(VirtualChar other) => Char == other.Char && Span == other.Span; public override int GetHashCode() { unchecked { var hashCode = 244102310; hashCode = hashCode * -1521134295 + Char.GetHashCode(); hashCode = hashCode * -1521134295 + Span.GetHashCode(); return hashCode; } } public static bool operator ==(VirtualChar char1, VirtualChar char2) => char1.Equals(char2); public static bool operator !=(VirtualChar char1, VirtualChar char2) => !(char1 == char2); public static implicit operator char(VirtualChar vc) => vc.Char; } }
// 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.VirtualChars { /// <summary> /// The Regex parser wants to work over an array of characters, however this array of characters /// is not the same as the array of characters a user types into a string in C# or VB. For example /// In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z" /// and the same as "\\\u007a". However, as these all have wildly different presentations for the /// user, there needs to be a way to map back the characters it sees ( '\' and 'z' ) back to the /// ranges of characters the user wrote. /// /// VirtualChar serves this purpose. It contains the interpretted value of any language character/ /// character-escape-sequence, as well as the original SourceText span where that interpretted /// character was created from. This allows the regex engine to both process regexes from any /// language uniformly, but then also produce trees and diagnostics that map back properly to /// the original source text locations that make sense to the user. /// </summary> internal struct VirtualChar : IEquatable<VirtualChar> { public readonly char Char; public readonly TextSpan Span; public VirtualChar(char @char, TextSpan span) { if (span.IsEmpty) { throw new ArgumentException(); } Char = @char; Span = span; } public override bool Equals(object obj) => obj is VirtualChar vc && Equals(vc); public bool Equals(VirtualChar other) => Char == other.Char && Span == other.Span; public override int GetHashCode() { unchecked { var hashCode = 244102310; hashCode = hashCode * -1521134295 + Char.GetHashCode(); hashCode = hashCode * -1521134295 + Span.GetHashCode(); return hashCode; } } public static bool operator ==(VirtualChar char1, VirtualChar char2) => char1.Equals(char2); public static bool operator !=(VirtualChar char1, VirtualChar char2) => !(char1 == char2); public static implicit operator char(VirtualChar vc) => vc.Char; } }
mit
C#
286c0a3920bf0a4609d52b0aaa00cf64e5a05bb3
Update hash.
msbahrul/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,msbahrul/EventStore,msbahrul/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,ianbattersby/EventStore
src/EventStore/EventStore.Common/Version/Version.cs
src/EventStore/EventStore.Common/Version/Version.cs
namespace EventStore.Common.Version { public static class EventStoreVersion { public const string Version = "1.0.0"; public const string Hashtag = "1c7b48c6fb1c115213239e16ac3844735ec5a88e"; public const string Branch = "master"; } }
namespace EventStore.Common.Version { public static class EventStoreVersion { public const string Version = "1.0.0"; public const string Hashtag = "06262f4c06d380e9a446002ec88f46c90a928403"; public const string Branch = "master"; } }
bsd-3-clause
C#
dcbd015aefabc3e0da81b94500574c141bd44aa2
Add missing company attributes
intercom/intercom-dotnet
src/Intercom/Data/Company.cs
src/Intercom/Data/Company.cs
using System; using Intercom.Core; using System.Collections.Generic; namespace Intercom.Data { public class Company : Model { public bool? remove { set; get; } public string name { get; set; } public Plan plan { get; set; } public string company_id { get; set; } public long? remote_created_at { get; set; } public long? created_at { get; set; } public long? updated_at { get; set; } public long? last_request_at { get; set; } public int? monthly_spend { get; set; } public int? session_count { get; set; } public int? user_count { get; set; } public int? size { get; set; } public string website { get; set; } public string industry { get; set; } public Dictionary<String, Object> custom_attributes { get; set; } } }
using System; using Intercom.Core; using System.Collections.Generic; namespace Intercom.Data { public class Company : Model { public bool? remove { set; get; } public string name { get; set; } public Plan plan { get; set; } public string company_id { get; set; } public long? remote_created_at { get; set; } public long? created_at { get; set; } public long? updated_at { get; set; } public long? last_request_at { get; set; } public int? monthly_spend { get; set; } public int? session_count { get; set; } public int? user_count { get; set; } public Dictionary<String, Object> custom_attributes { get; set; } } }
apache-2.0
C#
de88433a3a3a0009cea53e421fdaa575aad98cae
Use more appropriate exception (can also never happen - JSON.NET uses the CanWrite property).
lloydjatkinson/Lloyd.AzureMailGateway
src/Lloyd.AzureMailGateway.Core/JsonConverters/AddressConverter.cs
src/Lloyd.AzureMailGateway.Core/JsonConverters/AddressConverter.cs
using System; using Lloyd.AzureMailGateway.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Lloyd.AzureMailGateway.Core.JsonConverters { public class AddressConverter : JsonConverter { public override bool CanConvert(Type objectType) => (objectType == typeof(Address)); public override bool CanWrite { get { return false; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jobject = JObject.Load(reader); var email = (string)jobject["eMail"]; var name = (string)jobject["name"]; return new Address(email, name); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new InvalidOperationException("AddressConverter is for read only usage."); } }
using System; using Lloyd.AzureMailGateway.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Lloyd.AzureMailGateway.Core.JsonConverters { public class AddressConverter : JsonConverter { public override bool CanConvert(Type objectType) => (objectType == typeof(Address)); public override bool CanWrite { get { return false; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jobject = JObject.Load(reader); var email = (string)jobject["eMail"]; var name = (string)jobject["name"]; return new Address(email, name); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException(); } }
mit
C#
a84700a2008def8d2853af9a2ba3d76222e63ce0
Update Salesforce Provider ID
developerforce/visual-studio-tools
src/Salesforce.VisualStudio.Services/ConnectedService/Constants.cs
src/Salesforce.VisualStudio.Services/ConnectedService/Constants.cs
namespace Salesforce.VisualStudio.Services.ConnectedService { /// <summary> /// Miscellaneous constants that are used across the Salesforce connected service implementation. /// </summary> internal static class Constants { public const string ConfigKey_ConsumerKey = "ConsumerKey"; public const string ConfigKey_ConsumerSecret = "ConsumerSecret"; public const string ConfigKey_Domain = "Domain"; public const string ConfigKey_RedirectUri = "RedirectUri"; public const string ConfigKey_UserName = "UserName"; public const string ConfigKey_Password = "Password"; public const string ConfigKey_SecurityToken = "SecurityToken"; public const string ConfigValue_RequiredDefault = "RequiredValue"; public const string ConfigValue_OptionalDefault = "OptionalValue"; // Core Connected Services relies on this id for the Salesforce breadcrumb functionality it provides. // Changing it here would break that functionality. public const string ProviderId = "Salesforce.ForceDotCom"; public const string SalesforceApiVersion = "32.0"; public const string SalesforceApiVersionWithPrefix = "v32.0"; public const string ServiceInstanceNameFormat = "Salesforce{0}"; public const string ModelsName = "Models"; public const string OAuthRedirectHandlerTypeName = "SalesforceOAuthRedirectHandler"; public const string OAuthRedirectHandlerNameFormat = "{0}OAuthRedirectHandler"; public const string OAuthRedirectHandlerPathFormat = "/{0}OAuthRedirectHandler.axd"; public const string Metadata_ConnectedAppType = "ConnectedApp"; public const string Header_OAuth = "OAuth"; public const string ProductionDomainUrl = "https://login.salesforce.com"; public const string SandboxDomainUrl = "https://test.salesforce.com"; public const string NextStepsUrl = "http://developer.salesforce.com/go/VSAddinDoc"; public const string MoreInfoLink = "http://developer.salesforce.com/go/VSMoreInfo"; public const string VisualStudioConnectedAppClientId = "3MVG9JZ_r.QzrS7gAjO9uCs2VkFkrvkiZiv9w9fBwzt4ds5YE4fN9VVa.3oTwr7KJKk.BZiPNekIw.d_yEVle"; } }
namespace Salesforce.VisualStudio.Services.ConnectedService { /// <summary> /// Miscellaneous constants that are used across the Salesforce connected service implementation. /// </summary> internal static class Constants { public const string ConfigKey_ConsumerKey = "ConsumerKey"; public const string ConfigKey_ConsumerSecret = "ConsumerSecret"; public const string ConfigKey_Domain = "Domain"; public const string ConfigKey_RedirectUri = "RedirectUri"; public const string ConfigKey_UserName = "UserName"; public const string ConfigKey_Password = "Password"; public const string ConfigKey_SecurityToken = "SecurityToken"; public const string ConfigValue_RequiredDefault = "RequiredValue"; public const string ConfigValue_OptionalDefault = "OptionalValue"; // Core Connected Services relies on this id for the Salesforce breadcrumb functionality it provides. // Changing it here would break that functionality. public const string ProviderId = "SalesforceConnectedService"; public const string SalesforceApiVersion = "32.0"; public const string SalesforceApiVersionWithPrefix = "v32.0"; public const string ServiceInstanceNameFormat = "Salesforce{0}"; public const string ModelsName = "Models"; public const string OAuthRedirectHandlerTypeName = "SalesforceOAuthRedirectHandler"; public const string OAuthRedirectHandlerNameFormat = "{0}OAuthRedirectHandler"; public const string OAuthRedirectHandlerPathFormat = "/{0}OAuthRedirectHandler.axd"; public const string Metadata_ConnectedAppType = "ConnectedApp"; public const string Header_OAuth = "OAuth"; public const string ProductionDomainUrl = "https://login.salesforce.com"; public const string SandboxDomainUrl = "https://test.salesforce.com"; public const string NextStepsUrl = "http://developer.salesforce.com/go/VSAddinDoc"; public const string MoreInfoLink = "http://developer.salesforce.com/go/VSMoreInfo"; public const string VisualStudioConnectedAppClientId = "3MVG9JZ_r.QzrS7gAjO9uCs2VkFkrvkiZiv9w9fBwzt4ds5YE4fN9VVa.3oTwr7KJKk.BZiPNekIw.d_yEVle"; } }
bsd-3-clause
C#
2fd5657eeb4eb06dfa8ea8c7a0220d71d4c9e62c
Update SDK version number
NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity
ncmb_unity/Assets/NCMB/CommonConstant.cs
ncmb_unity/Assets/NCMB/CommonConstant.cs
/******* Copyright 2017 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "3.2.0"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
/******* Copyright 2017 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mb.api.cloud.nifty.com";//ドメイン public static readonly string DOMAIN_URL = "https://mb.api.cloud.nifty.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "3.1.1"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
apache-2.0
C#
86674e60a5ea03f1c1a40ca2b999ffdc1b7b2a16
Fix service tests
tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server
tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs
tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs
using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Watchdog; namespace Tgstation.Server.Host.Service.Tests { /// <summary> /// Tests for <see cref="ServerService"/> /// </summary> [TestClass] public sealed class TestServerService { [TestMethod] public void TestConstructionAndDisposal() { Assert.ThrowsException<ArgumentNullException>(() => new ServerService(null, null, default)); var mockWatchdogFactory = new Mock<IWatchdogFactory>(); Assert.ThrowsException<ArgumentNullException>(() => new ServerService(mockWatchdogFactory.Object, null, default)); var mockLoggerFactory = new LoggerFactory(); new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default).Dispose(); } [TestMethod] public void TestRun() { var type = typeof(ServerService); var onStart = type.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic); var onStop = type.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic); var mockWatchdog = new Mock<IWatchdog>(); var args = Array.Empty<string>(); CancellationToken cancellationToken; mockWatchdog.Setup(x => x.RunAsync(args, It.IsAny<CancellationToken>())).Callback((string[] _, CancellationToken token) => cancellationToken = token).Returns(Task.CompletedTask).Verifiable(); var mockWatchdogFactory = new Mock<IWatchdogFactory>(); var mockLoggerFactory = new LoggerFactory(); mockWatchdogFactory.Setup(x => x.CreateWatchdog(mockLoggerFactory)).Returns(mockWatchdog.Object).Verifiable(); using (var service = new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default)) { onStart.Invoke(service, new object[] { args }); Assert.IsFalse(cancellationToken.IsCancellationRequested); onStop.Invoke(service, Array.Empty<object>()); Assert.IsTrue(cancellationToken.IsCancellationRequested); mockWatchdog.VerifyAll(); } mockWatchdogFactory.VerifyAll(); } } }
using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Watchdog; namespace Tgstation.Server.Host.Service.Tests { /// <summary> /// Tests for <see cref="ServerService"/> /// </summary> [TestClass] public sealed class TestServerService { [TestMethod] public void TestConstructionAndDisposal() { Assert.ThrowsException<ArgumentNullException>(() => new ServerService(null, null)); var mockWatchdogFactory = new Mock<IWatchdogFactory>(); Assert.ThrowsException<ArgumentNullException>(() => new ServerService(mockWatchdogFactory.Object, null)); var mockLoggerFactory = new LoggerFactory(); new ServerService(mockWatchdogFactory.Object, mockLoggerFactory).Dispose(); } [TestMethod] public void TestRun() { var type = typeof(ServerService); var onStart = type.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic); var onStop = type.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic); var mockWatchdog = new Mock<IWatchdog>(); var args = Array.Empty<string>(); CancellationToken cancellationToken; mockWatchdog.Setup(x => x.RunAsync(args, It.IsAny<CancellationToken>())).Callback((string[] _, CancellationToken token) => cancellationToken = token).Returns(Task.CompletedTask).Verifiable(); var mockWatchdogFactory = new Mock<IWatchdogFactory>(); var mockLoggerFactory = new LoggerFactory(); mockWatchdogFactory.Setup(x => x.CreateWatchdog(mockLoggerFactory)).Returns(mockWatchdog.Object).Verifiable(); using (var service = new ServerService(mockWatchdogFactory.Object, mockLoggerFactory)) { onStart.Invoke(service, new object[] { args }); Assert.IsFalse(cancellationToken.IsCancellationRequested); onStop.Invoke(service, Array.Empty<object>()); Assert.IsTrue(cancellationToken.IsCancellationRequested); mockWatchdog.VerifyAll(); } mockWatchdogFactory.VerifyAll(); } } }
agpl-3.0
C#
365e8555268b55182b5ec2fcd8d4c6708ecf8472
update anchor tags in home page
iordan93/TeamPompeii,iordan93/TeamPompeii,iordan93/TeamPompeii
PompeiiSquare/PompeiiSquare.Server/Views/Home/Index.cshtml
PompeiiSquare/PompeiiSquare.Server/Views/Home/Index.cshtml
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1 class="text-center">PompeiiSquare</h1> <p class="text-center">Find the best places to eat, drink, shop, or visit in any city in the world.</p> <div class="text-center"> <input name="looking-for" class="form-control input-lg" type="text" value="I'm looking for..."> <input name="location" class="form-control input-lg" type="text" value="Your location"> <a href="#" class="btn btn-success btn-lg">Search</a> </div> <div class="text-center"> <a href="@Url.Action("SearchByGroup", "Venues", new { id = "Drinks", Area = "VenueAdministrator" })" class="btn btn-default"><span class="glyphicon glyphicon-glass" aria-hidden="true"></span> Drinks</a> <a href="@Url.Action("SearchByGroup", "Venues", new { id = "Food", Area = "VenueAdministrator" })" class="btn btn-default"><span class="glyphicon glyphicon-cutlery" aria-hidden="true"></span> Food</a> <a href="@Url.Action("SearchByGroup", "Venues", new { id = "Fun", Area = "VenueAdministrator" })" class="btn btn-default"><span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span> Fun</a> <a href="@Url.Action("SearchByGroup", "Venues", new { id = "NightLife", Area = "VenueAdministrator" })" class="btn btn-default"><span class="glyphicon glyphicon-cd" aria-hidden="true"></span> Nightlife</a> <a href="@Url.Action("SearchByGroup", "Venues", new { id = "Shopping", Area = "VenueAdministrator" })" class="btn btn-default"><span class="glyphicon glyphicon-piggy-bank" aria-hidden="true"></span> Shopping</a> </div> </div>
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1 class="text-center">PompeiiSquare</h1> <p class="text-center">Find the best places to eat, drink, shop, or visit in any city in the world.</p> <div class="text-center"> <input name="looking-for" class="form-control input-lg" type="text" value="I'm looking for..."> <input name="location" class="form-control input-lg" type="text" value="Your location"> <a href="#" class="btn btn-success btn-lg">Search</a> </div> <div class="text-center"> <a href="#" class="btn btn-default"><span class="glyphicon glyphicon-glass" aria-hidden="true"></span> Drinks</a> <a href="#" class="btn btn-default"><span class="glyphicon glyphicon-cutlery" aria-hidden="true"></span> Food</a> <a href="#" class="btn btn-default"><span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span> Fun</a> <a href="#" class="btn btn-default"><span class="glyphicon glyphicon-cd" aria-hidden="true"></span> Nightlife</a> <a href="#" class="btn btn-default"><span class="glyphicon glyphicon-piggy-bank" aria-hidden="true"></span> Shopping</a> </div> </div>
mit
C#
3af94dfc36e1b9f353fe835f8f60553872cf5caa
Add SvgRect ctor from SvgNumber.
mntone/SvgForXaml
Mntone.SvgForXaml/Mntone.SvgForXaml.Shared/Primitives/SvgRect.cs
Mntone.SvgForXaml/Mntone.SvgForXaml.Shared/Primitives/SvgRect.cs
using System; using System.Linq; namespace Mntone.SvgForXaml.Primitives { [System.Diagnostics.DebuggerDisplay("Point = ({this.X}, {this.Y}), Size = {this.Width}x{this.Height}")] public struct SvgRect : IEquatable<SvgRect> { internal SvgRect(float x, float y, float width, float height) { this.X = x; this.Y = y; this.Width = width; this.Height = height; } internal SvgRect(SvgNumber x, SvgNumber y, SvgNumber width, SvgNumber height) { this.X = x.Value; this.Y = y.Value; this.Width = width.Value; this.Height = height.Value; } public float X { get; } public float Y { get; } public float Width { get; } public float Height { get; } internal static SvgRect? Parse(string attributeValue) { if (string.IsNullOrWhiteSpace(attributeValue)) return null; var s = attributeValue.Split(new[] { ' ' }).Select(t => float.Parse(t, System.Globalization.CultureInfo.InvariantCulture)).ToArray(); return new SvgRect(s[0], s[1], s[2], s[3]); } public bool Equals(SvgRect other) => this.X == other.X && this.Y == other.Y && this.Width == other.Width && this.Height == other.Height; } }
using System; using System.Linq; namespace Mntone.SvgForXaml.Primitives { [System.Diagnostics.DebuggerDisplay("Point = ({this.X}, {this.Y}), Size = {this.Width}x{this.Height}")] public struct SvgRect : IEquatable<SvgRect> { internal SvgRect(float x, float y, float width, float height) { this.X = x; this.Y = y; this.Width = width; this.Height = height; } public float X { get; } public float Y { get; } public float Width { get; } public float Height { get; } internal static SvgRect? Parse(string attributeValue) { if (string.IsNullOrWhiteSpace(attributeValue)) return null; var s = attributeValue.Split(new[] { ' ' }).Select(t => float.Parse(t, System.Globalization.CultureInfo.InvariantCulture)).ToArray(); return new SvgRect(s[0], s[1], s[2], s[3]); } public bool Equals(SvgRect other) => this.X == other.X && this.Y == other.Y && this.Width == other.Width && this.Height == other.Height; } }
mit
C#
955287b42b5aa8b6b78826f3402fbede02b8e54a
Fix display glitches.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Views/Shared/_OpenIdLoginBox.cshtml
src/CGO.Web/Views/Shared/_OpenIdLoginBox.cshtml
@using (Html.BeginForm("Authenticate", "User", routeValues: new { ReturnUrl = Request.QueryString["ReturnUrl"] }, method: FormMethod.Post, htmlAttributes: new { id = "openid_form" })) { <div id="openIdLogin" class="modal hide fade" style="width: 600px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3>Log In with OpenID</h3> </div> <div class="modal-body"> <input type="hidden" name="action" value="verify" /> <div id="openid_choice"> <p>Please choose the account you would like to log in with:</p> <div id="openid_btns"></div> </div> <div id="openid_input_area"> <input id="openid_identifier" name="openid_identifier" type="text" value="http://" /> </div> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Cancel</a> </div> </div> } @Styles.Render("~/bundles/openid-css") @Scripts.Render("~/bundles/openid") <script> (function () { openid.init('openid_identifier'); $('#openid_submit').addClass("btn btn-primary"); $('#openid_submit').css('margin-top', '-8px'); $('#openid_submit').css('margin-left', '5px'); $('#openid_submit').val('Log In'); })(); </script>
@using (Html.BeginForm("Authenticate", "User", routeValues: new { ReturnUrl = Request.QueryString["ReturnUrl"] }, method: FormMethod.Post, htmlAttributes: new { id = "openid_form" })) { <div id="openIdLogin" class="modal hide fade"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3>Log In with OpenID</h3> </div> <div class="modal-body"> <input type="hidden" name="action" value="verify" /> <div id="openid_choice"> <p>Please choose the account you would like to log in with:</p> <div id="openid_btns"></div> </div> <div id="openid_input_area"> <input id="openid_identifier" name="openid_identifier" type="text" value="http://" /> </div> </div> <div class="modal-footer"> <input type="submit" id="openid_submit" class="btn btn-primary" value="Log In" /> <a href="#" class="btn" data-dismiss="modal">Cancel</a> </div> </div> } @Styles.Render("~/bundles/openid-css") @Scripts.Render("~/bundles/openid") <script> (function () { openid.init('openid_identifier'); })() </script>
mit
C#
ba8cff6a2c8d25ed665e897139409e0e00da71c8
Use explicit visibility.
EzyWebwerkstaden/NHibernate.Caches.Redis,TheCloudlessSky/NHibernate.Caches.Redis
src/NHibernate.Caches.Redis/ObjectExtensions.cs
src/NHibernate.Caches.Redis/ObjectExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NHibernate.Caches.Redis { internal static class ObjectExtensions { public static T ThrowIfNull<T>(this T source) where T : class { if (source == null) throw new ArgumentNullException(); return source; } public static T ThrowIfNull<T>(this T source, string paramName) { if (source == null) throw new ArgumentNullException(paramName); return source; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NHibernate.Caches.Redis { static class ObjectExtensions { public static T ThrowIfNull<T>(this T source) where T : class { if (source == null) throw new ArgumentNullException(); return source; } public static T ThrowIfNull<T>(this T source, string paramName) { if (source == null) throw new ArgumentNullException(paramName); return source; } } }
mit
C#
5e5989e7d7b7e41f92e832f0ed09777df7299887
increment version
naymore/influxdb-lineprotocolwriter
Source/Rs.InfluxDb.LineProtocolWriter/Properties/AssemblyInfo.cs
Source/Rs.InfluxDb.LineProtocolWriter/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("Rs.InfluxDb.LineProtocolWriter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rs.InfluxDb.LineProtocolWriter")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("70363feb-1137-4e4a-bc57-2598d6fa123c")] // 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.3.0")] [assembly: AssemblyFileVersion("1.0.3.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("Rs.InfluxDb.LineProtocolWriter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rs.InfluxDb.LineProtocolWriter")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("70363feb-1137-4e4a-bc57-2598d6fa123c")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
apache-2.0
C#
6384838517825da4448c71384cfffd98ef0167af
Add BindCollectionChanged to IBindableList interface
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Bindables/IBindableList.cs
osu.Framework/Bindables/IBindableList.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Collections.Specialized; namespace osu.Framework.Bindables { /// <summary> /// An readonly interface which can be bound to other <see cref="IBindableList{T}"/>s in order to watch for state and content changes. /// </summary> /// <typeparam name="T">The type of value encapsulated by this <see cref="IBindableList{T}"/>.</typeparam> public interface IBindableList<T> : IReadOnlyList<T>, IBindable, INotifyCollectionChanged { /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableList<T> them); /// <summary> /// Bind an action to <see cref="INotifyCollectionChanged.CollectionChanged"/> with the option of running the bound action once immediately /// with an <see cref="NotifyCollectionChangedAction.Add"/> event for the entire contents of this <see cref="BindableList{T}"/>. /// </summary> /// <param name="onChange">The action to perform when this <see cref="BindableList{T}"/> changes.</param> /// <param name="runOnceImmediately">Whether the action provided in <paramref name="onChange"/> should be run once immediately.</param> void BindCollectionChanged(NotifyCollectionChangedEventHandler onChange, bool runOnceImmediately = false); /// <summary> /// An alias of <see cref="BindTo"/> provided for use in object initializer scenarios. /// Passes the provided value as the foreign (more permanent) bindable. /// </summary> new sealed IBindableList<T> BindTarget { set => BindTo(value); } /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> new IBindableList<T> GetBoundCopy(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Collections.Specialized; namespace osu.Framework.Bindables { /// <summary> /// An readonly interface which can be bound to other <see cref="IBindableList{T}"/>s in order to watch for state and content changes. /// </summary> /// <typeparam name="T">The type of value encapsulated by this <see cref="IBindableList{T}"/>.</typeparam> public interface IBindableList<T> : IReadOnlyList<T>, IBindable, INotifyCollectionChanged { /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableList<T> them); /// <summary> /// An alias of <see cref="BindTo"/> provided for use in object initializer scenarios. /// Passes the provided value as the foreign (more permanent) bindable. /// </summary> new sealed IBindableList<T> BindTarget { set => BindTo(value); } /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> new IBindableList<T> GetBoundCopy(); } }
mit
C#
fa004377c4a4ec5a58211dbdf837c1d205e1aa04
Add a rotating box for indication of a good game template state
EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
template-game/TemplateGame.Game/TemplateGameGame.cs
template-game/TemplateGame.Game/TemplateGameGame.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace TemplateGame.Game { public class TemplateGameGame : osu.Framework.Game { private Box box; [BackgroundDependencyLoader] private void load() { // Add your game components here. // The rotating box can be removed. Child = box = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.Orange, Size = new Vector2(200), }; box.Loop(b => b.RotateTo(0).RotateTo(360, 2500)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; namespace TemplateGame.Game { public class TemplateGameGame : osu.Framework.Game { [BackgroundDependencyLoader] private void load() { // Add your game components here } } }
mit
C#
fd8f2c5e8d806f95e3c6b3084f11565ff40e69ad
Fix the subscription drop script
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/ScriptBuilder/Writers/SubscriptionWriter.cs
src/ScriptBuilder/Writers/SubscriptionWriter.cs
using System.IO; using NServiceBus.Persistence.Sql.ScriptBuilder; class SubscriptionWriter { public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect) { var createPath = Path.Combine(scriptPath, "Subscription_Create.sql"); File.Delete(createPath); using (var writer = File.CreateText(createPath)) { SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect); } var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql"); File.Delete(dropPath); using (var writer = File.CreateText(dropPath)) { SubscriptionScriptBuilder.BuildDropScript(writer, sqlDialect); } } }
using System.IO; using NServiceBus.Persistence.Sql.ScriptBuilder; class SubscriptionWriter { public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect) { var createPath = Path.Combine(scriptPath, "Subscription_Create.sql"); File.Delete(createPath); using (var writer = File.CreateText(createPath)) { SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect); } var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql"); File.Delete(dropPath); using (var writer = File.CreateText(dropPath)) { SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect); } } }
mit
C#
c91df5de3e4b29292107e0b9920a39f8fb9a108f
Initialize Options.GeneratorKinds to a default value because of tests.
mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000
binder/Options.cs
binder/Options.cs
using System.Collections.Generic; using CppSharp; using CppSharp.Generators; namespace Embeddinator { public class Options : DriverOptions { /// <summary> /// The list of generators that will be targeted. /// </summary> public IEnumerable<GeneratorKind> GeneratorKinds = new List<GeneratorKind>(); /// <summary> /// The name of the library to be bound. /// </summary> public string LibraryName; // If true, will use unmanaged->managed thunks to call managed methods. // In this mode the JIT will generate specialized wrappers for marshaling // which will be faster but also lead to higher memory consumption. public bool UseUnmanagedThunks; // If true, will generate support files alongside generated binding code. public bool GenerateSupportFiles = true; } }
using System.Collections.Generic; using CppSharp; using CppSharp.Generators; namespace Embeddinator { public class Options : DriverOptions { /// <summary> /// The list of generators that will be targeted. /// </summary> public IEnumerable<GeneratorKind> GeneratorKinds; /// <summary> /// The name of the library to be bound. /// </summary> public string LibraryName; // If true, will use unmanaged->managed thunks to call managed methods. // In this mode the JIT will generate specialized wrappers for marshaling // which will be faster but also lead to higher memory consumption. public bool UseUnmanagedThunks; // If true, will generate support files alongside generated binding code. public bool GenerateSupportFiles = true; } }
mit
C#
38a17a02d1462d70294cc177c055f65aa7dd994c
Update HmacSigningCredentials.cs
cleftheris/IdentityModel
source/IdentityModel.Net45/Tokens/HmacSigningCredentials.cs
source/IdentityModel.Net45/Tokens/HmacSigningCredentials.cs
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IdentityModel.Tokens; using IdentityModel.Constants; namespace IdentityModel.Tokens { public class HmacSigningCredentials : SigningCredentials { public HmacSigningCredentials(string base64EncodedKey) : this(Convert.FromBase64String(base64EncodedKey)) { } public HmacSigningCredentials(byte[] key) : base(new InMemorySymmetricSecurityKey(key), CreateSignatureAlgorithm(key), CreateDigestAlgorithm(key)) { } protected static string CreateSignatureAlgorithm(byte[] key) { switch (key.Length) { case 32: return Algorithms.HmacSha256Signature; case 48: return Algorithms.HmacSha384Signature; case 64: return Algorithms.HmacSha512Signature; default: throw new InvalidOperationException("Unsupported key length"); } } protected static string CreateDigestAlgorithm(byte[] key) { switch (key.Length) { case 32: return Algorithms.Sha256Digest; case 48: return Algorithms.Sha384Digest; case 64: return Algorithms.Sha512Digest; default: throw new InvalidOperationException("Unsupported key length"); } } } }
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IdentityModel.Tokens; using IdentityModel.Constants; namespace IdentityModel.Tokens { public class HmacSigningCredentials : SigningCredentials { public HmacSigningCredentials(string base64EncodedKey) : this(Convert.FromBase64String(base64EncodedKey)) { } public HmacSigningCredentials(byte[] key) : base(new InMemorySymmetricSecurityKey(key), CreateSignatureAlgorithm(key), CreateDigestAlgorithm(key)) { } protected static string CreateSignatureAlgorithm(byte[] key) { switch (key.Length) { case 32: return Algorithms.HmacSha256Signature; case 48: return Algorithms.HmacSha384Signature; case 64: return Algorithms.HmacSha512Signature; default: throw new InvalidOperationException("Unsupported key lenght"); } } protected static string CreateDigestAlgorithm(byte[] key) { switch (key.Length) { case 32: return Algorithms.Sha256Digest; case 48: return Algorithms.Sha384Digest; case 64: return Algorithms.Sha512Digest; default: throw new InvalidOperationException("Unsupported key length"); } } } }
apache-2.0
C#
fd23f07cd9c48601f97c9556b58d53be2686d423
Make sure we receive a meaningful response
dirkrombauts/AppVeyor-Light
AppVeyorServices.IntegrationTests/AppVeyorGatewayTests.cs
AppVeyorServices.IntegrationTests/AppVeyorGatewayTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NFluent; using NUnit.Framework; namespace AppVeyorServices.IntegrationTests { [TestFixture] public class AppVeyorGatewayTests { [Test] public void GetProjects_Always_ReturnsListOfProjects() { var apiToken = System.Configuration.ConfigurationManager.AppSettings["ApiKey"]; var gateway = new AppVeyorGateway(apiToken); var projects = gateway.GetProjects(); Check.That(projects).IsNotNull(); var project = projects[0]; Check.That(project.Name).IsNotNull(); Check.That(project.Slug).IsNotNull(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NFluent; using NUnit.Framework; namespace AppVeyorServices.IntegrationTests { [TestFixture] public class AppVeyorGatewayTests { [Test] public void GetProjects_Always_ReturnsListOfProjects() { var apiToken = System.Configuration.ConfigurationManager.AppSettings["ApiKey"]; var gateway = new AppVeyorGateway(apiToken); var projects = gateway.GetProjects(); Check.That(projects).IsNotNull(); } } }
mit
C#
34fb112a7e93b5f659cc5b0303eee5f61ee2bc6b
Update title for NuGet name
techniq/Autofac.Integration.SharePoint
Autofac.Integration.SharePoint/Properties/AssemblyInfo.cs
Autofac.Integration.SharePoint/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("Autofac SharePoint Integration")] [assembly: AssemblyDescription("Autofac integration module for SharePoint.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sean Lynch")] [assembly: AssemblyProduct("Autofac.Integration.SharePoint")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("31ca8397-3769-41a0-a7f1-7f4e49dfb6e9")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
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("Autofac.Integration.SharePoint")] [assembly: AssemblyDescription("Autofac integration module for SharePoint.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sean Lynch")] [assembly: AssemblyProduct("Autofac.Integration.SharePoint")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("31ca8397-3769-41a0-a7f1-7f4e49dfb6e9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
dc0174e658c523b7a4699f2fb03b74bf2d123013
Add a blank line test
avinashbhujan/ASPVariables
ASPVariables/ASPVariables/SessionResultsPage.aspx.cs
ASPVariables/ASPVariables/SessionResultsPage.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ASPVariables { public partial class SessionResultsPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblResults.Text = (string)(Session["FirstName"]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ASPVariables { public partial class SessionResultsPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblResults.Text = (string)(Session["FirstName"]); } } }
apache-2.0
C#
96a33bec80d4af39b80f4ca38ddb0daf493eb2c8
test for validation
jacobpovar/MassTransit,SanSYS/MassTransit,jacobpovar/MassTransit,phatboyg/MassTransit,MassTransit/MassTransit,MassTransit/MassTransit,SanSYS/MassTransit,phatboyg/MassTransit
src/MassTransit.Tests/Configuration/When_configuration_fails.cs
src/MassTransit.Tests/Configuration/When_configuration_fails.cs
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.Tests.Configuration { using System; using System.Linq; using Configurators; using Exceptions; using Magnum.TestFramework; using NUnit.Framework; [TestFixture] public class When_configuration_fails { [Test] public void Should_include_the_configuration_results() { try { using (ServiceBusFactory.New(x => { })) { } Assert.Fail("An exception should have thrown for invalid configuration"); } catch (ConfigurationException ex) { ex.Result.Results.Any(x => x.Disposition == ValidationResultDisposition.Failure) .ShouldBeTrue("There were no failure results"); ex.Result.Results.Any(x => x.Key == "InputAddress") .ShouldBeTrue("There should have been an InputAddress violation"); } catch (Exception ex) { Assert.Fail("The exception type thrown was invalid: " + ex.GetType().Name); } } [Test] public void Should_validate_against_null() { try { using (ServiceBusFactory.New(x => { x.ReceiveFrom("loopback://localhost/a"); x.UseBusBuilder(null); })) { } Assert.Fail("bus builder was set to null"); } catch (ConfigurationException) { } } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.Tests.Configuration { using System; using System.Linq; using Configurators; using Exceptions; using Magnum.TestFramework; using NUnit.Framework; [TestFixture] public class When_configuration_fails { [Test] public void Should_include_the_configuration_results() { try { using (ServiceBusFactory.New(x => { })) { } Assert.Fail("An exception should have thrown for invalid configuration"); } catch (ConfigurationException ex) { ex.Result.Results.Any(x => x.Disposition == ValidationResultDisposition.Failure) .ShouldBeTrue("There were no failure results"); ex.Result.Results.Any(x => x.Key == "InputAddress") .ShouldBeTrue("There should have been an InputAddress violation"); } catch (Exception ex) { Assert.Fail("The exception type thrown was invalid: " + ex.GetType().Name); } } } }
apache-2.0
C#
d8be77743f94889891a44db9f975dc0c11ed25bb
Fix jet.
maximveksler/DrunkenAirplaneMechanik,maximveksler/DrunkenAirplaneMechanik,maximveksler/DrunkenAirplaneMechanik
Assets/Scripts/Components/Jet.cs
Assets/Scripts/Components/Jet.cs
using UnityEngine; using System.Collections; public class Jet : AirplaneComponent { public float thrustFactor = 10000.0f; // Use this for initialization void Start () { } // Update is called once per frame protected override void SimUpdate () { if (Input.GetKey(KeyCode.W)) { Bounds combinedBounds = new Bounds(transform.position, Vector3.zero); foreach (Renderer r in GetComponentsInChildren<Renderer>()) combinedBounds.Encapsulate(r.bounds); GetAirplane().rigidbody.AddForceAtPosition(transform.forward * -thrustFactor, combinedBounds.center); } } }
using UnityEngine; using System.Collections; public class Jet : AirplaneComponent { public float thrustFactor = 10000.0f; // Use this for initialization void Start () { } // Update is called once per frame protected override void SimUpdate () { if (Input.GetKeyDown(KeyCode.W)) { Bounds combinedBounds = new Bounds(transform.position, Vector3.zero); foreach (Renderer r in GetComponentsInChildren<Renderer>()) combinedBounds.Encapsulate(r.bounds); GetAirplane().rigidbody.AddForceAtPosition(transform.forward * -thrustFactor, combinedBounds.center); } } }
mit
C#
2a7e2c2617c6d11308297e7db9e6c07b7d2b361d
Tweak log download endpoint?
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/AdminController.cs
Battery-Commander.Web/Controllers/AdminController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { var data = System.IO.File.ReadAllBytes($@"logs\{DateTime.Today:yyyyMMdd}.log"); var mimeType = "text/plain"; return File(data, mimeType); } } }
mit
C#
f715c7863fc890a739993c32de7ef3b4807ede80
remove unrequired role from breadcrumb ul
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/stockportgov/Shared/Breadcrumb.cshtml
src/StockportWebapp/Views/stockportgov/Shared/Breadcrumb.cshtml
@model IEnumerable<StockportWebapp.Models.Crumb> <nav aria-label="Breadcrumb"> <div class="breadcrumb-container"> <div class="grid-container grid-100"> <ul class="breadcrumb"> <li>@Html.ActionLink("Home", "Index", "Home")</li> @{string title = ViewBag.Title != null ? ViewBag.Title.ToString() : "";} @{ foreach (var crumb in Model) { <li class="chevron">&rsaquo;</li> <li><a href="@crumb.NavigationLink">@crumb.Title</a></li> } } <li class="chevron">&rsaquo;</li> <li class="current"><span>@ViewBag.Title</span></li> </ul> </div> </div> </nav>
@model IEnumerable<StockportWebapp.Models.Crumb> <nav aria-label="Breadcrumb"> <div class="breadcrumb-container"> <div class="grid-container grid-100"> <ul class="breadcrumb" role="navigation"> <li>@Html.ActionLink("Home", "Index", "Home")</li> @{string title = ViewBag.Title != null ? ViewBag.Title.ToString() : "";} @{ foreach (var crumb in Model) { <li class="chevron">&rsaquo;</li> <li><a href="@crumb.NavigationLink">@crumb.Title</a></li> } } <li class="chevron">&rsaquo;</li> <li class="current"><span>@ViewBag.Title</span></li> </ul> </div> </div> </nav>
mit
C#
31c87887a0a7657270351f3c1014b5471b568c27
Add comments for F.False
farity/farity
Farity/False.cs
Farity/False.cs
namespace Farity { public static partial class F { /// <summary> /// A function that takes any arguments and returns false. /// </summary> /// <param name="args">Any arguments passed to the function.</param> /// <returns>false</returns> public static bool False(params object[] args) => false; } }
namespace Farity { public static partial class F { public static bool False(params object[] args) => false; } }
mit
C#
5e9f387cd6dfe329d23ba9058baaac4484e3d832
fix hotkey ofr paste
kommanderapp/kmd-uwp
kmd.Core/Explorer/Commands/PasteToCurrentFolderCommand.cs
kmd.Core/Explorer/Commands/PasteToCurrentFolderCommand.cs
using kmd.Core.Explorer.Commands.Configuration; using kmd.Core.Services.Contracts; using kmd.Core.Hotkeys; using kmd.Storage.Extensions; using System; using Windows.Storage; using Windows.System; using kmd.Core.Command; using kmd.Core.Explorer.Contracts; namespace kmd.Core.Explorer.Commands { [ExplorerCommand(modifierKey: ModifierKeys.Control, key: VirtualKey.V)] public class PasteToCurrentFolderCommand : ExplorerCommandBase { public PasteToCurrentFolderCommand(ICilpboardService cilpboardService, NavigateCommand navigateCommand) { _clipboardService = cilpboardService ?? throw new ArgumentNullException(nameof(cilpboardService)); _navigateCommand = navigateCommand ?? throw new ArgumentNullException(nameof(navigateCommand)); } protected readonly ICilpboardService _clipboardService; protected readonly NavigateCommand _navigateCommand; protected override bool OnCanExecute(IExplorerViewModel vm) { return true; } protected override async void OnExecute(IExplorerViewModel vm) { var pastedItem = _clipboardService.Get(); var storageItems = await pastedItem.GetStorageItemsAsync(); var changesMade = false; foreach (var item in storageItems) { if (item is IStorageFolder) { await (item as IStorageFolder).CopyContentsRecursiveAsync(vm.CurrentFolder, vm.CancellationTokenSource.Token); changesMade = true; } else if (item is IStorageFile) { await (item as IStorageFile).CopyAsync(vm.CurrentFolder, item.Name, NameCollisionOption.GenerateUniqueName); changesMade = true; } } if (changesMade) { // if changes made refresh view vm.CurrentFolder = vm.CurrentFolder; } } } }
using kmd.Core.Explorer.Commands.Configuration; using kmd.Core.Services.Contracts; using kmd.Core.Hotkeys; using kmd.Storage.Extensions; using System; using Windows.Storage; using Windows.System; using kmd.Core.Command; using kmd.Core.Explorer.Contracts; namespace kmd.Core.Explorer.Commands { [ExplorerCommand(modifierKey: ModifierKeys.Control, key: VirtualKey.Enter)] public class PasteToCurrentFolderCommand : ExplorerCommandBase { public PasteToCurrentFolderCommand(ICilpboardService cilpboardService, NavigateCommand navigateCommand) { _clipboardService = cilpboardService ?? throw new ArgumentNullException(nameof(cilpboardService)); _navigateCommand = navigateCommand ?? throw new ArgumentNullException(nameof(navigateCommand)); } protected readonly ICilpboardService _clipboardService; protected readonly NavigateCommand _navigateCommand; protected override bool OnCanExecute(IExplorerViewModel vm) { return true; } protected override async void OnExecute(IExplorerViewModel vm) { var pastedItem = _clipboardService.Get(); var storageItems = await pastedItem.GetStorageItemsAsync(); var changesMade = false; foreach (var item in storageItems) { if (item is IStorageFolder) { await (item as IStorageFolder).CopyContentsRecursiveAsync(vm.CurrentFolder, vm.CancellationTokenSource.Token); changesMade = true; } else if (item is IStorageFile) { await (item as IStorageFile).CopyAsync(vm.CurrentFolder, item.Name, NameCollisionOption.GenerateUniqueName); changesMade = true; } } if (changesMade) { // if changes made refresh view vm.CurrentFolder = vm.CurrentFolder; } } } }
apache-2.0
C#
41965151625062fd611cd765e5e8d63a0f217343
Fix region
domtheluck/yellowjacket,domtheluck/yellowjacket,domtheluck/yellowjacket,domtheluck/yellowjacket
YellowJacket/Test/YellowJacket.Dashboard.Test/TestBase.cs
YellowJacket/Test/YellowJacket.Dashboard.Test/TestBase.cs
// *********************************************************************** // Copyright (c) 2017 Dominik Lachance // // 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 AutoMapper; using YellowJacket.Dashboard.Mapping; namespace YellowJacket.Dashboard.Test { /// <summary> /// Test base class. /// </summary> public class TestBase { #region Protected Methods /// <summary> /// Gets the mapper. /// </summary> /// <returns><see cref="Mapper"/>.</returns> protected Mapper GetMapper() { MapperConfiguration config = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); }); return new Mapper(config); } #endregion } }
// *********************************************************************** // Copyright (c) 2017 Dominik Lachance // // 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 AutoMapper; using YellowJacket.Dashboard.Mapping; namespace YellowJacket.Dashboard.Test { /// <summary> /// Test base class. /// </summary> public class TestBase { #region Public Methods /// <summary> /// Gets the mapper. /// </summary> /// <returns><see cref="Mapper"/>.</returns> protected Mapper GetMapper() { MapperConfiguration config = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); }); return new Mapper(config); } #endregion } }
mit
C#
515e6ee9bffffd1194b01e02224025bf6d7202f6
Fix CoreCLR issues in Org.Apache.REEF.Client
jwang98052/incubator-reef,dongjoon-hyun/incubator-reef,apache/incubator-reef,shravanmn/reef,shravanmn/reef,apache/incubator-reef,dongjoon-hyun/incubator-reef,jwang98052/reef,apache/reef,apache/reef,apache/incubator-reef,jwang98052/incubator-reef,dongjoon-hyun/incubator-reef,apache/reef,jwang98052/reef,apache/incubator-reef,dougmsft/reef,apache/reef,singlis/reef,motus/reef,dongjoon-hyun/reef,motus/reef,dongjoon-hyun/incubator-reef,markusweimer/incubator-reef,jwang98052/incubator-reef,markusweimer/reef,motus/reef,jwang98052/reef,markusweimer/reef,apache/incubator-reef,motus/reef,motus/reef,markusweimer/reef,singlis/reef,apache/reef,apache/reef,jwang98052/reef,markusweimer/incubator-reef,markusweimer/reef,markusweimer/reef,dongjoon-hyun/reef,motus/reef,singlis/reef,dongjoon-hyun/reef,jwang98052/reef,dougmsft/reef,apache/incubator-reef,dougmsft/reef,shravanmn/reef,jwang98052/incubator-reef,dougmsft/reef,dongjoon-hyun/incubator-reef,apache/incubator-reef,dongjoon-hyun/incubator-reef,motus/reef,shravanmn/reef,markusweimer/incubator-reef,dongjoon-hyun/reef,markusweimer/reef,dongjoon-hyun/reef,singlis/reef,shravanmn/reef,jwang98052/reef,jwang98052/reef,markusweimer/incubator-reef,jwang98052/incubator-reef,dougmsft/reef,singlis/reef,jwang98052/incubator-reef,jwang98052/incubator-reef,apache/reef,markusweimer/incubator-reef,dougmsft/reef,dongjoon-hyun/incubator-reef,singlis/reef,shravanmn/reef,markusweimer/incubator-reef,dongjoon-hyun/reef,dougmsft/reef,dongjoon-hyun/reef,markusweimer/incubator-reef,shravanmn/reef,markusweimer/reef,singlis/reef
lang/cs/Org.Apache.REEF.Client/YARN/RESTClient/HttpClient.cs
lang/cs/Org.Apache.REEF.Client/YARN/RESTClient/HttpClient.cs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.Net.Http; using System.Threading; using System.Threading.Tasks; using Org.Apache.REEF.Tang.Annotations; namespace Org.Apache.REEF.Client.YARN.RestClient { /// <summary> /// Pass through HTTP client which calls into <see cref="System.Net.Http.HttpClient"/> /// </summary> internal class HttpClient : IHttpClient { private readonly System.Net.Http.HttpClient _httpClient; [Inject] private HttpClient(IYarnRestClientCredential yarnRestClientCredential) { _httpClient = new System.Net.Http.HttpClient( new HttpClientRetryHandler(new HttpClientHandler { Credentials = yarnRestClientCredential.Credentials }), disposeHandler: false); } public async Task<HttpResponseMessage> GetAsync(string requestResource, CancellationToken cancellationToken) { return await _httpClient.GetAsync(requestResource, cancellationToken); } public async Task<HttpResponseMessage> PostAsync(string requestResource, StringContent content, CancellationToken cancellationToken) { return await _httpClient.PostAsync(requestResource, content, cancellationToken); } public async Task<HttpResponseMessage> PutAsync(string requestResource, StringContent content, CancellationToken cancellationToken) { return await _httpClient.PutAsync(requestResource, content, cancellationToken); } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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.Net.Http; using System.Threading; using System.Threading.Tasks; using Org.Apache.REEF.Tang.Annotations; namespace Org.Apache.REEF.Client.YARN.RestClient { /// <summary> /// Pass through HTTP client which calls into <see cref="System.Net.Http.HttpClient"/> /// </summary> internal class HttpClient : IHttpClient { private readonly System.Net.Http.HttpClient _httpClient; [Inject] private HttpClient(IYarnRestClientCredential yarnRestClientCredential) { _httpClient = new System.Net.Http.HttpClient( new HttpClientRetryHandler(new WebRequestHandler { Credentials = yarnRestClientCredential.Credentials }), disposeHandler: false); } public async Task<HttpResponseMessage> GetAsync(string requestResource, CancellationToken cancellationToken) { return await _httpClient.GetAsync(requestResource, cancellationToken); } public async Task<HttpResponseMessage> PostAsync(string requestResource, StringContent content, CancellationToken cancellationToken) { return await _httpClient.PostAsync(requestResource, content, cancellationToken); } public async Task<HttpResponseMessage> PutAsync(string requestResource, StringContent content, CancellationToken cancellationToken) { return await _httpClient.PutAsync(requestResource, content, cancellationToken); } } }
apache-2.0
C#
93402d493816565aff1289cc3f5b6473cd5b600a
Fix data object reference.
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
XamarinApp/MyTrips/MyTrips.DataObjects/IOTHubData.cs
XamarinApp/MyTrips/MyTrips.DataObjects/IOTHubData.cs
using System; using System.Collections.Generic; using System.Text; namespace MyTrips.DataObjects { public class IOTHubData : BaseDataObject { public string Blob; } }
using Microsoft.Azure.Mobile.Server; using System; using System.Collections.Generic; using System.Text; namespace MyTrips.DataObjects { public class IOTHubData : EntityData { public string Blob; } }
mit
C#
018a2640fb2c4013b8de0f0c7a4c42a32534c13a
fix build error
NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,nataren/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack
tests/ServiceStack.WebHost.Endpoints.Tests/WsdlMetadataTests.cs
tests/ServiceStack.WebHost.Endpoints.Tests/WsdlMetadataTests.cs
using NUnit.Framework; using ServiceStack.ServiceHost; using ServiceStack.WebHost.Endpoints.Metadata; using ServiceStack.WebHost.Endpoints.Tests.Support; using ServiceStack.WebHost.Endpoints.Tests.Support.Operations; namespace ServiceStack.WebHost.Endpoints.Tests { [TestFixture] public class WsdlMetadataTests : MetadataTestBase { //private static ILog log = LogManager.GetLogger(typeof(WsdlMetadataTests)); [Test] public void Wsdl_state_is_correct() { var wsdlGenerator = new Soap11WsdlMetadataHandler(); var xsdMetadata = new XsdMetadata(Metadata); var wsdlTemplate = wsdlGenerator.GetWsdlTemplate(xsdMetadata, "http://w3c.org/types", false, "http://w3c.org/types"); Assert.That(wsdlTemplate.ReplyOperationNames, Is.EquivalentTo(xsdMetadata.GetReplyOperationNames(Format.Soap12))); Assert.That(wsdlTemplate.OneWayOperationNames, Is.EquivalentTo(xsdMetadata.GetOneWayOperationNames(Format.Soap12))); } [Test] public void Xsd_output_does_not_contain_xml_declaration() { var xsd = new XsdGenerator { OperationTypes = new[] { typeof(GetCustomer), typeof(GetCustomerResponse), typeof(GetCustomers), typeof(GetCustomersResponse), typeof(StoreCustomer) }, OptimizeForFlash = false, }.ToString(); Assert.That(!xsd.StartsWith("<?")); } [Test] public void XsdUtils_strips_all_xml_declarations() { #if no const string xsd = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<xs:schema xmlns:tns=\"http://schemas.sericestack.net/examples/types\" elementFormDefault=\"qualified\" targetNamespace=\"http://schemas.sericestack.net/examples/types\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + "<xs:complexType name=\"ArrayOfLong\">" + " <xs:sequence><xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"long\" type=\"xs:long\" /></xs:sequence>" + "</xs:complexType>"; const string xsds = xsd + xsd + xsd; #endif //var strippedXsd = XsdUtils.StripXmlDeclaration(xsds); //Assert.That(strippedXsd.IndexOf("<?"), Is.EqualTo(-1)); } } }
using NUnit.Framework; using ServiceStack.ServiceHost; using ServiceStack.WebHost.Endpoints.Metadata; using ServiceStack.WebHost.Endpoints.Tests.Support; using ServiceStack.WebHost.Endpoints.Tests.Support.Operations; namespace ServiceStack.WebHost.Endpoints.Tests { [TestFixture] public class WsdlMetadataTests : MetadataTestBase { //private static ILog log = LogManager.GetLogger(typeof(WsdlMetadataTests)); [Test] public void Wsdl_state_is_correct() { var wsdlGenerator = new Soap11WsdlMetadataHandler(); var xsdMetadata = new XsdMetadata(Metadata); var wsdlTemplate = wsdlGenerator.GetWsdlTemplate(xsdMetadata, "http://w3c.org/types", false, "http://w3c.org/types"); Assert.That(wsdlTemplate.ReplyOperationNames, Is.EquivalentTo(xsdMetadata.GetReplyOperationNames())); Assert.That(wsdlTemplate.OneWayOperationNames, Is.EquivalentTo(xsdMetadata.GetOneWayOperationNames())); } [Test] public void Xsd_output_does_not_contain_xml_declaration() { var xsd = new XsdGenerator { OperationTypes = new[] { typeof(GetCustomer), typeof(GetCustomerResponse), typeof(GetCustomers), typeof(GetCustomersResponse), typeof(StoreCustomer) }, OptimizeForFlash = false, }.ToString(); Assert.That(!xsd.StartsWith("<?")); } [Test] public void XsdUtils_strips_all_xml_declarations() { #if no const string xsd = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<xs:schema xmlns:tns=\"http://schemas.sericestack.net/examples/types\" elementFormDefault=\"qualified\" targetNamespace=\"http://schemas.sericestack.net/examples/types\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + "<xs:complexType name=\"ArrayOfLong\">" + " <xs:sequence><xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"long\" type=\"xs:long\" /></xs:sequence>" + "</xs:complexType>"; const string xsds = xsd + xsd + xsd; #endif //var strippedXsd = XsdUtils.StripXmlDeclaration(xsds); //Assert.That(strippedXsd.IndexOf("<?"), Is.EqualTo(-1)); } } }
bsd-3-clause
C#
4d035afcc6f93d808c28f4ebec36b26be2f1aee5
Add setting to bypass front-to-back
ppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,smoogipooo/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,ppy/osu
osu.Game/Overlays/Settings/Sections/Debug/GeneralSettings.cs
osu.Game/Overlays/Settings/Sections/Debug/GeneralSettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Show log overlay", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = "Performance logging", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging) }, new SettingsCheckbox { LabelText = "Bypass caching (slow)", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, new SettingsCheckbox { LabelText = "Bypass front-to-back render pass", Bindable = config.GetBindable<bool>(DebugSetting.BypassFrontToBackPass) } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Show log overlay", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = "Performance logging", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging) }, new SettingsCheckbox { LabelText = "Bypass caching (slow)", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, }; } } }
mit
C#
dc701e88811e16e5567656e2dc86916fc515d494
Update OrmLiteTestBase.cs
NServiceKit/NServiceKit.OrmLite,NServiceKit/NServiceKit.OrmLite
tests/ServiceStack.OrmLite.FirebirdTests/OrmLiteTestBase.cs
tests/ServiceStack.OrmLite.FirebirdTests/OrmLiteTestBase.cs
using System; using System.IO; using System.Configuration; using NUnit.Framework; using ServiceStack.Common.Utils; using ServiceStack.Logging; using ServiceStack.Logging.Support.Logging; using ServiceStack.OrmLite.Firebird; namespace ServiceStack.OrmLite.FirebirdTests { public class OrmLiteTestBase { protected virtual string ConnectionString { get; set; } protected string GetFileConnectionString() { // add ormlite-tests.fdb = {PATH TO FDB FILE} D:\\ormlite-tests.fdb to your firebird alias.conf return "User=SYSDBA;Password=masterkey;Database=ormlite-tests.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;MinPoolSize=0;MaxPoolSize=100;"; } protected void CreateNewDatabase() { ConnectionString = GetFileConnectionString(); } [TestFixtureSetUp] public void TestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); OrmLiteConfig.DialectProvider = FirebirdOrmLiteDialectProvider.Instance; ConnectionString = GetFileConnectionString(); } public void Log(string text) { Console.WriteLine(text); } } }
using System; using System.IO; using System.Configuration; using NUnit.Framework; using ServiceStack.Common.Utils; using ServiceStack.Logging; using ServiceStack.Logging.Support.Logging; using ServiceStack.OrmLite.Firebird; namespace ServiceStack.OrmLite.FirebirdTests { public class OrmLiteTestBase { protected virtual string ConnectionString { get; set; } protected string GetFileConnectionString() { // add ormlite-tests.fdb = D:\\ormlite-tests.fdb to your firebird alias.conf return ConfigurationManager.ConnectionStrings["testDb"].ConnectionString; } protected void CreateNewDatabase() { ConnectionString = GetFileConnectionString(); } [TestFixtureSetUp] public void TestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); OrmLiteConfig.DialectProvider = FirebirdOrmLiteDialectProvider.Instance; ConnectionString = GetFileConnectionString(); } public void Log(string text) { Console.WriteLine(text); } } }
bsd-3-clause
C#
6559cb27bd18fd177ddf6def6629db3f87a04611
Fix test
rosolko/WebDriverManager.Net
IntegrationTests/VersionTests.cs
IntegrationTests/VersionTests.cs
using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace IntegrationTests { public class VersionData : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {new ChromeConfig(), @"^\d+\.\d+$"}, new object[] {new EdgeConfig(), @"^\d+\.\d+$"}, new object[] {new FirefoxConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new InternetExplorerConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new OperaConfig(), @"^\d+\.\d+\.\d+$"}, // new object[] {new PhantomConfig(), @"^\d+\.\d+\.\d+$"} }; public IEnumerator<object[]> GetEnumerator() { return _data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class VersionTests { [Theory, ClassData(typeof(VersionData)), Trait("Category", "Version")] protected void VersionTest(IDriverConfig driverConfig, string pattern) { var version = driverConfig.GetLatestVersion(); var regex = new Regex(pattern); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } } }
using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace IntegrationTests { public class VersionData : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {new ChromeConfig(), @"^\d+\.\d+$"}, new object[] {new EdgeConfig(), @"^\d+\.\d+$"}, new object[] {new FirefoxConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new InternetExplorerConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new OperaConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new PhantomConfig(), @"^\d+\.\d+\.\d+$"} }; public IEnumerator<object[]> GetEnumerator() { return _data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class VersionTests { [Theory, ClassData(typeof(VersionData)), Trait("Category", "Version")] protected void VersionTest(IDriverConfig driverConfig, string pattern) { var version = driverConfig.GetLatestVersion(); var regex = new Regex(pattern); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } } }
mit
C#
e67b56be72428cace9db4766e2b16ad828c9f8b2
Improve ShortVersionParser.TryParseMajorMinor() test coverage
pascalberger/GitVersion,JakeGinnivan/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,distantcam/GitVersion,GeertvanHorrik/GitVersion,GitTools/GitVersion,ermshiperete/GitVersion,alexhardwicke/GitVersion,GeertvanHorrik/GitVersion,asbjornu/GitVersion,gep13/GitVersion,ParticularLabs/GitVersion,Kantis/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,FireHost/GitVersion,anobleperson/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,Kantis/GitVersion,openkas/GitVersion,anobleperson/GitVersion,onovotny/GitVersion,onovotny/GitVersion,JakeGinnivan/GitVersion,TomGillen/GitVersion,FireHost/GitVersion,RaphHaddad/GitVersion,dpurge/GitVersion,ermshiperete/GitVersion,JakeGinnivan/GitVersion,asbjornu/GitVersion,MarkZuber/GitVersion,Philo/GitVersion,dazinator/GitVersion,Philo/GitVersion,openkas/GitVersion,alexhardwicke/GitVersion,orjan/GitVersion,dpurge/GitVersion,onovotny/GitVersion,Kantis/GitVersion,JakeGinnivan/GitVersion,ParticularLabs/GitVersion,dpurge/GitVersion,MarkZuber/GitVersion,TomGillen/GitVersion,distantcam/GitVersion,orjan/GitVersion,GitTools/GitVersion,RaphHaddad/GitVersion,anobleperson/GitVersion,dpurge/GitVersion
Tests/ShortVersionParserTests.cs
Tests/ShortVersionParserTests.cs
using GitFlowVersion; using NUnit.Framework; [TestFixture] public class ShortVersionParserTests { [Test] public void Major_minor_patch() { int minor; int major; int patch; ShortVersionParser.Parse("1.2.3", out major,out minor,out patch); Assert.AreEqual(1, major); Assert.AreEqual(2, minor); Assert.AreEqual(3, patch); } [Test] public void Major_minor_patchTry() { int minor; int major; int patch; var result = ShortVersionParser.TryParse("1.2.3", out major,out minor,out patch); Assert.IsTrue(result); Assert.AreEqual(1, major); Assert.AreEqual(2, minor); Assert.AreEqual(3, patch); } [Test] public void Major_minorTry() { int minor; int major; var result = ShortVersionParser.TryParseMajorMinor("1.2.3", out major, out minor); Assert.IsFalse(result); result = ShortVersionParser.TryParseMajorMinor("1.2", out major, out minor); Assert.IsFalse(result); result = ShortVersionParser.TryParseMajorMinor("1.2.0", out major, out minor); Assert.IsTrue(result); Assert.AreEqual(1, major); Assert.AreEqual(2, minor); } }
using GitFlowVersion; using NUnit.Framework; [TestFixture] public class ShortVersionParserTests { [Test] public void Major_minor_patch() { int minor; int major; int patch; ShortVersionParser.Parse("1.2.3", out major,out minor,out patch); Assert.AreEqual(1, major); Assert.AreEqual(2, minor); Assert.AreEqual(3, patch); } [Test] public void Major_minor_patchTry() { int minor; int major; int patch; var result = ShortVersionParser.TryParse("1.2.3", out major,out minor,out patch); Assert.IsTrue(result); Assert.AreEqual(1, major); Assert.AreEqual(2, minor); Assert.AreEqual(3, patch); } }
mit
C#
bdba7733ee62f7462c42967946836b4f1c288f37
Update GroupMember.cs
vknet/vk,vknet/vk
VkNet/Model/Group/GroupMember.cs
VkNet/Model/Group/GroupMember.cs
using System; using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация о сообществе (группе). /// См. описание http://vk.com/dev/fields_groups /// </summary> [Serializable] public class GroupMember { #region Методы /// <summary> /// Десериализовать из Json. /// </summary> /// <param name="response"> Jndtn. </param> /// <returns> </returns> public static GroupMember FromJson(VkResponse response) { var group = new GroupMember { UserId = response[key: "user_id"] , Member = response[key: "member"] , Request = response[key: "request"] , Invitation = response[key: "invitation"] }; return group; } #endregion #region Стандартные поля /// <summary> /// Идентификатор пользователя ВК. /// </summary> public ulong? UserId { get; set; } /// <summary> /// Является ли пользователь участником сообщества; /// </summary> public bool Member { get; set; } /// <summary> /// Есть ли непринятая заявка от пользователя на вступление в группу (такую заявку /// можно отозвать методом /// groups.leave). /// </summary> public bool? Request { get; set; } /// <summary> /// Приглашён ли пользователь в группу или встречу. /// </summary> public bool? Invitation { get; set; } #endregion } }
using System; using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация о сообществе (группе). /// См. описание http://vk.com/dev/fields_groups /// </summary> [Serializable] public class GroupMember { #region Методы /// <summary> /// Десериализовать из Json. /// </summary> /// <param name="response"> Jndtn. </param> /// <returns> </returns> public static GroupMember FromJson(VkResponse response) { var group = new GroupMember { UserId = response[key: "user_id"] , Member = response[key: "member"] , Request = response[key: "request"] , Invitation = response[key: "invitation"] }; return group; } #endregion #region Стандартные поля /// <summary> /// Идентификатор сообщества. /// </summary> public ulong? UserId { get; set; } /// <summary> /// Является ли пользователь участником сообщества; /// </summary> public bool Member { get; set; } /// <summary> /// Есть ли непринятая заявка от пользователя на вступление в группу (такую заявку /// можно отозвать методом /// groups.leave). /// </summary> public bool? Request { get; set; } /// <summary> /// Приглашён ли пользователь в группу или встречу. /// </summary> public bool? Invitation { get; set; } #endregion } }
mit
C#
89f6486a1cfa8689c88119ae94fa439c17d777ef
Update cookie name.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex/Config/Authentication/AuthenticationServices.cs
backend/src/Squidex/Config/Authentication/AuthenticationServices.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Microsoft.AspNetCore.Authentication; using Squidex.Hosting.Web; namespace Squidex.Config.Authentication { public static class AuthenticationServices { public static void AddSquidexAuthentication(this IServiceCollection services, IConfiguration config) { var identityOptions = config.GetSection("identity").Get<MyIdentityOptions>() ?? new (); services.AddAuthentication() .AddSquidexCookies(config) .AddSquidexExternalGithubAuthentication(identityOptions) .AddSquidexExternalGoogleAuthentication(identityOptions) .AddSquidexExternalMicrosoftAuthentication(identityOptions) .AddSquidexExternalOdic(identityOptions) .AddSquidexIdentityServerAuthentication(identityOptions, config); } public static AuthenticationBuilder AddSquidexCookies(this AuthenticationBuilder builder, IConfiguration config) { var urlsOptions = config.GetSection("urls").Get<UrlOptions>() ?? new (); builder.Services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/identity-server/account/access-denied"; options.LoginPath = "/identity-server/account/login"; options.LogoutPath = "/identity-server/account/login"; options.Cookie.Name = ".sq.auth2"; if (urlsOptions.BaseUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) == true) { options.Cookie.SameSite = SameSiteMode.None; } }); return builder.AddCookie(); } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Microsoft.AspNetCore.Authentication; using Squidex.Hosting.Web; namespace Squidex.Config.Authentication { public static class AuthenticationServices { public static void AddSquidexAuthentication(this IServiceCollection services, IConfiguration config) { var identityOptions = config.GetSection("identity").Get<MyIdentityOptions>() ?? new (); services.AddAuthentication() .AddSquidexCookies(config) .AddSquidexExternalGithubAuthentication(identityOptions) .AddSquidexExternalGoogleAuthentication(identityOptions) .AddSquidexExternalMicrosoftAuthentication(identityOptions) .AddSquidexExternalOdic(identityOptions) .AddSquidexIdentityServerAuthentication(identityOptions, config); } public static AuthenticationBuilder AddSquidexCookies(this AuthenticationBuilder builder, IConfiguration config) { var urlsOptions = config.GetSection("urls").Get<UrlOptions>() ?? new (); builder.Services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/identity-server/account/access-denied"; options.LoginPath = "/identity-server/account/login"; options.LogoutPath = "/identity-server/account/login"; options.Cookie.Name = ".sq.auth"; if (urlsOptions.BaseUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) == true) { options.Cookie.SameSite = SameSiteMode.None; } }); return builder.AddCookie(); } } }
mit
C#
1418297958047ecd6b5a821dfecab8f22a2767ca
Update QuoteRepository.cs
shikhir-arora/NadekoBot,powered-by-moe/MikuBot,PravEF/EFNadekoBot,Midnight-Myth/Mitternacht-NEW,ShadowNoire/NadekoBot,Youngsie1997/NadekoBot,Midnight-Myth/Mitternacht-NEW,miraai/NadekoBot,Nielk1/NadekoBot,gfrewqpoiu/NadekoBot,WoodenGlaze/NadekoBot,Midnight-Myth/Mitternacht-NEW,halitalf/NadekoMods,ScarletKuro/NadekoBot,Taknok/NadekoBot,Blacnova/NadekoBot,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); string lowertext = text.ToLowerInvariant(); string uppertext = text.ToUpperInvariant(); return _set.Where(q => (q.Text.Contains(text) | q.Text.Contains(lowertext) | q.Text.Contains(uppertext)) & (q.GuildId == guildId && q.Keyword == keyword)).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); string lowertext = text.ToLowerInvariant(); string uppertext = text.ToUpperInvariant(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword && (q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext))).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
mit
C#
97efcd3c05dc77b3a8817f397059752356a1ef5b
set tile to empty by default
UpBeet/dungeon-generator
Assets/Scripts/TileController.cs
Assets/Scripts/TileController.cs
using UnityEngine; /// <summary> /// Tile definition, logic passed between client and server. /// </summary> public class Tile { /// <summary> /// The X coordinate. /// </summary> public int X { get; private set; } /// <summary> /// The Y coordinate. /// </summary> public int Y { get; private set; } /// <summary> /// If set to true, this tile does not have an established definition. /// </summary> public bool Empty { get; private set; } /// <summary> /// Instantiates a new Tile object. /// </summary> /// <param name="x">The X coordinate of the tile.</param> /// <param name="y">The Y coordinate of the tile.</param> public Tile (int x, int y) { this.X = x; this.Y = y; this.Empty = true; } } /// <summary> /// Tile component. Exists only on the client, to interface between /// the Unity scene and the server's logical definition. /// </summary> public class TileController : MonoBehaviour { /// <summary> /// The X coordinate. /// </summary> public int X { get; private set; } /// <summary> /// The Y coordinate. /// </summary> /// <value>The y.</value> public int Y { get; private set; } /// <summary> /// If set to true, this tile is an empty part of the board. /// </summary> public bool Empty { get; private set; } /// <summary> /// Reference to the definition for this tile. /// </summary> private Tile tile; }
using UnityEngine; /// <summary> /// Tile definition, logic passed between client and server. /// </summary> public class Tile { /// <summary> /// The X coordinate. /// </summary> public int X { get; private set; } /// <summary> /// The Y coordinate. /// </summary> public int Y { get; private set; } /// <summary> /// If set to true, this tile does not have an established definition. /// </summary> public bool Empty { get; private set; } /// <summary> /// Instantiates a new Tile object. /// </summary> /// <param name="x">The X coordinate of the tile.</param> /// <param name="y">The Y coordinate of the tile.</param> public Tile (int x, int y, bool empty) { this.X = x; this.Y = y; this.Empty = empty; } } /// <summary> /// Tile component. Exists only on the client, to interface between /// the Unity scene and the server's logical definition. /// </summary> public class TileController : MonoBehaviour { /// <summary> /// The X coordinate. /// </summary> public int X { get; private set; } /// <summary> /// The Y coordinate. /// </summary> /// <value>The y.</value> public int Y { get; private set; } /// <summary> /// If set to true, this tile is an empty part of the board. /// </summary> public bool Empty { get; private set; } /// <summary> /// Reference to the definition for this tile. /// </summary> private Tile tile; }
mit
C#
7835e95eb0316ea1bbc34d9f4f9ba5defaec4cb2
Update 1.19
maikonfarias/runshadow,maikonfarias/runshadow
client/Assets/Scripts/Config.cs
client/Assets/Scripts/Config.cs
using UnityEngine; using System.Collections; public static class Config { public static string Version { get { return "1.19"; } } public static float ScoreMultiplier { get { return 2.7f; } } public static string ServerSecrectKey { get { return "YOUR-SECRET-KEY"; } } }
using UnityEngine; using System.Collections; public static class Config { public static string Version { get { return "1.18"; } } public static float ScoreMultiplier { get { return 2.5f; } } public static string ServerSecrectKey { get { return "YOUR-SECRET-KEY"; } } }
bsd-3-clause
C#
a86194963d939b8a3db20e828a6c89cc4841390b
Update summary to clarify when Initialize runs
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Core/Interfaces/Services/IMixedRealityService.cs
Assets/MRTK/Core/Interfaces/Services/IMixedRealityService.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit { /// <summary> /// Generic interface for all Mixed Reality Services /// </summary> public interface IMixedRealityService : IDisposable { /// <summary> /// Optional Priority attribute if multiple services of the same type are required, enables targeting a service for action. /// </summary> string Name { get; } /// <summary> /// Optional Priority to reorder registered managers based on their respective priority, reduces the risk of race conditions by prioritizing the order in which managers are evaluated. /// </summary> uint Priority { get; } /// <summary> /// The configuration profile for the service. /// </summary> /// <remarks> /// Many services may wish to provide a typed version (ex: MixedRealityInputSystemProfile) that casts this value for ease of use in calling code. /// </remarks> BaseMixedRealityProfile ConfigurationProfile { get; } /// <summary> /// The initialize function is used to setup the service once created. /// This method is called once all services have been registered in the Mixed Reality Toolkit. /// </summary> /// <remarks>This will run both in edit mode and in play mode. Gate code behind `Application.isPlaying` if it should only run in one or the other.</remarks> void Initialize(); /// <summary> /// Optional Reset function to perform that will Reset the service, for example, whenever there is a profile change. /// </summary> void Reset(); /// <summary> /// Optional Enable function to enable / re-enable the service. /// </summary> void Enable(); /// <summary> /// Optional Update function to perform per-frame updates of the service. /// </summary> void Update(); /// <summary> /// Optional LateUpdate function to that is called after Update has been called on all services. /// </summary> void LateUpdate(); /// <summary> /// Optional Disable function to pause the service. /// </summary> void Disable(); /// <summary> /// Optional Destroy function to perform cleanup of the service before the Mixed Reality Toolkit is destroyed. /// </summary> void Destroy(); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit { /// <summary> /// Generic interface for all Mixed Reality Services /// </summary> public interface IMixedRealityService : IDisposable { /// <summary> /// Optional Priority attribute if multiple services of the same type are required, enables targeting a service for action. /// </summary> string Name { get; } /// <summary> /// Optional Priority to reorder registered managers based on their respective priority, reduces the risk of race conditions by prioritizing the order in which managers are evaluated. /// </summary> uint Priority { get; } /// <summary> /// The configuration profile for the service. /// </summary> /// <remarks> /// Many services may wish to provide a typed version (ex: MixedRealityInputSystemProfile) that casts this value for ease of use in calling code. /// </remarks> BaseMixedRealityProfile ConfigurationProfile { get; } /// <summary> /// The initialize function is used to setup the service once created. /// This method is called once all services have been registered in the Mixed Reality Toolkit. /// </summary> void Initialize(); /// <summary> /// Optional Reset function to perform that will Reset the service, for example, whenever there is a profile change. /// </summary> void Reset(); /// <summary> /// Optional Enable function to enable / re-enable the service. /// </summary> void Enable(); /// <summary> /// Optional Update function to perform per-frame updates of the service. /// </summary> void Update(); /// <summary> /// Optional LateUpdate function to that is called after Update has been called on all services. /// </summary> void LateUpdate(); /// <summary> /// Optional Disable function to pause the service. /// </summary> void Disable(); /// <summary> /// Optional Destroy function to perform cleanup of the service before the Mixed Reality Toolkit is destroyed. /// </summary> void Destroy(); } }
mit
C#
e988c15b19471a11ef941589e9a0243ec8737349
Update SettingHeightOfRow.cs
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
Examples/CSharp/RowsColumns/HeightAndWidth/SettingHeightOfRow.cs
Examples/CSharp/RowsColumns/HeightAndWidth/SettingHeightOfRow.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth { public class SettingHeightOfRow { 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 the second row to 13 worksheet.Cells.SetRowHeight(1, 13); //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 SettingHeightOfRow { 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 the second row to 13 worksheet.Cells.SetRowHeight(1, 13); //Saving the modified Excel file workbook.Save(dataDir + "output.out.xls"); //Closing the file stream to free all resources fstream.Close(); } } }
mit
C#
5dc0dfb5addafcd51f9438f8512b54f92457993e
Update src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS
src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
using System; using Umbraco.Core; using Microsoft.AspNetCore.Routing; using System.Reflection; using Umbraco.Web.Common.Install; namespace Umbraco.Extensions { public static class LinkGeneratorExtensions { /// <summary> /// Return the back office url if the back office is installed /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetBackOfficeUrl(this LinkGenerator linkGenerator) { Type backOfficeControllerType; try { backOfficeControllerType = Assembly.Load("Umbraco.Web.BackOffice")?.GetType("Umbraco.Web.BackOffice.Controllers.BackOfficeController"); if (backOfficeControllerType == null) return "/"; // this would indicate that the installer is installed without the back office } catch (Exception) { return "/"; // this would indicate that the installer is installed without the back office } return linkGenerator.GetPathByAction("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea }); } /// <summary> /// Returns the URL for the installer /// </summary> /// <param name="linkGenerator"></param> /// <returns></returns> public static string GetInstallerUrl(this LinkGenerator linkGenerator) { return linkGenerator.GetPathByAction(nameof(InstallController.Index), ControllerExtensions.GetControllerName<InstallController>(), new { area = Constants.Web.Mvc.InstallArea }); } } }
using System; using Umbraco.Core; using Microsoft.AspNetCore.Routing; using System.Reflection; using Umbraco.Web.Common.Install; namespace Umbraco.Extensions { public static class LinkGeneratorExtensions { /// <summary> /// Return the back office url if the back office is installed /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetBackOfficeUrl(this LinkGenerator linkGenerator) { Type backOfficeControllerType; try { backOfficeControllerType = Assembly.Load("Umbraco.Web.BackOffice")?.GetType("Umbraco.Web.BackOffice.Controllers.BackOfficeController"); if (backOfficeControllerType == null) return "/"; // this would indicate that the installer is installed without the back office } catch (Exception) { return "/"; // this would indicate that the installer is installed without the back office } return linkGenerator.GetPathByAction("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea }); } /// <summary> /// Returns the URL for the installer /// </summary> /// <param name="linkGenerator"></param> /// <returns></returns> public static string GetInstallerUrl(this LinkGenerator linkGenerator) { return linkGenerator.GetPathByAction("Index", ControllerExtensions.GetControllerName<InstallController>(), new { area = Constants.Web.Mvc.InstallArea }); } } }
mit
C#
56e0ae18b8bf394d9f223ddb69f01bb70e6f03fa
Include aggregate name in routing key
AntoineGa/EventFlow,liemqv/EventFlow,rasmus/EventFlow
Source/EventFlow.RabbitMQ/Integrations/RabbitMqMessageFactory.cs
Source/EventFlow.RabbitMQ/Integrations/RabbitMqMessageFactory.cs
// The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // 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.Text; using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlow.RabbitMQ.Integrations { public class RabbitMqMessageFactory : IRabbitMqMessageFactory { private readonly IEventJsonSerializer _eventJsonSerializer; public RabbitMqMessageFactory( IEventJsonSerializer eventJsonSerializer) { _eventJsonSerializer = eventJsonSerializer; } public RabbitMqMessage CreateMessage(IDomainEvent domainEvent) { var serializedEvent = _eventJsonSerializer.Serialize( domainEvent.GetAggregateEvent(), domainEvent.Metadata); var message = Encoding.UTF8.GetBytes(serializedEvent.SerializedData); // TODO: Add aggregate name to routing key var routingKey = string.Format( "eventflow.domainevent.{0}.{1}.{2}", domainEvent.Metadata[MetadataKeys.AggregateName].ToLowerInvariant(), // TODO: Transform from "MyAgg" to "my-agg" domainEvent.Metadata.EventName.ToLowerInvariant(), // TODO: Transform from "MyEvnt" to "my-evnt" domainEvent.Metadata.EventVersion); return new RabbitMqMessage(message, domainEvent.Metadata, routingKey); } } }
// The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // 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.Text; using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlow.RabbitMQ.Integrations { public class RabbitMqMessageFactory : IRabbitMqMessageFactory { private readonly IEventJsonSerializer _eventJsonSerializer; public RabbitMqMessageFactory( IEventJsonSerializer eventJsonSerializer) { _eventJsonSerializer = eventJsonSerializer; } public RabbitMqMessage CreateMessage(IDomainEvent domainEvent) { var serializedEvent = _eventJsonSerializer.Serialize( domainEvent.GetAggregateEvent(), domainEvent.Metadata); var message = Encoding.UTF8.GetBytes(serializedEvent.SerializedData); // TODO: Add aggregate name to routing key var routingKey = string.Format( "eventflow.domainevent.{0}.{1}", domainEvent.Metadata.EventName, domainEvent.Metadata.EventVersion); return new RabbitMqMessage(message, domainEvent.Metadata, routingKey); } } }
mit
C#
c9f2fd67f748b405cb13aae7746261e5ad34ab63
comment out debug for moment
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Spa2/NakedObjects.Spa.Selenium.Test/helpers/SafeWebDriverWait.cs
Spa2/NakedObjects.Spa.Selenium.Test/helpers/SafeWebDriverWait.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Diagnostics; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace NakedObjects.Selenium { public class SafeWebDriverWait : IWait<IWebDriver> { private readonly WebDriverWait wait; public SafeWebDriverWait(IWebDriver driver, TimeSpan timeout) { wait = new WebDriverWait(driver, timeout); Driver = driver; } public IWebDriver Driver { get; private set; } #region IWait<IWebDriver> Members public void IgnoreExceptionTypes(params Type[] exceptionTypes) { wait.IgnoreExceptionTypes(exceptionTypes); } private void DebugDumpPage() { var page = Driver.PageSource; Debug.WriteLine(page); } public TResult Until<TResult>(Func<IWebDriver, TResult> condition) { try { return wait.Until(d => { try { return condition(d); } catch { } return default(TResult); }); } catch { //DebugDumpPage(); throw; } } public TimeSpan Timeout { get { return wait.Timeout; } set { wait.Timeout = value; } } public TimeSpan PollingInterval { get { return wait.PollingInterval; } set { wait.PollingInterval = value; } } public string Message { get { return wait.Message; } set { wait.Message = value; } } #endregion } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Diagnostics; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace NakedObjects.Selenium { public class SafeWebDriverWait : IWait<IWebDriver> { private readonly WebDriverWait wait; public SafeWebDriverWait(IWebDriver driver, TimeSpan timeout) { wait = new WebDriverWait(driver, timeout); Driver = driver; } public IWebDriver Driver { get; private set; } #region IWait<IWebDriver> Members public void IgnoreExceptionTypes(params Type[] exceptionTypes) { wait.IgnoreExceptionTypes(exceptionTypes); } private void DebugDumpPage() { var page = Driver.PageSource; Debug.WriteLine(page); } public TResult Until<TResult>(Func<IWebDriver, TResult> condition) { try { return wait.Until(d => { try { return condition(d); } catch { } return default(TResult); }); } catch { DebugDumpPage(); throw; } } public TimeSpan Timeout { get { return wait.Timeout; } set { wait.Timeout = value; } } public TimeSpan PollingInterval { get { return wait.PollingInterval; } set { wait.PollingInterval = value; } } public string Message { get { return wait.Message; } set { wait.Message = value; } } #endregion } }
apache-2.0
C#
8788b17825959def4353ff37fa47576dea59c769
change color order for Win32
LayoutFarm/PixelFarm
src/PixelFarm/PixelFarm.CpuBlit/05_PixelProcessing/CO.cs
src/PixelFarm/PixelFarm.CpuBlit/05_PixelProcessing/CO.cs
//BSD, 2014-present, WinterDev //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- //#define ABGR #define ARGB namespace PixelFarm.CpuBlit.PixelProcessing { /// <summary> /// color order /// </summary> public static class CO { #if ARGB // eg. Win32 //eg. windows /// <summary> /// order b /// </summary> public const int B = 0; /// <summary> /// order g /// </summary> public const int G = 1; /// <summary> /// order r /// </summary> public const int R = 2; /// <summary> /// order a /// </summary> public const int A = 3; #endif #if ABGR // eg. Skia on iOS /// <summary> /// order b /// </summary> public const int B = 2; /// <summary> /// order g /// </summary> public const int G = 1; /// <summary> /// order r /// </summary> public const int R = 0; /// <summary> /// order a /// </summary> public const int A = 3; #endif public const int B_SHIFT = B * 8; /// <summary> /// order g /// </summary> public const int G_SHIFT = G * 8; /// <summary> /// order r /// </summary> public const int R_SHIFT = R * 8; /// <summary> /// order a /// </summary> public const int A_SHIFT = A * 8; } }
//BSD, 2014-present, WinterDev //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- #define ABGR namespace PixelFarm.CpuBlit.PixelProcessing { /// <summary> /// color order /// </summary> public static class CO { #if ARGB // eg. Win32 //eg. windows /// <summary> /// order b /// </summary> public const int B = 0; /// <summary> /// order g /// </summary> public const int G = 1; /// <summary> /// order r /// </summary> public const int R = 2; /// <summary> /// order a /// </summary> public const int A = 3; #endif #if ABGR // eg. Skia on iOS /// <summary> /// order b /// </summary> public const int B = 2; /// <summary> /// order g /// </summary> public const int G = 1; /// <summary> /// order r /// </summary> public const int R = 0; /// <summary> /// order a /// </summary> public const int A = 3; #endif public const int B_SHIFT = B * 8; /// <summary> /// order g /// </summary> public const int G_SHIFT = G * 8; /// <summary> /// order r /// </summary> public const int R_SHIFT = R * 8; /// <summary> /// order a /// </summary> public const int A_SHIFT = A * 8; } }
bsd-2-clause
C#
064c93509961ea4735eeeaec54fa5ddd479b086b
Fix broken build.
Bartmax/Foundatio,vebin/Foundatio,exceptionless/Foundatio,FoundatioFx/Foundatio,wgraham17/Foundatio
src/Core/Messaging/IMessageSubscriber.cs
src/Core/Messaging/IMessageSubscriber.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Foundatio.Messaging { public interface IMessageSubscriber { void Subscribe<T>(Action<T> handler) where T : class; } public interface IMessageSubscriber2 { void Subscribe<T>(Func<T, CancellationToken, Task> handler, CancellationToken cancellationToken = default(CancellationToken)) where T : class; } public static class MessageBusExtensions { public static void Subscribe<T>(this IMessageSubscriber2 subscriber, Func<T, Task> handler, CancellationToken cancellationToken = default (CancellationToken)) where T : class { subscriber.Subscribe<T>((msg, token) => handler(msg), cancellationToken); } public static void Subscribe<T>(this IMessageSubscriber2 subscriber, Action<T> handler, CancellationToken cancellationToken = default (CancellationToken)) where T : class { subscriber.Subscribe<T>((msg, token) => { handler(msg); return Task.FromResult(0); }, cancellationToken); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Foundatio.Messaging { public interface IMessageSubscriber { void Subscribe<T>(Action<T> handler) where T : class; } public interface IMessageSubscriber2 { void Subscribe<T>(Func<T, CancellationToken, Task> handler, CancellationToken cancellationToken = default(CancellationToken)) where T : class; } public static class MessageBusExtensions { public static void Subscribe<T>(this IMessageSubscriber2 subscriber, Func<T, Task> handler, CancellationToken cancellationToken = default (CancellationToken)) where T : class { subscriber.Subscribe<T>((msg, token) => handler(msg), cancellationToken); } public static void Subscribe<T>(this IMessageSubscriber2 subscriber, Action<T> handler, CancellationToken cancellationToken = default (CancellationToken)) where T : class { subscriber.Subscribe<T>((msg, token) => handler(msg), cancellationToken); } } }
apache-2.0
C#
c2a2ce4a3b77ca8c02c00ef7a3d3a5f5310e035a
Update my feed URL: I've moved to GitHub pages (#675)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/DamianMehers.cs
src/Firehose.Web/Authors/DamianMehers.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DamianMehers : IAmACommunityMember { public string FirstName => "Damian"; public string LastName => "Mehers"; public string ShortBioOrTagLine => "Independent Xamarin Developer"; public string StateOrRegion => "Geneva, Switzerland"; public string EmailAddress => "damian@mehers.com"; public string TwitterHandle => "DamianMehers"; public string GravatarHash => "d77613f4e20bfcae401a6bf0018a83d1"; public string GitHubHandle => "DamianMehers"; public GeoPosition Position => new GeoPosition(46.3635288, 6.1860801); public Uri WebSite => new Uri("https://damian.fyi/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://damian.fyi/feed/Xamarin.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DamianMehers : IAmACommunityMember { public string FirstName => "Damian"; public string LastName => "Mehers"; public string ShortBioOrTagLine => "Independent Xamarin Developer"; public string StateOrRegion => "Geneva, Switzerland"; public string EmailAddress => "damian@mehers.com"; public string TwitterHandle => "DamianMehers"; public string GravatarHash => "d77613f4e20bfcae401a6bf0018a83d1"; public string GitHubHandle => "DamianMehers"; public GeoPosition Position => new GeoPosition(46.3635288, 6.1860801); public Uri WebSite => new Uri("https://damian.fyi/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://damian.fyi/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
3c46a8f3078dc9021da3ef012a655a2888b662f8
repair searching encounters by a serviceProvider chain criteria
furore-fhir/spark,furore-fhir/spark,furore-fhir/spark
src/Spark.Engine/Model/SparkModelInfo.cs
src/Spark.Engine/Model/SparkModelInfo.cs
using System; using Hl7.Fhir.Model; using System.Collections.Generic; using System.Linq; using static Hl7.Fhir.Model.ModelInfo; namespace Spark.Engine.Model { public static class SparkModelInfo { public static List<SearchParamDefinition> SparkSearchParameters = ModelInfo.SearchParameters.Union( new List<SearchParamDefinition>() { new SearchParamDefinition() {Resource = "Composition", Name = "custodian", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.custodian" }, XPath = "f:Composition/f:custodian", Expression = "Composition.custodian", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Composition", Name = "eventdetail", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.event.detail" }, XPath = "f:Composition/f:event/f:detail", Expression = "Composition.event.detail", Target = Enum.GetValues(typeof(ResourceType)).Cast<ResourceType>().ToArray() } , new SearchParamDefinition() {Resource = "Encounter", Name = "serviceprovider", Description = @"Organization that provides the Encounter services.", Type = SearchParamType.Reference, Path = new[] {"Encounter.serviceProvider"}, XPath = "f:Encounter/f:serviceProvider",Expression = "Encounter.serviceProvider", Target = new ResourceType[] { ResourceType.Organization} } , new SearchParamDefinition() {Resource = "Slot", Name = "provider", Description = @"Search Slot by provider extension", Type = SearchParamType.Reference, Path = new string[] { @"Slot.extension(url=http://fhir.blackpear.com/era/Slot/provider).valueReference" } } }).ToList(); } }
using Hl7.Fhir.Model; using System.Collections.Generic; using System.Linq; using static Hl7.Fhir.Model.ModelInfo; namespace Spark.Engine.Model { public static class SparkModelInfo { public static List<SearchParamDefinition> SparkSearchParameters = ModelInfo.SearchParameters.Union( new List<SearchParamDefinition>() { new SearchParamDefinition() {Resource = "Composition", Name = "custodian", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.custodian" }, XPath = "f:Composition/f:custodian", Expression = "Composition.custodian" } , new SearchParamDefinition() {Resource = "Composition", Name = "eventdetail", Description = @"custom search parameter on Composition for generating $document", Type = SearchParamType.Reference, Path = new string[] {"Composition.event.detail" }, XPath = "f:Composition/f:event/f:detail", Expression = "Composition.event.detail" } , new SearchParamDefinition() {Resource = "Encounter", Name = "serviceprovider", Description = @"Organization that provides the Encounter services.", Type = SearchParamType.Reference, Path = new[] {"Encounter.serviceProvider"}, XPath = "f:Encounter/f:serviceProvider",Expression = "Encounter.serviceProvider" } , new SearchParamDefinition() {Resource = "Slot", Name = "provider", Description = @"Search Slot by provider extension", Type = SearchParamType.Reference, Path = new string[] { @"Slot.extension(url=http://fhir.blackpear.com/era/Slot/provider).valueReference" } } }).ToList(); } }
bsd-3-clause
C#
e438bdb733049e40f2ef690610c20a884a845b40
Test to be proper async. Dave to make the test pass
texred/WhatsMyRun
Testing/WhatsMyRun.Services.Tests/WorkoutDataProviderTest.cs
Testing/WhatsMyRun.Services.Tests/WorkoutDataProviderTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WhatsMyRun.Services.DataRequestor; using Moq; using WhatsMyRun.Services.DataProviders.Workouts; using System.Threading.Tasks; using System.IO; using System.Reflection; namespace WhatsMyRun.Tests { [TestClass] public class WorkoutDataProviderTest { private string dataLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SampleWorkoutsData.json"; [TestMethod] public async Task WorkoutDataProvider_Default_CallsRequestor() { //ARRANGE var mockRequestor = new Moq.Mock<IDataRequestor>(); var mockedData = File.ReadAllText(dataLocation); var provider = new WorkoutDataProvider(mockRequestor.Object); mockRequestor.Setup(r => r.GetDataAsync(It.IsAny<Uri>())) .Returns(Task.FromResult(mockedData)); //To see the test fail, bring back this line: mockRequestor.Setup(r => r.GetDataAsync(new Uri("http://test.com"))) .Returns(Task.FromResult(mockedData)); //ACT await provider.GetWorkoutsForUserAsync(1); mockRequestor.VerifyAll(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WhatsMyRun.Services.DataRequestor; using Moq; using WhatsMyRun.Services.DataProviders.Workouts; using System.Threading.Tasks; using System.IO; using System.Reflection; namespace WhatsMyRun.Tests { [TestClass] public class WorkoutDataProviderTest { private string dataLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SampleWorkoutsData.json"; [TestMethod] public void WorkoutDataProvider_Default_CallsRequestor() { //ARRANGE var mockRequestor = new Moq.Mock<IDataRequestor>(); var mockedData = File.ReadAllText(dataLocation); var provider = new WorkoutDataProvider(mockRequestor.Object); mockRequestor.Setup(r => r.GetDataAsync<string>(It.IsAny<Uri>())) .Returns(Task.FromResult(mockedData)); //To see the test fail, bring back this line: //mockRequestor.Setup(r => r.GetDataAsync<int>(It.IsAny<Uri>())) // .Returns(Task.FromResult(1)); //ACT provider.GetWorkoutsForUserAsync(1) .Wait(); mockRequestor.VerifyAll(); } } }
mit
C#
b4daaac67802724b8bdebaee3f9fa2d5ec1dde7d
Return Journal entries latest first
charlesj/Apollo,charlesj/Apollo,charlesj/Apollo,charlesj/Apollo,charlesj/Apollo
server/Apollo/Data/IJournalDataService.cs
server/Apollo/Data/IJournalDataService.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Apollo.Data.ResultModels; using Dapper; namespace Apollo.Data { public interface IJournalDataService { Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries(); Task CreateJournalEntry(JournalEntry entry); } public class JournalDataService : IJournalDataService { private readonly IDbConnectionFactory connectionFactory; public JournalDataService(IDbConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public async Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries() { using (var connection = await connectionFactory.GetConnection()) { var query = "select * from journal order by id desc"; var results = await connection .QueryAsync<JournalEntry>(query); return results.ToList(); } } public async Task CreateJournalEntry(JournalEntry entry) { using (var connection = await connectionFactory.GetConnection()) { connection.Execute(@" insert into journal(note, created_at) values (@note, current_timestamp)", new {note = entry.note}); } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Apollo.Data.ResultModels; using Dapper; namespace Apollo.Data { public interface IJournalDataService { Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries(); Task CreateJournalEntry(JournalEntry entry); } public class JournalDataService : IJournalDataService { private readonly IDbConnectionFactory connectionFactory; public JournalDataService(IDbConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public async Task<IReadOnlyList<JournalEntry>> GetAllJournalEntries() { using (var connection = await connectionFactory.GetConnection()) { var results = await connection.QueryAsync<JournalEntry>("select * from journal"); return results.ToList(); } } public async Task CreateJournalEntry(JournalEntry entry) { using (var connection = await connectionFactory.GetConnection()) { connection.Execute(@" insert into journal(note, created_at) values (@note, current_timestamp)", new {note = entry.note}); } } } }
mit
C#
cb239a36e04ff788a49b1df8644b32ac3a3e6644
Improve GetDefault method
evicertia/HermaFx,evicertia/HermaFx,evicertia/HermaFx
HermaFx.Foundation/RuntimeExtensions/TypeExtensions.cs
HermaFx.Foundation/RuntimeExtensions/TypeExtensions.cs
using System; using System.Reflection; using System.Collections.Concurrent; namespace HermaFx { public static class TypeExtension { //A thread-safe way to hold default instances created at run-time private static ConcurrentDictionary<Type, object> typeDefaults = new ConcurrentDictionary<Type, object>(); // Copied from : http://stackoverflow.com/a/7881481 public static object GetDefault(this Type type) { Guard.IsNotNull(type, nameof(type)); // If the Type was a reference type, or if the Type was a System.Void, return null if (!type.IsValueType || type == typeof(void)) return null; // If the supplied Type has generic parameters, its default value cannot be determined if (type.ContainsGenericParameters) { throw new ArgumentException($"The supplied value type <{type}> contains generic parameters, so the default value cannot be retrieved"); } // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct), return a // default instance of the value type if (type.IsPrimitive || !type.IsNotPublic) { try { return typeDefaults.GetOrAdd(type, t => Activator.CreateInstance(t)); } catch (Exception e) { throw new ArgumentException( $"The Activator.CreateInstance method could not create a default instance of the supplied value type <{type}>", e); } } // Fail with exception throw new ArgumentException($"The supplied value type <{type}> is not a publicly-visible type, so the default value cannot be retrieved"); } } }
using System; using System.Reflection; using System.Collections.Concurrent; namespace HermaFx { public static class TypeExtension { //a thread-safe way to hold default instances created at run-time private static ConcurrentDictionary<Type, object> typeDefaults = new ConcurrentDictionary<Type, object>(); // Extracted from : http://stackoverflow.com/a/7881481 public static object GetDefault(this Type type) { Guard.IsNotNull(type, nameof(type)); // If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null if (type == null || !type.IsValueType || type == typeof(void)) return null; // If the supplied Type has generic parameters, its default value cannot be determined if (type.ContainsGenericParameters) { throw new ArgumentException($"The supplied value type <{type}> contains generic parameters, so the default value cannot be retrieved"); } // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct), return a // default instance of the value type if (type.IsPrimitive || !type.IsNotPublic) { try { return typeDefaults.GetOrAdd(type, t => Activator.CreateInstance(t)); } catch (Exception e) { throw new ArgumentException( $"The Activator.CreateInstance method could not create a default instance of the supplied value type <{type}>\n\n"+ $"Exception message:{e.Message}", e); } } // Fail with exception throw new ArgumentException($"The supplied value type <{type}> is not a publicly-visible type, so the default value cannot be retrieved"); } } }
mit
C#
ba5b717fc0f70f426b7146d0d164673e715f7f2c
Add xmldoc warning against use of FramesPerSecond
ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework
osu.Framework/Timing/IFrameBasedClock.cs
osu.Framework/Timing/IFrameBasedClock.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Timing { /// <summary> /// A clock which will only update its current time when a frame proces is triggered. /// Useful for keeping a consistent time state across an individual update. /// </summary> public interface IFrameBasedClock : IClock { /// <summary> /// Elapsed time since last frame in milliseconds. /// </summary> double ElapsedFrameTime { get; } /// <summary> /// A moving average representation of the frames per second of this clock. /// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead). /// </summary> double FramesPerSecond { get; } FrameTimeInfo TimeInfo { get; } /// <summary> /// Processes one frame. Generally should be run once per update loop. /// </summary> void ProcessFrame(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Timing { /// <summary> /// A clock which will only update its current time when a frame proces is triggered. /// Useful for keeping a consistent time state across an individual update. /// </summary> public interface IFrameBasedClock : IClock { /// <summary> /// Elapsed time since last frame in milliseconds. /// </summary> double ElapsedFrameTime { get; } double FramesPerSecond { get; } FrameTimeInfo TimeInfo { get; } /// <summary> /// Processes one frame. Generally should be run once per update loop. /// </summary> void ProcessFrame(); } }
mit
C#
2babb7ecb0b122555a339809ce158b748f0e3295
Fix CI
ppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu
osu.Game/Rulesets/Mods/ModSuddenDeath.cs
osu.Game/Rulesets/Mods/ModSuddenDeath.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToHealthProcessor, IApplicableFailOverride { public override string Name => "Sudden Death"; public override string Acronym => "SD"; public override IconUsage? Icon => OsuIcon.ModSuddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; [SettingSource("Restart on fail", "Automatically restarts when failed.")] public BindableBool Restart { get; } = new BindableBool(); public bool PerformFail() => true; public bool RestartOnFail => Restart.Value; public void ApplyToHealthProcessor(HealthProcessor healthProcessor) { healthProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(HealthProcessor healthProcessor, JudgementResult result) => result.Type.AffectsCombo() && !result.IsHit; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToHealthProcessor, IApplicableFailOverride { public override string Name => "Sudden Death"; public override string Acronym => "SD"; public override IconUsage? Icon => OsuIcon.ModSuddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; [SettingSource("Restart on fail", "Automatically restarts when failed.")] public BindableBool Restart { get; } = new BindableBool(); public bool PerformFail() => true; public bool RestartOnFail => Restart.Value; public void ApplyToHealthProcessor(HealthProcessor healthProcessor) { healthProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(HealthProcessor healthProcessor, JudgementResult result) => result.Type.AffectsCombo() && !result.IsHit; } }
mit
C#
e0361ffe91b546716cdf7dce0e783eeee7b2b619
Add organization to XML Docs (#488)
auth0/auth0.net,auth0/auth0.net
src/Auth0.AuthenticationApi/Tokens/IdTokenRequirements.cs
src/Auth0.AuthenticationApi/Tokens/IdTokenRequirements.cs
using System; namespace Auth0.AuthenticationApi.Tokens { /// <summary> /// Identity token validation requirements for use with <see cref="IdTokenClaimValidator"/>. /// </summary> internal class IdTokenRequirements { /// <summary> /// Required algorithm the token must be signed using. /// </summary> public JwtSignatureAlgorithm SignatureAlgorithm; /// <summary> /// Required issuer (iss) the token must be from. /// </summary> public string Issuer; /// <summary> /// Required audience (aud) the token must be for. /// </summary> public string Audience; /// <summary> /// Optional one-time nonce the token must be issued in response to. /// </summary> public string Nonce; /// <summary> /// Optional maximum time since the user last authenticated. /// </summary> public TimeSpan? MaxAge = null; /// <summary> /// Amount of leeway to allow in validating date and time claims in order to allow some clock variance /// between the issuer and the application. /// </summary> public TimeSpan Leeway; /// <summary> /// Optional organization (org_id) the token must be for. /// </summary> public string Organization; /// <summary> /// Create a new instance of <see cref="IdTokenRequirements"/> with specified parameters. /// </summary> /// <param name="signatureAlgorithm"><see cref="JwtSignatureAlgorithm"/> the id token must be signed with.</param> /// <param name="issuer">Required issuer (iss) the token must be from.</param> /// <param name="audience">Required audience (aud) the token must be for.</param> /// <param name="leeway">Amount of leeway in validating date and time claims to allow some clock variance /// between the issuer and the application.</param> /// <param name="maxAge">Optional maximum time since the user last authenticated.</param> /// <param name="organization">Optional organization (org_id) the token must be for.</param> public IdTokenRequirements(JwtSignatureAlgorithm signatureAlgorithm, string issuer, string audience, TimeSpan leeway, TimeSpan? maxAge = null, string organization = null) { SignatureAlgorithm = signatureAlgorithm; Issuer = issuer; Audience = audience; Leeway = leeway; MaxAge = maxAge; Organization = organization; } } }
using System; namespace Auth0.AuthenticationApi.Tokens { /// <summary> /// Identity token validation requirements for use with <see cref="IdTokenClaimValidator"/>. /// </summary> internal class IdTokenRequirements { /// <summary> /// Required algorithm the token must be signed using. /// </summary> public JwtSignatureAlgorithm SignatureAlgorithm; /// <summary> /// Required issuer (iss) the token must be from. /// </summary> public string Issuer; /// <summary> /// Required audience (aud) the token must be for. /// </summary> public string Audience; /// <summary> /// Optional one-time nonce the token must be issued in response to. /// </summary> public string Nonce; /// <summary> /// Optional maximum time since the user last authenticated. /// </summary> public TimeSpan? MaxAge = null; /// <summary> /// Amount of leeway to allow in validating date and time claims in order to allow some clock variance /// between the issuer and the application. /// </summary> public TimeSpan Leeway; /// <summary> /// Optional organization (org_id) the token must be for. /// </summary> public string Organization; /// <summary> /// Create a new instance of <see cref="IdTokenRequirements"/> with specified parameters. /// </summary> /// <param name="signatureAlgorithm"><see cref="JwtSignatureAlgorithm"/> the id token must be signed with.</param> /// <param name="issuer">Required issuer (iss) the token must be from.</param> /// <param name="audience">Required audience (aud) the token must be for.</param> /// <param name="leeway">Amount of leeway in validating date and time claims to allow some clock variance /// between the issuer and the application.</param> /// <param name="maxAge">Optional maximum time since the user last authenticated.</param> public IdTokenRequirements(JwtSignatureAlgorithm signatureAlgorithm, string issuer, string audience, TimeSpan leeway, TimeSpan? maxAge = null, string organization = null) { SignatureAlgorithm = signatureAlgorithm; Issuer = issuer; Audience = audience; Leeway = leeway; MaxAge = maxAge; Organization = organization; } } }
mit
C#
0e721f3a135d8fe4df813ee59cf3a4d1e9b49228
Replace field by access to base class
terrajobst/nquery-vnext
NQuery.Language/Syntax/ExpressionSelectColumnSyntax.cs
NQuery.Language/Syntax/ExpressionSelectColumnSyntax.cs
using System; using System.Collections.Generic; namespace NQuery.Language { public sealed class ExpressionSelectColumnSyntax : SelectColumnSyntax { private readonly ExpressionSyntax _expression; private readonly AliasSyntax _alias; public ExpressionSelectColumnSyntax(ExpressionSyntax expression, AliasSyntax alias, SyntaxToken? commaToken) : base(commaToken) { _expression = expression; _alias = alias; } public override SyntaxKind Kind { get { return SyntaxKind.ExpressionSelectColumn; } } public override IEnumerable<SyntaxNodeOrToken> GetChildren() { yield return _expression; if (_alias != null) yield return _alias; if (CommaToken != null) yield return CommaToken.Value; } public ExpressionSyntax Expression { get { return _expression; } } public AliasSyntax Alias { get { return _alias; } } } }
using System; using System.Collections.Generic; namespace NQuery.Language { public sealed class ExpressionSelectColumnSyntax : SelectColumnSyntax { private readonly ExpressionSyntax _expression; private readonly AliasSyntax _alias; private readonly SyntaxToken? _commaToken; public ExpressionSelectColumnSyntax(ExpressionSyntax expression, AliasSyntax alias, SyntaxToken? commaToken) : base(commaToken) { _expression = expression; _alias = alias; _commaToken = commaToken; } public override SyntaxKind Kind { get { return SyntaxKind.ExpressionSelectColumn; } } public override IEnumerable<SyntaxNodeOrToken> GetChildren() { yield return _expression; if (_alias != null) yield return _alias; if (_commaToken != null) yield return _commaToken.Value; } public ExpressionSyntax Expression { get { return _expression; } } public AliasSyntax Alias { get { return _alias; } } } }
mit
C#
691590ab6a55a8dc91b551b21f045a6261658212
Change null check
pauldendulk/Mapsui,charlenni/Mapsui,charlenni/Mapsui
Samples/Mapsui.Samples.Common/Maps/Navigation/KeepCenterInMapSample.cs
Samples/Mapsui.Samples.Common/Maps/Navigation/KeepCenterInMapSample.cs
using Mapsui.Layers.Tiling; using Mapsui.Projections; using Mapsui.UI; namespace Mapsui.Samples.Common.Maps.Navigation { public class KeepCenterInMapSample : ISample { public string Name => "Keep Center In Map"; public string Category => "Navigation"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); // This is the default limiter. This limiter ensures that the center // of the viewport always is within the extent. When no PanLimits are // specified the Map.Extent is used. In this sample the extent of // Madagaskar is used. In such a scenario it makes sense to also limit // the top ZoomLimit. var extent = GetLimitsOfMadagaskar(); map.Limiter.PanLimits = extent; map.Limiter.ZoomLimits = new MinMax(0.15, 2500); map.Home = n => n.NavigateTo(extent); return map; } private static MRect GetLimitsOfMadagaskar() { var (minX, minY) = SphericalMercator.FromLonLat(41.8, -27.2); var (maxX, maxY) = SphericalMercator.FromLonLat(52.5, -11.6); return new MRect(minX, minY, maxX, maxY); } } }
using Mapsui.Layers.Tiling; using Mapsui.Projections; using Mapsui.UI; using Mapsui.Utilities; namespace Mapsui.Samples.Common.Maps.Navigation { public class KeepCenterInMapSample : ISample { public string Name => "Keep Center In Map"; public string Category => "Navigation"; public void Setup(IMapControl mapControl) { mapControl.Map = CreateMap(); } public static Map CreateMap() { var map = new Map(); map.Layers.Add(OpenStreetMap.CreateTileLayer()); // This is the default limiter. This limiter ensures that the center // of the viewport always is within the extent. When no PanLimits are // specified the Map.Extent is used. In this sample the extent of // Madagaskar is used. In such a scenario it makes sense to also limit // the top ZoomLimit. map.Limiter.PanLimits = GetLimitsOfMadagaskar(); map.Limiter.ZoomLimits = new MinMax(0.15, 2500); if (map.Limiter.PanLimits != null) map.Home = n => n.NavigateTo(map.Limiter.PanLimits); return map; } private static MRect GetLimitsOfMadagaskar() { var (minX, minY) = SphericalMercator.FromLonLat(41.8, -27.2); var (maxX, maxY) = SphericalMercator.FromLonLat(52.5, -11.6); return new MRect(minX, minY, maxX, maxY); } } }
mit
C#
b9f8cad4b490c583f8d218fd0e1957d7b5ad74a2
Increment Android version
Benrnz/CorporateBsGenerator
Droid/Properties/AssemblyInfo.cs
Droid/Properties/AssemblyInfo.cs
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("CorporateBsGenerator.Droid")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("rees.biz")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.1.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("CorporateBsGenerator.Droid")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("rees.biz")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
f9fd0772bbe5993d45b81e1db2bb5371e27c5770
Support for ReDoc
domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.ReDoc/ReDocBuilderExtensions.cs
src/Swashbuckle.AspNetCore.ReDoc/ReDocBuilderExtensions.cs
using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Swashbuckle.AspNetCore.ReDoc; namespace Microsoft.AspNetCore.Builder { public static class ReDocBuilderExtensions { public static IApplicationBuilder UseReDoc( this IApplicationBuilder app, Action<ReDocOptions> setupAction = null) { var options = new ReDocOptions(); if (setupAction != null) { setupAction(options); } else { options = app.ApplicationServices.GetRequiredService<IOptions<ReDocOptions>>().Value; } app.UseMiddleware<ReDocMiddleware>(options); return app; } } }
using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Swashbuckle.AspNetCore.ReDoc; namespace Microsoft.AspNetCore.Builder { public static class ReDocBuilderExtensions { public static IApplicationBuilder UseReDoc( this IApplicationBuilder app, Action<ReDocOptions> setupAction = null) { var options = app.ApplicationServices.GetService<IOptions<ReDocOptions>>()?.Value ?? new ReDocOptions(); setupAction?.Invoke(options); app.UseMiddleware<ReDocMiddleware>(options); return app; } } }
mit
C#
8baa66b8f398841607bb042f5eb9d2d9a68ce61b
Fix for Issue 12262
KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS
src/Umbraco.Web.UI/Views/Partials/grid/editors/base.cshtml
src/Umbraco.Web.UI/Views/Partials/grid/editors/base.cshtml
@model dynamic @try { string editor = EditorView(Model); <text>@await Html.PartialAsync(editor, Model as object)</text> } catch (Exception ex) { <pre>@ex.ToString()</pre> } @functions{ public static string EditorView(dynamic contentItem) { string view = contentItem.editor.render != null ? contentItem.editor.render.ToString() : contentItem.editor.view.ToString(); view = view.Replace(".html", ".cshtml"); if (!view.Contains("/")) { view = "grid/editors/" + view; } return view; } }
@model dynamic @try { string editor = EditorView(Model); <text>@await Html.PartialAsync(editor, Model as object)</text> } catch (Exception ex) { <pre>@ex.ToString()</pre> } @functions{ public static string EditorView(dynamic contentItem) { string view = contentItem.editor.render != null ? contentItem.editor.render.ToString() : contentItem.editor.view.ToString(); view = view.ToLower().Replace(".html", ".cshtml"); if (!view.Contains("/")) { view = "grid/editors/" + view; } return view; } }
mit
C#
23bb3334962a5a0fa1f93785438ce0fa3153cb35
Remove unused import.
Bloomcredit/SSH.NET,sshnet/SSH.NET,miniter/SSH.NET
src/Renci.SshNet.Silverlight/Session.SilverlightShared.cs
src/Renci.SshNet.Silverlight/Session.SilverlightShared.cs
namespace Renci.SshNet { public partial class Session { /// <summary> /// Gets a value indicating whether the socket is connected. /// </summary> /// <param name="isConnected"><c>true</c> if the socket is connected; otherwise, <c>false</c></param> partial void IsSocketConnected(ref bool isConnected) { isConnected = (_socket != null && _socket.Connected); } } }
using System.Linq; namespace Renci.SshNet { public partial class Session { /// <summary> /// Gets a value indicating whether the socket is connected. /// </summary> /// <param name="isConnected"><c>true</c> if the socket is connected; otherwise, <c>false</c></param> partial void IsSocketConnected(ref bool isConnected) { isConnected = (_socket != null && _socket.Connected); } } }
mit
C#
e1a23a560083ac09878fdf848d6e07bb4041f3af
simplify checkmarkvisibility behavior.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Behaviors/CheckMarkVisibilityBehavior.cs
WalletWasabi.Fluent/Behaviors/CheckMarkVisibilityBehavior.cs
using Avalonia; using Avalonia.Controls; using ReactiveUI; using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Xaml.Interactivity; namespace WalletWasabi.Fluent.Behaviors { public class CheckMarkVisibilityBehavior : Behavior<PathIcon> { public static readonly StyledProperty<TextBox> OwnerTextBoxProperty = AvaloniaProperty.Register<CheckMarkVisibilityBehavior, TextBox>(nameof(OwnerTextBox)); [ResolveByName] public TextBox OwnerTextBox { get => GetValue(OwnerTextBoxProperty); set => SetValue(OwnerTextBoxProperty, value); } private CompositeDisposable? _disposables; protected override void OnAttached() { this.WhenAnyValue(x => x.OwnerTextBox) .Subscribe( x => { _disposables?.Dispose(); if (x != null) { _disposables = new CompositeDisposable(); var hasErrors = OwnerTextBox.GetObservable(DataValidationErrors.HasErrorsProperty); var text = OwnerTextBox.GetObservable(TextBox.TextProperty); hasErrors.Select(_ => Unit.Default) .Merge(text.Select(_ => Unit.Default)) .Throttle(TimeSpan.FromMilliseconds(100)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe( _ => { if (AssociatedObject is { }) { AssociatedObject.Opacity = !DataValidationErrors.GetHasErrors(OwnerTextBox) && !string.IsNullOrEmpty(OwnerTextBox.Text) ? 1 : 0; } }) .DisposeWith(_disposables); } }); } } }
using Avalonia; using Avalonia.Controls; using ReactiveUI; using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Input; namespace WalletWasabi.Fluent.Behaviors { public class CheckMarkVisibilityBehavior : DisposingBehavior<PathIcon> { public static readonly StyledProperty<TextBox> OwnerTextBoxProperty = AvaloniaProperty.Register<CheckMarkVisibilityBehavior, TextBox>(nameof(OwnerTextBox), null!); [ResolveByName] public TextBox OwnerTextBox { get => GetValue(OwnerTextBoxProperty); set => SetValue(OwnerTextBoxProperty, value); } protected override void OnAttached(CompositeDisposable disposables) { this.WhenAnyValue( x => x.HasErrors, x => x.IsFocused, x => x.Text) .Throttle(TimeSpan.FromMilliseconds(100)) .ObserveOn(RxApp.MainThreadScheduler) .Where(_ => AssociatedObject is { }) .Subscribe(_ => AssociatedObject!.Opacity = !HasErrors && !IsFocused && !string.IsNullOrEmpty(Text) ? 1 : 0); Observable .FromEventPattern<AvaloniaPropertyChangedEventArgs>(OwnerTextBox, nameof(OwnerTextBox.PropertyChanged)) .Select(x => x.EventArgs) .Where(x => x.Property.Name == "HasErrors") .Subscribe(x => HasErrors = (bool)x.NewValue!); } } }
mit
C#
aca9289d89df4c0984a0416ad689cff0ddff6f16
Use SkinnableSprite for approach circle
UselessToucan/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,ZLima12/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,2yangk23/osu,ZLima12/osu,EVAST9919/osu
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/ApproachCircle.cs
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/ApproachCircle.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Textures; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class ApproachCircle : Container { public override bool RemoveWhenNotAlive => false; public ApproachCircle() { Anchor = Anchor.Centre; Origin = Anchor.Centre; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(TextureStore textures) { Child = new SkinnableSprite("Play/osu/approachcircle"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class ApproachCircle : Container { public override bool RemoveWhenNotAlive => false; public ApproachCircle() { Anchor = Anchor.Centre; Origin = Anchor.Centre; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(TextureStore textures) { Child = new SkinnableDrawable("Play/osu/approachcircle", name => new Sprite { Texture = textures.Get(name) }); } } }
mit
C#
77e0d7ed8e3ecc799387c5d2096183ca5269ff88
Fix formatting
NeoAdonis/osu,naoey/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,ppy/osu,DrabWeb/osu,johnneijzen/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,DrabWeb/osu,naoey/osu,peppy/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,ZLima12/osu,smoogipooo/osu,smoogipoo/osu,2yangk23/osu,peppy/osu-new
osu.Game.Rulesets.Taiko/Judgements/TaikoDrumRollTickJudgement.cs
osu.Game.Rulesets.Taiko/Judgements/TaikoDrumRollTickJudgement.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Taiko.Judgements { public class TaikoDrumRollTickJudgement : TaikoJudgement { public override bool AffectsCombo => false; protected override int NumericResultFor(HitResult result) { switch (result) { case HitResult.Great: return 200; default: return 0; } } protected override double HealthIncreaseFor(HitResult result) { switch (result) { case HitResult.Great: return 0.15; default: return 0; } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Taiko.Judgements { public class TaikoDrumRollTickJudgement : TaikoJudgement { public override bool AffectsCombo => false; protected override int NumericResultFor(HitResult result) { switch (result) { case HitResult.Great: return 200; default: return 0; } } protected override double HealthIncreaseFor(HitResult result) { switch(result) { case HitResult.Great: return 0.15; default: return 0; } } } }
mit
C#
4433397951c9aff3cce3b60bae43a50d57b5485d
Improve Cards.GetFromDbfId performance
HearthSim/HearthDb
HearthDb/Cards.cs
HearthDb/Cards.cs
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; using HearthDb.CardDefs; using HearthDb.Enums; #endregion namespace HearthDb { public static class Cards { public static readonly Dictionary<string, Card> All = new Dictionary<string, Card>(); public static readonly Dictionary<int, Card> AllByDbfId = new Dictionary<int, Card>(); public static readonly Dictionary<string, Card> Collectible = new Dictionary<string, Card>(); public static readonly Dictionary<int, Card> CollectibleByDbfId = new Dictionary<int, Card>(); public static readonly Dictionary<string, Card> BaconPoolMinions = new Dictionary<string, Card>(); public static readonly Dictionary<int, Card> BaconPoolMinionsByDbfId = new Dictionary<int, Card>(); static Cards() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HearthDb.CardDefs.xml"); if(stream == null) return; using(TextReader tr = new StreamReader(stream)) { var xml = new XmlSerializer(typeof(CardDefs.CardDefs)); var cardDefs = (CardDefs.CardDefs)xml.Deserialize(tr); foreach(var entity in cardDefs.Entites) { // For some reason Deflect-o-bot is missing divine shield if (IsDeflectOBot(entity) && !entity.Tags.Any(x => x.EnumId == (int)GameTag.DIVINE_SHIELD)) entity.Tags.Add(new Tag { EnumId = (int)GameTag.DIVINE_SHIELD, Value = 1 }); var card = new Card(entity); All.Add(entity.CardId, card); AllByDbfId.Add(entity.DbfId, card); if (card.Collectible && (card.Type != CardType.HERO || card.Set != CardSet.CORE && card.Set != CardSet.HERO_SKINS)) { Collectible.Add(entity.CardId, card); CollectibleByDbfId.Add(entity.DbfId, card); } if (card.IsBaconPoolMinion) { BaconPoolMinions.Add(entity.CardId, card); BaconPoolMinionsByDbfId.Add(entity.DbfId, card); } } } } public static Card GetFromName(string name, Locale lang, bool collectible = true) => (collectible ? Collectible : All).Values.FirstOrDefault(x => x.GetLocName(lang)?.Equals(name, StringComparison.InvariantCultureIgnoreCase) ?? false); public static Card GetFromDbfId(int dbfId, bool collectibe = true) => (collectibe ? CollectibleByDbfId : AllByDbfId).TryGetValue(dbfId, out var card) ? card : null; private static bool IsDeflectOBot(Entity entity) => entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBot || entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBotTavernBrawl; } }
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; using HearthDb.CardDefs; using HearthDb.Enums; #endregion namespace HearthDb { public static class Cards { public static readonly Dictionary<string, Card> All = new Dictionary<string, Card>(); public static readonly Dictionary<string, Card> Collectible = new Dictionary<string, Card>(); public static readonly Dictionary<string, Card> BaconPoolMinions = new Dictionary<string, Card>(); static Cards() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HearthDb.CardDefs.xml"); if(stream == null) return; using(TextReader tr = new StreamReader(stream)) { var xml = new XmlSerializer(typeof(CardDefs.CardDefs)); var cardDefs = (CardDefs.CardDefs)xml.Deserialize(tr); foreach(var entity in cardDefs.Entites) { // For some reason Deflect-o-bot is missing divine shield if (IsDeflectOBot(entity) && !entity.Tags.Any(x => x.EnumId == (int)GameTag.DIVINE_SHIELD)) entity.Tags.Add(new Tag { EnumId = (int)GameTag.DIVINE_SHIELD, Value = 1 }); var card = new Card(entity); All.Add(entity.CardId, card); if(card.Collectible && (card.Type != CardType.HERO || card.Set != CardSet.CORE && card.Set != CardSet.HERO_SKINS)) Collectible.Add(entity.CardId, card); if(card.IsBaconPoolMinion) BaconPoolMinions.Add(entity.CardId, card); } } } public static Card GetFromName(string name, Locale lang, bool collectible = true) => (collectible ? Collectible : All).Values.FirstOrDefault(x => x.GetLocName(lang)?.Equals(name, StringComparison.InvariantCultureIgnoreCase) ?? false); public static Card GetFromDbfId(int dbfId, bool collectibe = true) => (collectibe ? Collectible : All).Values.FirstOrDefault(x => x.DbfId == dbfId); private static bool IsDeflectOBot(Entity entity) => entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBot || entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBotTavernBrawl; } }
mit
C#
0cd39b009b5224f08f2647d4d7d6433d3373d218
Add unit tests
lecaillon/Evolve
test/Evolve.Test/Extensions/DbConnectionExtensionsTest.cs
test/Evolve.Test/Extensions/DbConnectionExtensionsTest.cs
using System.Data; using Evolve.Extensions; using Microsoft.Data.Sqlite; using Xunit; using System.Collections.Generic; namespace Evolve.Test.Extensions { public class DbConnectionExtensionsTest { [Fact(DisplayName = "QueryForLong works")] public void QueryForLong_works() { using (var connection = new SqliteConnection("Data Source=:memory:")) { Assert.Equal(1L, DbConnectionExtensions.QueryForLong(connection, "SELECT 1;")); Assert.True(connection.State == ConnectionState.Closed); } } [Fact(DisplayName = "QueryForString works")] public void QueryForString_works() { using (var connection = new SqliteConnection("Data Source=:memory:")) { Assert.Equal("azerty", DbConnectionExtensions.QueryForString(connection, "SELECT 'azerty';")); Assert.True(connection.State == ConnectionState.Closed); } } [Fact(DisplayName = "QueryForListOfString works")] public void QueryForListOfString_works() { using (var connection = new SqliteConnection("Data Source=:memory:")) { Assert.Equal(new List<string> { "azerty", "qwerty" }, DbConnectionExtensions.QueryForListOfString(connection, "SELECT 'azerty' UNION SELECT 'qwerty';")); Assert.True(connection.State == ConnectionState.Closed); } } } }
using System.Data; using Evolve.Extensions; using Microsoft.Data.Sqlite; using Xunit; namespace Evolve.Test.Extensions { public class DbConnectionExtensionsTest { [Fact(DisplayName = "QueryForLong works")] public void QueryForLong_works() { using (var connection = new SqliteConnection("Data Source=:memory:")) { Assert.Equal(1L, DbConnectionExtensions.QueryForLong(connection, "SELECT 1;")); Assert.True(connection.State == ConnectionState.Closed); } } } }
mit
C#
316efe379635c16e464fa03405b788da610b51b3
Refactor TaskAssertions.BeFaulted
brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync
projects/FluentSample/source/FluentSample.Core/TaskAssertions.cs
projects/FluentSample/source/FluentSample.Core/TaskAssertions.cs
//----------------------------------------------------------------------- // <copyright file="TaskAssertions.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace FluentSample { using System; using System.Threading.Tasks; using FluentAssertions.Execution; public class TaskAssertions { private readonly Task subject; public TaskAssertions(Task subject) { this.subject = subject; } public void BeCompleted(string because = "", params object[] reasonArgs) { this.AssertCondition(t => t.IsCompleted, "completed", because, reasonArgs); } public void BeCompletedSuccessfully(string because = "", params object[] reasonArgs) { this.AssertCondition(t => t.IsCompleted && !t.IsFaulted, "completed successfully", because, reasonArgs); } public void BeFaulted(string because = "", params object[] reasonArgs) { this.AssertCondition(t => t.IsFaulted, "faulted", because, reasonArgs); } private void AssertCondition(Predicate<Task> predicate, string expectedState, string because, object[] reasonArgs) { string failureMessage = "Expected task to be " + expectedState + "{reason} but was {0}."; Execute.Assertion .ForCondition(this.subject != null) .BecauseOf(because, reasonArgs) .FailWith(failureMessage, this.subject); Execute.Assertion .ForCondition(predicate(this.subject)) .BecauseOf(because, reasonArgs) .FailWith(failureMessage, this.subject.Status); } } }
//----------------------------------------------------------------------- // <copyright file="TaskAssertions.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace FluentSample { using System; using System.Threading.Tasks; using FluentAssertions.Execution; public class TaskAssertions { private readonly Task subject; public TaskAssertions(Task subject) { this.subject = subject; } public void BeCompleted(string because = "", params object[] reasonArgs) { this.AssertCondition(t => t.IsCompleted, "completed", because, reasonArgs); } public void BeCompletedSuccessfully(string because = "", params object[] reasonArgs) { this.AssertCondition(t => t.IsCompleted && !t.IsFaulted, "completed successfully", because, reasonArgs); } public void BeFaulted(string because = "", params object[] reasonArgs) { Execute.Assertion .ForCondition(this.subject != null) .BecauseOf(because, reasonArgs) .FailWith("Expected task to be faulted{reason} but was {0}.", this.subject); Execute.Assertion .ForCondition(this.subject.IsFaulted) .BecauseOf(because, reasonArgs) .FailWith("Expected task to be faulted{reason} but was {0}.", this.subject.Status); } private void AssertCondition(Predicate<Task> predicate, string expectedState, string because, object[] reasonArgs) { string failureMessage = "Expected task to be " + expectedState + "{reason} but was {0}."; Execute.Assertion .ForCondition(this.subject != null) .BecauseOf(because, reasonArgs) .FailWith(failureMessage, this.subject); Execute.Assertion .ForCondition(predicate(this.subject)) .BecauseOf(because, reasonArgs) .FailWith(failureMessage, this.subject.Status); } } }
unlicense
C#
a2ef55b89045e37d2e57b4e7cc0f8fc61ec5bbb0
Update Home/Index.cshtml
lucasdavid/Gamedalf,lucasdavid/Gamedalf
Gamedalf/Views/Home/Index.cshtml
Gamedalf/Views/Home/Index.cshtml
@model HomeViewModel @Html.Partial("_GamesList", @Model.Games) <hr /> <div class="row"> <div class="col-md-8"> <h2>Care for some change?</h2> <p> Do you have a <strong>good</strong> game? Want to <strong>share it</strong> with the community or <strong>make some profit</strong> with it? </p> @if (!User.Identity.IsAuthenticated) { <p> According with our infinitly smart database, we have no idea who you are! In order to registry your games, you must first sign up in the system. </p> <p> <a href="@Url.Action("Login", "Account")" class="btn btn-primary">Sign in</a> </p> } else { if (User.IsInRole("developer")) { <p> <a href="@Url.Action("Create", "Games")" class="btn btn-primary">Start a successful game and dominate the world!</a> </p> } if (User.IsInRole("player")) { <p> <a href="@Url.Action("Become", "Players")" class="btn btn-primary">Become a developer right now</a> </p> } } </div> <div class="col-md-4"> <img src="@Url.Content("~/Images/change.jpg")" alt="Game picture" class="img-rounded img-responsive"> </div> </div>
@model HomeViewModel @Html.Partial("_GamesList", @Model.Games) <hr /> <div class="row"> <div class="col-md-8"> <h2>Care for some change?</h2> <p> Do you have a <strong>good</strong> game? Want to <strong>share it</strong> with the community or <strong>make some profit</strong> with it? </p> @if (!User.Identity.IsAuthenticated) { <p> According with our infinitly smart database, we have no idea who you are! In order to registry your games, you must first sign up in the system. </p> <p> <a href="@Url.Action("Register", "Players")" class="btn btn-primary">Sign up</a> </p> } else { if (User.IsInRole("developer")) { <p> <a href="@Url.Action("Create", "Games")" class="btn btn-primary">Start a successful game and dominate the world!</a> </p> } if (User.IsInRole("player")) { <p> <a href="@Url.Action("Become", "Players")" class="btn btn-primary">Become a developer right now</a> </p> } if (User.IsInRole("employee")) { <p> You're a employeeeeeeeeeeee! Good for you! </p> } } </div> <div class="col-md-4"> <img src="@Url.Content("~/Images/change.jpg")" alt="Game picture" class="img-rounded img-responsive"> </div> </div>
mit
C#
e3d8db99901c62dd7a298bbef90a9a64e4852c51
Update TJobStateClient.cs
GuidanceAutomation/SchedulingClients
CSharp/SchedulingClients.Test/TJobStateClient.cs
CSharp/SchedulingClients.Test/TJobStateClient.cs
using BaseClients; using NUnit.Framework; using SchedulingClients.JobStateServiceReference; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchedulingClients.Test { [TestFixture] public class TJobStateClient : AbstractClientTest { [OneTimeSetUp] public override void OneTimeSetup() { base.OneTimeSetup(); IJobStateClient jobStateClient = ClientFactory.CreateTcpJobStateClient(settings); clients.Add(jobStateClient); } IJobStateClient JobStateClient => clients.First(e => e is IJobStateClient) as IJobStateClient; [Test] [Category("ClientExceptionNull")] public void TryGetJobSummary_ClientExceptionNull() { JobSummaryData jobSummaryData; ServiceOperationResult result = JobStateClient.TryGetJobSummary(-1, out jobSummaryData); Assert.IsNull(result.ClientException); } } }
using BaseClients; using NUnit.Framework; using SchedulingClients.JobStateServiceReference; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchedulingClients.Test { [TestFixture] [Category("JobState")] public class TJobStateClient : AbstractClientTest { [OneTimeSetUp] public override void OneTimeSetup() { base.OneTimeSetup(); IJobStateClient jobStateClient = ClientFactory.CreateTcpJobStateClient(settings); clients.Add(jobStateClient); } IJobStateClient JobStateClient => clients.First(e => e is IJobStateClient) as IJobStateClient; [Test] public void AssertZero() { JobSummaryData jobSummaryData; ServiceOperationResult result = JobStateClient.TryGetJobSummary(-1, out jobSummaryData); Assert.IsFalse(result.IsSuccessfull); } } }
mit
C#
ca2194a0bc8335b4de13b396e9915e7ae9a8f5b1
fix S_SPAWN_PROJECTILE
neowutran/OpcodeSearcher
DamageMeter.Core/Heuristic/S_SPAWN_PROJECTILE.cs
DamageMeter.Core/Heuristic/S_SPAWN_PROJECTILE.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace DamageMeter.Heuristic { public class S_SPAWN_PROJECTILE : AbstractPacketHeuristic { public static S_SPAWN_PROJECTILE Instance => _instance ?? (_instance = new S_SPAWN_PROJECTILE()); private static S_SPAWN_PROJECTILE _instance; public bool Initialized = false; private S_SPAWN_PROJECTILE() : base(OpcodeEnum.S_SPAWN_PROJECTILE) { } public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; } // 65 - current packet size from NA (EU should be too), 67 will be in future (maybe?) //TODO: ADD check with projectilOwnerId from sEachSkillResult if (message.Payload.Count == 65 || message.Payload.Count == 67) { return; } var id = Reader.ReadUInt64(); var unk1 = Reader.ReadInt32(); var skill = Reader.ReadInt32(); var startPosition = Reader.ReadVector3f(); var endPosition = Reader.ReadVector3f(); var unk2 = Reader.ReadByte(); var speed = Reader.ReadSingle(); var source = Reader.ReadUInt64(); var model = Reader.ReadUInt32(); var unk4 = Reader.ReadInt32(); var unk5 = Reader.ReadInt32(); if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.LoggedCharacter, out Tuple<Type, object> currChar)) { throw new Exception("Logger character should be know at this point."); } var ch = (LoggedCharacter)currChar.Item2; if (ch.Cid != source) { return; } if (ch.Model != model) { return; } OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace DamageMeter.Heuristic { public class S_SPAWN_PROJECTILE : AbstractPacketHeuristic { public static S_SPAWN_PROJECTILE Instance => _instance ?? (_instance = new S_SPAWN_PROJECTILE()); private static S_SPAWN_PROJECTILE _instance; public bool Initialized = false; private S_SPAWN_PROJECTILE() : base(OpcodeEnum.S_SPAWN_PROJECTILE) { } public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; } if (message.Payload.Count != 67) { return; } var id = Reader.ReadUInt64(); var unk1 = Reader.ReadInt32(); var skill = Reader.ReadInt32(); var startPosition = Reader.ReadVector3f(); var endPosition = Reader.ReadVector3f(); var unk2 = Reader.ReadByte(); var speed = Reader.ReadSingle(); var source = Reader.ReadUInt64(); var model = Reader.ReadUInt32(); var unk4 = Reader.ReadInt32(); var unk5 = Reader.ReadInt32(); if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.LoggedCharacter, out Tuple<Type, object> currChar)) { throw new Exception("Logger character should be know at this point."); } var ch = (LoggedCharacter)currChar.Item2; if (ch.Cid != source) { return; } if (ch.Model != model) { return; } OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE); } } }
mit
C#
a12b7e5832c37658bb1eb5c417463910e83448a9
Use expression body
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/CrashReport/ViewModels/CrashReportWindowViewModel.cs
WalletWasabi.Gui/CrashReport/ViewModels/CrashReportWindowViewModel.cs
using Splat; namespace WalletWasabi.Gui.CrashReport.ViewModels { public class CrashReportWindowViewModel { public CrashReportWindowViewModel() { var global = Locator.Current.GetService<Global>(); CrashReporter = global.CrashReporter; } private CrashReporter CrashReporter { get; } public int MinWidth => 370; public int MinHeight => 180; public string Title => "Wasabi Wallet - Crash Reporting"; public string Details => CrashReporter.GetException().ToString(); public string Message => CrashReporter.GetException().Message; } }
using Splat; namespace WalletWasabi.Gui.CrashReport.ViewModels { public class CrashReportWindowViewModel { public CrashReportWindowViewModel() { var global = Locator.Current.GetService<Global>(); CrashReporter = global.CrashReporter; } private CrashReporter CrashReporter { get; } public int MinWidth => 370; public int MinHeight => 180; public string Title => "Wasabi Wallet - Crash Reporting"; public string Details => CrashReporter.GetException().ToString(); public string Message { get { return CrashReporter.GetException().Message; } } } }
mit
C#
eea10f500dae50a51d00e8f6ac40755a92a34d7c
update nuget
weitaolee/Orleans.EventSourcing
Orleans.EventSourcing/Properties/AssemblyInfo.cs
Orleans.EventSourcing/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Orleans.EventSourcing")] [assembly: AssemblyDescription("Orleans Event-Sourcing Libary")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Witte Lee")] [assembly: AssemblyProduct("Orleans.EventSourcing")] [assembly: AssemblyCopyright("Copyright © Witte Lee 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("f82b183c-c122-4e97-825a-636770f135d9")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.2")] [assembly: AssemblyFileVersion("1.0.2.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Orleans.EventSourcing")] [assembly: AssemblyDescription("Orleans Event-Sourcing Libary")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Witte Lee")] [assembly: AssemblyProduct("Orleans.EventSourcing")] [assembly: AssemblyCopyright("Copyright © Witte Lee 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("f82b183c-c122-4e97-825a-636770f135d9")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.1")] [assembly: AssemblyFileVersion("1.0.2.1")]
mit
C#
63c06b0487fb24a75be23a55c9367907d8fc900f
Update demo
sunkaixuan/SqlSugar
Src/Asp.Net/SqlServerTest/Demo/Demo8_Saveable.cs
Src/Asp.Net/SqlServerTest/Demo/Demo8_Saveable.cs
using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public class Demo8_Saveable { public static void Init() { Console.WriteLine(""); Console.WriteLine("#### Saveable Start ####"); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = Config.ConnectionString, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, AopEvents = new AopEvents { OnLogExecuting = (sql, p) => { Console.WriteLine(sql); Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); } } }); //insert or update db.Saveable<Order>(new Order() { Id=1, Name="jack" }).ExecuteReturnEntity(); //insert or update db.Saveable<Order>(new Order() { Id = 1000, Name = "jack", CreateTime=DateTime.Now }) .InsertColumns(it => new { it.Name,it.CreateTime, it.Price})//if insert into name,CreateTime,Price .UpdateColumns(it => new { it.Name, it.CreateTime })//if update set name CreateTime .ExecuteReturnEntity(); Console.WriteLine(""); Console.WriteLine("#### Saveable End ####"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public class Demo8_Saveable { public static void Init() { } } }
apache-2.0
C#
37f97d3ac189ea12c57c8db10aaa1b4f0e9f7029
write out the sent commands
SexyFishHorse/IrcClient4Net
IrcClient4Net/TwitchIrcClient.cs
IrcClient4Net/TwitchIrcClient.cs
namespace SexyFishHorse.Irc.Client { using System; using System.IO; using System.Net.Sockets; using SexyFishHorse.Irc.Client.Configuration; public class TwitchIrcClient : ITwitchIrcClient { private readonly IConfiguration configuration; private TcpClient client; private StreamReader inputStream; private StreamWriter outputStream; public TwitchIrcClient(IConfiguration configuration) { this.configuration = configuration; } public void Connect() { client = new TcpClient(configuration.TwitchIrcServerName, configuration.TwitchIrcPortNumber); inputStream = new StreamReader(client.GetStream()); outputStream = new StreamWriter(client.GetStream()); outputStream.WriteLine("PASS {0}", configuration.TwitchIrcPassword); outputStream.WriteLine("NICK {0}", configuration.TwitchIrcNickname); outputStream.WriteLine("USER {0} 8 * : {0}", configuration.TwitchIrcNickname); outputStream.Flush(); } public void JoinRoom() { SendIrcMessage(string.Format("JOIN #{0}", configuration.TwitchIrcNickname)); } public void SendIrcMessage(string message) { Console.WriteLine("<SENT> " + message); outputStream.WriteLine(message); outputStream.Flush(); } public void SendChatMessage(string message) { SendIrcMessage( string.Format(configuration.TwitchIrcPrivmsgFormat, configuration.TwitchIrcNickname, message)); } public string ReadRawMessage() { return inputStream.ReadLine(); } public void LeaveRoom() { SendIrcMessage(string.Format("PART #{0}", configuration.TwitchIrcNickname)); } public void RequestMembershipCapability() { SendIrcMessage(string.Format("CAP REQ :{0}", configuration.TwitchIrcMembershipCapability)); } } }
namespace SexyFishHorse.Irc.Client { using System.IO; using System.Net.Sockets; using SexyFishHorse.Irc.Client.Configuration; public class TwitchIrcClient : ITwitchIrcClient { private readonly IConfiguration configuration; private TcpClient client; private StreamReader inputStream; private StreamWriter outputStream; public TwitchIrcClient(IConfiguration configuration) { this.configuration = configuration; } public void Connect() { client = new TcpClient(configuration.TwitchIrcServerName, configuration.TwitchIrcPortNumber); inputStream = new StreamReader(client.GetStream()); outputStream = new StreamWriter(client.GetStream()); outputStream.WriteLine("PASS {0}", configuration.TwitchIrcPassword); outputStream.WriteLine("NICK {0}", configuration.TwitchIrcNickname); outputStream.WriteLine("USER {0} 8 * : {0}", configuration.TwitchIrcNickname); outputStream.Flush(); } public void JoinRoom() { SendIrcMessage(string.Format("JOIN #{0}", configuration.TwitchIrcNickname)); } public void SendIrcMessage(string message) { outputStream.WriteLine(message); outputStream.Flush(); } public void SendChatMessage(string message) { SendIrcMessage( string.Format(configuration.TwitchIrcPrivmsgFormat, configuration.TwitchIrcNickname, message)); } public string ReadRawMessage() { return inputStream.ReadLine(); } public void LeaveRoom() { SendIrcMessage(string.Format("PART #{0}", configuration.TwitchIrcNickname)); } public void RequestMembershipCapability() { SendIrcMessage(string.Format("CAP REQ :{0}", configuration.TwitchIrcMembershipCapability)); } } }
mit
C#
cc9f96a6d3a97f70a7bc6a26279895cc5f46935c
Update CopyMoveRequest.cs
DotNetDevs/Synology,Ar3sDevelopment/Synology,DotNetDevs/Synology
Synology.FileStation/CopyMove/CopyMoveRequest.cs
Synology.FileStation/CopyMove/CopyMoveRequest.cs
using Synology.Classes; using Synology.FileStation.CopyMove.Parameters; using Synology.FileStation.CopyMove.Results; using Synology.Parameters; namespace Synology.FileStation.CopyMove { /// <summary> /// Copy / Move operations from the Synology API /// This is a non-blocking API. You need to start to copy/move files with start method. Then, you should poll requests with status method to get the progress status, or make a request with stop method to cancel the operation. /// </summary> public class CopyMoveRequest : FileStationRequest { public CopyMoveRequest(SynologyApi parentApi) : base(parentApi, "CopyMove") { } /// <summary> /// Start to copy/move files. /// </summary> /// <param name="parameters">Parameters of the operation</param> [RequestMethod("start")] public ResultData<StartResult> Start(StartParameters parameters) { return GetData<StartResult>(new SynologyRequestParameters { Version = 3, Method = "start", Additional = parameters }); } /// <summary> /// Get the copying/moving status. /// </summary> [RequestMethod("status")] public ResultData<StatusResult> Status(StatusParameters parameters) { return GetData<StatusResult>(new SynologyRequestParameters { Version = 3, Method = "status", Additional = parameters }); } /// <summary> /// Stop a copy/move task. /// </summary> [RequestMethod("stop")] public ResultData Stop(StopParameters parameters) { return GetData(new SynologyRequestParameters { Version = 3, Method = "stop", Additional = parameters }); } } }
using Synology.Classes; using Synology.FileStation.CopyMove.Parameters; using Synology.FileStation.CopyMove.Results; using Synology.Parameters; namespace Synology.FileStation.CopyMove { /// <summary> /// Copy / Move operations from the Synology API /// This is a non-blocking API. You need to start to copy/move files with start method. Then, you should poll requests with status method to get the progress status, or make a request with stop method to cancel the operation. /// </summary> public class CopyMoveRequest : FileStationRequest { public CopyMoveRequest(SynologyApi parentApi) : base(parentApi, "CopyMove") { } /// <summary> /// Start to copy/move files. /// </summary> /// <param name="parameters">Parameters of the operation</param> [RequestMethod(“start”)] public ResultData<StartResult> Start(StartParameters parameters) { return GetData<StartResult>(new SynologyRequestParameters { Version = 3, Method = "start", Additional = parameters }); } /// <summary> /// Get the copying/moving status. /// </summary> [RequestMethod(“status”)] public ResultData<StatusResult> Status(StatusParameters parameters) { return GetData<StatusResult>(new SynologyRequestParameters { Version = 3, Method = "status", Additional = parameters }); } /// <summary> /// Stop a copy/move task. /// </summary> [RequestMethod(“stop”)] public ResultData Stop(StopParameters parameters) { return GetData(new SynologyRequestParameters { Version = 3, Method = "stop", Additional = parameters }); } } }
apache-2.0
C#
0125e67677740a885fbb3af3a2a09570e3fd17c8
Use port 80 by default for containerizer
cloudfoundry/garden-windows,cloudfoundry-incubator/garden-windows,cloudfoundry/garden-windows,cloudfoundry/garden-windows,stefanschneider/garden-windows,stefanschneider/garden-windows,cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows,cloudfoundry-incubator/garden-windows
Containerizer/Program.cs
Containerizer/Program.cs
using Microsoft.Owin.Hosting; using System; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using Owin.WebSocket; using Owin.WebSocket.Extensions; using System.Threading.Tasks; namespace Containerizer { public class Program { static void Main(string[] args) { var port = (args.Length == 1 ? args[0] : "80"); // Start OWIN host try { using (WebApp.Start<Startup>("http://*:" + port + "/")) { Console.WriteLine("SUCCESS: started"); // Create HttpCient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync("http://localhost:" + port + "/api/ping").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.WriteLine("Hit a key"); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine("ERRROR: " + ex.Message); } } } }
using Microsoft.Owin.Hosting; using System; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using Owin.WebSocket; using Owin.WebSocket.Extensions; using System.Threading.Tasks; namespace Containerizer { public class Program { static void Main(string[] args) { // Start OWIN host try { using (WebApp.Start<Startup>("http://*:" + args[0] + "/")) { Console.WriteLine("SUCCESS: started"); // Create HttpCient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync("http://localhost:" + args[0] + "/api/ping").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.WriteLine("Hit a key"); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine("ERRROR: " + ex.Message); } } } }
apache-2.0
C#
1bb98e113a2f7c41aaf377bc9a761446f2002db6
fix it
ndrmc/cats,ndrmc/cats,ndrmc/cats
Web/Areas/Regional/Controllers/HomeController.cs
Web/Areas/Regional/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Cats.Helpers; using Cats.Models.Security; using Cats.Services.Dashboard; using Cats.Services.EarlyWarning; namespace Cats.Areas.Regional.Controllers { public class HomeController : Controller { private readonly IAdminUnitService _adminUnitService; public HomeController(IAdminUnitService adminUnitService) { _adminUnitService = adminUnitService; } // // GET: /Regional/Home/ public ActionResult Index() { var currentUser = UserAccountHelper.GetUser(HttpContext.User.Identity.Name); ViewBag.RegionID = currentUser.RegionID; ViewBag.RegionName = currentUser.RegionID != null ? _adminUnitService.FindById(currentUser.RegionID ?? 0).Name : ""; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Cats.Helpers; using Cats.Models.Security; using Cats.Services.Dashboard; using Cats.Services.EarlyWarning; namespace Cats.Areas.Regional.Controllers { public class HomeController : Controller { private readonly IAdminUnitService _adminUnitService; public HomeController(IAdminUnitService adminUnitService) { _adminUnitService = adminUnitService; } // // GET: /Regional/Home/ public ActionResult Index() { ViewBag.RegionID = currentUser.RegionID; var currentUser = UserAccountHelper.GetUser(HttpContext.User.Identity.Name); ViewBag.RegionName = currentUser.RegionID != null ? _adminUnitService.FindById(currentUser.RegionID ?? 0).Name : ""; return View(); } } }
apache-2.0
C#
ed0752a5f12d29de2ec0e57e7cd9ae25ee0ef729
Update test assumptions
peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game.Tests/Visual/Navigation/TestSceneEditDefaultSkin.cs
osu.Game.Tests/Visual/Navigation/TestSceneEditDefaultSkin.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Overlays.Settings.Sections; using osu.Game.Skinning; using osu.Game.Skinning.Editor; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneEditDefaultSkin : OsuGameTestScene { private SkinManager skinManager => Game.Dependencies.Get<SkinManager>(); private SkinEditorOverlay skinEditor => Game.Dependencies.Get<SkinEditorOverlay>(); [Test] public void TestEditDefaultSkin() { AddAssert("is default skin", () => skinManager.CurrentSkinInfo.Value.ID == SkinInfo.ARGON_SKIN); AddStep("open settings", () => { Game.Settings.Show(); }); // Until step requires as settings has a delayed load. AddUntilStep("export button disabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == false); // Will create a mutable skin. AddStep("open skin editor", () => skinEditor.Show()); // Until step required as the skin editor may take time to load (and an extra scheduled frame for the mutable part). AddUntilStep("is modified default skin", () => skinManager.CurrentSkinInfo.Value.ID != SkinInfo.ARGON_SKIN); AddAssert("is not protected", () => skinManager.CurrentSkinInfo.Value.PerformRead(s => !s.Protected)); AddUntilStep("export button enabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Overlays.Settings.Sections; using osu.Game.Skinning; using osu.Game.Skinning.Editor; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneEditDefaultSkin : OsuGameTestScene { private SkinManager skinManager => Game.Dependencies.Get<SkinManager>(); private SkinEditorOverlay skinEditor => Game.Dependencies.Get<SkinEditorOverlay>(); [Test] public void TestEditDefaultSkin() { AddAssert("is default skin", () => skinManager.CurrentSkinInfo.Value.ID == SkinInfo.TRIANGLES_SKIN); AddStep("open settings", () => { Game.Settings.Show(); }); // Until step requires as settings has a delayed load. AddUntilStep("export button disabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == false); // Will create a mutable skin. AddStep("open skin editor", () => skinEditor.Show()); // Until step required as the skin editor may take time to load (and an extra scheduled frame for the mutable part). AddUntilStep("is modified default skin", () => skinManager.CurrentSkinInfo.Value.ID != SkinInfo.TRIANGLES_SKIN); AddAssert("is not protected", () => skinManager.CurrentSkinInfo.Value.PerformRead(s => !s.Protected)); AddUntilStep("export button enabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == true); } } }
mit
C#
982066dfdfe2bf2356ff1d7acfc5c0827d0894cd
Convert to method group
2yangk23/osu,johnneijzen/osu,ppy/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu
osu.Game/Screens/Multi/Match/Components/MatchBeatmapPanel.cs
osu.Game/Screens/Multi/Match/Components/MatchBeatmapPanel.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Direct; using osu.Game.Rulesets; namespace osu.Game.Screens.Multi.Match.Components { public class MatchBeatmapPanel : MultiplayerComposite { [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } private GetBeatmapSetRequest request; private DirectGridPanel panel; public MatchBeatmapPanel() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { CurrentItem.BindValueChanged(item => { request?.Cancel(); if (panel != null) { panel.FadeOut(200); panel.Expire(); panel = null; } var onlineId = item.NewValue?.Beatmap.OnlineBeatmapID; if (onlineId.HasValue) { request = new GetBeatmapSetRequest(onlineId.Value, BeatmapSetLookupType.BeatmapId); request.Success += beatmap => { panel = new DirectGridPanel(beatmap.ToBeatmapSet(rulesets)); LoadComponentAsync(panel, AddInternal); }; api.Queue(request); } }, true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Direct; using osu.Game.Rulesets; namespace osu.Game.Screens.Multi.Match.Components { public class MatchBeatmapPanel : MultiplayerComposite { [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } private GetBeatmapSetRequest request; private DirectGridPanel panel; public MatchBeatmapPanel() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { CurrentItem.BindValueChanged(item => { request?.Cancel(); if (panel != null) { panel.FadeOut(200); panel.Expire(); panel = null; } var onlineId = item.NewValue?.Beatmap.OnlineBeatmapID; if (onlineId.HasValue) { request = new GetBeatmapSetRequest(onlineId.Value, BeatmapSetLookupType.BeatmapId); request.Success += beatmap => { panel = new DirectGridPanel(beatmap.ToBeatmapSet(rulesets)); LoadComponentAsync(panel, p => { AddInternal(p); }); }; api.Queue(request); } }, true); } } }
mit
C#
264987b9428c5f11fc4e6475f3a6bf96f43ee6e7
Allow passing specific settings to .Register()
NickCraver/StackExchange.Exceptional,NickCraver/StackExchange.Exceptional
src/StackExchange.Exceptional.Shared/Notifiers/IErrorNotifier.cs
src/StackExchange.Exceptional.Shared/Notifiers/IErrorNotifier.cs
namespace StackExchange.Exceptional.Notifiers { /// <summary> /// Represents a notifier, something that takes an exception that was just logged and notifies someone or something else. /// </summary> public interface IErrorNotifier { /// <summary> /// Whether this notifier is enabled. /// </summary> bool Enabled { get; } /// <summary> /// Processes an error that was just logged. /// </summary> /// <param name="error">The error to notify someone or something about.</param> void Notify(Error error); } /// <summary> /// Extensions for <see cref="IErrorNotifier"/>. /// </summary> public static class ErrorNotifierExtensions { /// <summary> /// Registers an <see cref="IErrorNotifier"/>, returning the notifier for chaining purposes. /// If the notifier is already registered, it is not registered again. /// </summary> /// <typeparam name="T">The notifier type to register (this should be inferred generics).</typeparam> /// <param name="notifier">The notifier to register.</param> /// <param name="settings">The settings object to register with, <see cref="Settings.Current"/> is used otherwise.</param> public static T Register<T>(this T notifier, Settings settings = null) where T : IErrorNotifier { var notifiers = (settings ?? Settings.Current).Notifiers; if (!notifiers.Contains(notifier)) { notifiers.Add(notifier); } return notifier; } /// <summary> /// De-registers a notifier, for disabling a notifier at runtime. /// </summary> /// <param name="notifier">The notifier to remove.</param> /// <returns>Whether the notifier was removed. <c>false</c> indicates it was not present.</returns> public static bool Deregister(IErrorNotifier notifier) => Settings.Current.Notifiers.Remove(notifier); } }
namespace StackExchange.Exceptional.Notifiers { /// <summary> /// Represents a notifier, something that takes an exception that was just logged and notifies someone or something else. /// </summary> public interface IErrorNotifier { /// <summary> /// Whether this notifier is enabled. /// </summary> bool Enabled { get; } /// <summary> /// Processes an error that was just logged. /// </summary> /// <param name="error">The error to notify someone or something about.</param> void Notify(Error error); } /// <summary> /// Extensions for <see cref="IErrorNotifier"/>. /// </summary> public static class ErrorNotifierExtensions { /// <summary> /// Registers an <see cref="IErrorNotifier"/>, returning the notifier for chaining purposes. /// If the notifier is already registered, it is not registered again. /// </summary> /// <typeparam name="T">The notifier type to register (this should be inferred generics).</typeparam> /// <param name="notifier">The notifier to register.</param> public static T Register<T>(this T notifier) where T : IErrorNotifier { var notifiers = Settings.Current.Notifiers; if (!notifiers.Contains(notifier)) { notifiers.Add(notifier); } return notifier; } /// <summary> /// De-registers a notifier, for disabling a notifier at runtime. /// </summary> /// <param name="notifier">The notifier to remove.</param> /// <returns>Whether the notifier was removed. <c>false</c> indicates it was not present.</returns> public static bool Deregister(IErrorNotifier notifier) => Settings.Current.Notifiers.Remove(notifier); } }
apache-2.0
C#
ad5b50cf56394377f844cc0f3dfa6581e5374942
add style for a textbox
LayoutFarm/PixelFarm
src/Tests/Test_BasicPixelFarm/Demo2/2.2_Demo_MultilineTextBox.cs
src/Tests/Test_BasicPixelFarm/Demo2/2.2_Demo_MultilineTextBox.cs
//Apache2, 2014-2018, WinterDev using LayoutFarm.CustomWidgets; namespace LayoutFarm { [DemoNote("2.2 MultiLineTextBox")] class Demo_MultiLineTextBox : DemoBase { protected override void OnStartDemo(SampleViewport viewport) { var textbox1 = new LayoutFarm.CustomWidgets.TextBox(400, 100, true); var style1 = new Text.TextSpanStyle(); style1.FontInfo = new PixelFarm.Drawing.RequestFont("tahoma", 18); //test with various font style style1.FontColor = new PixelFarm.Drawing.Color(255, 0, 0); textbox1.DefaultSpanStyle = style1; viewport.AddContent(textbox1); //------------------- //this version we need to set a style font each textbox var textbox2 = new LayoutFarm.CustomWidgets.TextBox(400, 500, true); var style2 = new Text.TextSpanStyle(); style2.FontInfo = new PixelFarm.Drawing.RequestFont("tahoma", 10); style2.FontColor = new PixelFarm.Drawing.Color(0, 0, 0); textbox2.SetLocation(20, 120); textbox2.DefaultSpanStyle = style2; viewport.AddContent(textbox2); var textSplitter = new ContentTextSplitter(); textbox2.TextSplitter = textSplitter; textbox2.Text = "Hello World!"; } } }
//Apache2, 2014-2018, WinterDev using LayoutFarm.CustomWidgets; namespace LayoutFarm { [DemoNote("2.2 MultiLineTextBox")] class Demo_MultiLineTextBox : DemoBase { protected override void OnStartDemo(SampleViewport viewport) { var textbox1 = new LayoutFarm.CustomWidgets.TextBox(400, 100, true); var style1 = new Text.TextSpanStyle(); style1.FontInfo = new PixelFarm.Drawing.RequestFont("tahoma", 18); //test with various font style style1.FontColor = new PixelFarm.Drawing.Color(255, 0, 0); textbox1.DefaultSpanStyle = style1; viewport.AddContent(textbox1); //------------------- var textbox2 = new LayoutFarm.CustomWidgets.TextBox(400, 500, true); textbox2.SetLocation(20, 120); viewport.AddContent(textbox2); var textSplitter = new ContentTextSplitter(); textbox2.TextSplitter = textSplitter; textbox2.Text = "Hello World!"; } } }
bsd-2-clause
C#
e54f80754a56664ce2155921380a6a26ec4049a0
fix TypedInterceptorFactory
AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions
src/AspectCore.Abstractions/Interceptors/TypedInterceptorFactory.cs
src/AspectCore.Abstractions/Interceptors/TypedInterceptorFactory.cs
using System; using System.Collections.Generic; using System.Reflection; namespace AspectCore.Abstractions { public class TypedInterceptorFactory : IInterceptorFactory { private static readonly Predicate<MethodInfo>[] EmptyPredicates = new Predicate<MethodInfo>[0]; private static readonly object[] EmptyArgs = new object[0]; private readonly ICollection<Predicate<MethodInfo>> _predicates; public object[] Args { get; } public Type InterceptorType { get; } public TypedInterceptorFactory(Type interceptorType) : this(interceptorType, null, EmptyPredicates) { } public TypedInterceptorFactory(Type interceptorType, object[] args) : this(interceptorType, args, EmptyPredicates) { } public TypedInterceptorFactory(Type interceptorType, Predicate<MethodInfo>[] predicates) : this(interceptorType, EmptyArgs, predicates) { } public TypedInterceptorFactory(Type interceptorType, object[] args, Predicate<MethodInfo>[] predicates) { if (interceptorType == null) { throw new ArgumentNullException(nameof(interceptorType)); } if (!typeof(IInterceptor).GetTypeInfo().IsAssignableFrom(interceptorType.GetTypeInfo())) { throw new ArgumentException($"{interceptorType} is not an interceptor type.", nameof(interceptorType)); } InterceptorType = interceptorType; Args = args ?? EmptyArgs; _predicates = predicates ?? EmptyPredicates; } public IInterceptor CreateInstance(IServiceProvider serviceProvider) { var activator = (ITypedInterceptorActivator)serviceProvider.GetService(typeof(ITypedInterceptorActivator)); return activator.CreateInstance(InterceptorType, Args); } public bool CanCreated(MethodInfo method) { if (_predicates.Count == 0) { return true; } foreach (var predicate in _predicates) { if (predicate(method)) return true; } return false; } } }
using System; using System.Collections.Generic; using System.Reflection; namespace AspectCore.Abstractions { public class TypedInterceptorFactory : IInterceptorFactory { private static readonly Predicate<MethodInfo>[] Empty = new Predicate<MethodInfo>[0]; private readonly ICollection<Predicate<MethodInfo>> _predicates; public object[] Args { get; } public Type InterceptorType { get; } public TypedInterceptorFactory(Type interceptorType) : this(interceptorType, null, Empty) { } public TypedInterceptorFactory(Type interceptorType, object[] args) : this(interceptorType, args, Empty) { } public TypedInterceptorFactory(Type interceptorType, Predicate<MethodInfo>[] predicates) : this(interceptorType, null, predicates) { } public TypedInterceptorFactory(Type interceptorType, object[] args, Predicate<MethodInfo>[] predicates) { if (predicates == null) { throw new ArgumentNullException(nameof(predicates)); } if (interceptorType == null) { throw new ArgumentNullException(nameof(interceptorType)); } if (!typeof(IInterceptor).GetTypeInfo().IsAssignableFrom(interceptorType.GetTypeInfo())) { throw new ArgumentException($"{interceptorType} is not an interceptor type.", nameof(interceptorType)); } InterceptorType = interceptorType; Args = args ?? new object[0]; _predicates = predicates; } public IInterceptor CreateInstance(IServiceProvider serviceProvider) { var activator = (ITypedInterceptorActivator)serviceProvider.GetService(typeof(ITypedInterceptorActivator)); return activator.CreateInstance(InterceptorType, Args); } public bool CanCreated(MethodInfo method) { foreach (var predicate in _predicates) { if (predicate(method)) return true; } return false; } } }
mit
C#
08382e5bf554381a327e215b191d901ab4b16663
Fix SolidColorBrushAnimator NRE
AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex
src/Avalonia.Visuals/Animation/Animators/SolidColorBrushAnimator.cs
src/Avalonia.Visuals/Animation/Animators/SolidColorBrushAnimator.cs
using System; using Avalonia.Data; using Avalonia.Media; using Avalonia.Media.Immutable; namespace Avalonia.Animation.Animators { /// <summary> /// Animator that handles <see cref="SolidColorBrush"/> values. /// </summary> public class ISolidColorBrushAnimator : Animator<ISolidColorBrush> { public override ISolidColorBrush Interpolate(double progress, ISolidColorBrush oldValue, ISolidColorBrush newValue) { if (oldValue is null || newValue is null) { return oldValue; } return new ImmutableSolidColorBrush(ColorAnimator.InterpolateCore(progress, oldValue.Color, newValue.Color)); } public override IDisposable BindAnimation(Animatable control, IObservable<ISolidColorBrush> instance) { return control.Bind((AvaloniaProperty<IBrush>)Property, instance, BindingPriority.Animation); } } [Obsolete] public class SolidColorBrushAnimator : Animator<SolidColorBrush> { public override SolidColorBrush Interpolate(double progress, SolidColorBrush oldValue, SolidColorBrush newValue) { if (oldValue is null || newValue is null) { return oldValue; } return new SolidColorBrush(ColorAnimator.InterpolateCore(progress, oldValue.Color, newValue.Color)); } } }
using System; using Avalonia.Data; using Avalonia.Media; using Avalonia.Media.Immutable; namespace Avalonia.Animation.Animators { /// <summary> /// Animator that handles <see cref="SolidColorBrush"/> values. /// </summary> public class ISolidColorBrushAnimator : Animator<ISolidColorBrush> { public override ISolidColorBrush Interpolate(double progress, ISolidColorBrush oldValue, ISolidColorBrush newValue) { return new ImmutableSolidColorBrush(ColorAnimator.InterpolateCore(progress, oldValue.Color, newValue.Color)); } public override IDisposable BindAnimation(Animatable control, IObservable<ISolidColorBrush> instance) { return control.Bind((AvaloniaProperty<IBrush>)Property, instance, BindingPriority.Animation); } } [Obsolete] public class SolidColorBrushAnimator : Animator<SolidColorBrush> { public override SolidColorBrush Interpolate(double progress, SolidColorBrush oldValue, SolidColorBrush newValue) { return new SolidColorBrush(ColorAnimator.InterpolateCore(progress, oldValue.Color, newValue.Color)); } } }
mit
C#