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 |
|---|---|---|---|---|---|---|---|---|
a46daffdd09426d86ca578367039b965b5b59776 | Refactor EmployeeListViewModel | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University.EmployeeList/ViewModels/EmployeeListViewModel.cs | R7.University.EmployeeList/ViewModels/EmployeeListViewModel.cs | //
// EmployeeListViewModel.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.DotNetNuke.Extensions.ViewModels;
using R7.University.EmployeeList.Components;
using R7.University.Models;
namespace R7.University.EmployeeList.ViewModels
{
public class EmployeeListViewModel
{
public EmployeeListViewModel (IEnumerable<IEmployee> employees, IDivision division)
{
Employees = employees;
Division = division;
}
public ViewModelContext<EmployeeListSettings> Context { get; protected set; }
public EmployeeListViewModel SetContext (ViewModelContext<EmployeeListSettings> context)
{
Context = context;
return this;
}
public IDivision Division { get; protected set; }
private IEnumerable<IEmployee> employees;
public IEnumerable<IEmployee> Employees
{
get {
// cache settings properties
var hideHeadEmployee = Context.Settings.HideHeadEmployee;
var divisionId = Context.Settings.DivisionID;
// filter out selected division's head employee (according to settings)
return employees.Where (e => !hideHeadEmployee || !e.OccupiedPositions
.Any (op => op.DivisionID == divisionId && op.PositionID == Division.HeadPositionID));
}
protected set { employees = value; }
}
}
}
| //
// EmployeeListViewModel.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.DotNetNuke.Extensions.ViewModels;
using R7.University.EmployeeList.Components;
using R7.University.Models;
namespace R7.University.EmployeeList.ViewModels
{
public class EmployeeListViewModel
{
protected ViewModelContext<EmployeeListSettings> Context;
public EmployeeListViewModel SetContext (ViewModelContext<EmployeeListSettings> context)
{
Context = context;
return this;
}
public EmployeeListViewModel (IEnumerable<IEmployee> employees,
IDivision division)
{
Employees = employees;
Division = division;
}
public IDivision Division { get; protected set; }
private IEnumerable<IEmployee> employees;
public IEnumerable<IEmployee> Employees
{
get {
// cache settings properties
var hideHeadEmployee = Context.Settings.HideHeadEmployee;
var divisionId = Context.Settings.DivisionID;
// filter out selected division's head employee (according to settings)
return employees.Where (e => !hideHeadEmployee || !e.OccupiedPositions
.Any (op => op.DivisionID == divisionId && op.PositionID == Division.HeadPositionID));
}
set { employees = value; }
}
}
}
| agpl-3.0 | C# |
10d8ef44ede651d148370f63f9d04735018b0322 | add MutateSettings | BigBabay/AsyncConverter,BigBabay/AsyncConverter | AsyncConverter.Tests/Highlightings/HighlightingsTestsBase.cs | AsyncConverter.Tests/Highlightings/HighlightingsTestsBase.cs | using System.IO;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
namespace AsyncConverter.Tests.Highlightings
{
[TestFixture]
[TestNetFramework46]
public abstract class HighlightingsTestsBase : CSharpHighlightingTestBase
{
[TestCaseSource(nameof(FileNames))]
public void Test(string fileName)
{
DoTestSolution(fileName);
}
protected abstract string Folder { get; }
protected override string RelativeTestDataPath => "Highlightings\\" + Folder;
protected TestCaseData[] FileNames()
{
return Directory
.GetFiles(@"..\..\Test\Data\" + RelativeTestDataPath, "*.cs")
.Select(x => new TestCaseData(Path.GetFileName(x)))
.ToArray();
}
protected override void DoTestSolution([NotNull] params string[] fileSet)
{
ExecuteWithinSettingsTransaction(settingsStore =>
{
RunGuarded(() => MutateSettings(settingsStore));
base.DoTestSolution(fileSet);
});
}
protected virtual void MutateSettings([NotNull] IContextBoundSettingsStore settingsStore)
{
}
}
} | using System.IO;
using System.Linq;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
namespace AsyncConverter.Tests.Highlightings
{
[TestFixture]
[TestNetFramework46]
public abstract class HighlightingsTestsBase : CSharpHighlightingTestBase
{
[TestCaseSource(nameof(FileNames))]
public void Test(string fileName)
{
DoTestSolution(fileName);
}
protected abstract string Folder { get; }
protected override string RelativeTestDataPath => "Highlightings\\" + Folder;
protected TestCaseData[] FileNames()
{
return Directory
.GetFiles(@"..\..\Test\Data\" + RelativeTestDataPath, "*.cs")
.Select(x => new TestCaseData(Path.GetFileName(x)))
.ToArray();
}
}
} | mit | C# |
0557d4ecdfa1aa57badb53cfa48c99fca9a90289 | Revert "Rename field." | Zakkgard/Moonfire | Moonfire/Core/Moonfire.Core/Networking/IncomingRealmPacket.cs | Moonfire/Core/Moonfire.Core/Networking/IncomingRealmPacket.cs | using Moonfire.Core.Constants;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Moonfire.Core.Networking
{
public class IncomingRealmPacket : IncomingPacket
{
public IncomingRealmPacket(byte[] packet, int length)
: base(packet, 0, length)
{
this.Length = base.ReadUInt16();
this.PacketId = (WorldOpCode)base.ReadUInt16();
}
public WorldOpCode PacketId { get; set; }
public uint Length { get; set; }
}
}
| using Moonfire.Core.Constants;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Moonfire.Core.Networking
{
public class IncomingRealmPacket : IncomingPacket
{
public IncomingRealmPacket(byte[] packet, int length)
: base(packet, 0, length)
{
this.Lenght = base.ReadUInt16();
this.PacketId = (WorldOpCode)base.ReadUInt16();
}
public WorldOpCode PacketId { get; set; }
public uint Lenght { get; set; }
}
}
| mit | C# |
020d59e52336c065bb8e3e26ebd50263e3a61943 | Update ShapeStyleDragAndDropListBox.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs | Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="ShapeStyle"/> items with drag and drop support.
/// </summary>
public class ShapeStyleDragAndDropListBox : DragAndDropListBox<ShapeStyle>
{
/// <summary>
/// Initializes a new instance of the <see cref="ShapeStyleDragAndDropListBox"/> class.
/// </summary>
public ShapeStyleDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<ShapeStyle> array)
{
var editor = (Core2D.Editor)this.Tag;
var sg = editor.Project.CurrentStyleLibrary;
var previous = sg.Items;
var next = array;
editor.project?.History?.Snapshot(previous, next, (p) => sg.Items = p);
sg.Items = next;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="ShapeStyle"/> items with drag and drop support.
/// </summary>
public class ShapeStyleDragAndDropListBox : DragAndDropListBox<ShapeStyle>
{
/// <summary>
/// Initializes a new instance of the <see cref="ShapeStyleDragAndDropListBox"/> class.
/// </summary>
public ShapeStyleDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<ShapeStyle> array)
{
var editor = (Core2D.Editor)this.Tag;
var sg = editor.Project.CurrentStyleLibrary;
var previous = sg.Items;
var next = array;
editor.Project.History.Snapshot(previous, next, (p) => sg.Items = p);
sg.Items = next;
}
}
}
| mit | C# |
2d7718a9be85538c1a7562f41e7675059a195959 | refactor view | Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017 | PhotoArtSystem/Web/PhotoArtSystem.Web/Views/Home/Index.cshtml | PhotoArtSystem/Web/PhotoArtSystem.Web/Views/Home/Index.cshtml | @using PhotoArtSystem.Web.ViewModels.User
@model IEnumerable<UserHomePageViewModel>
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
| @using PhotoArtSystem.Web.ViewModels.User
@model IEnumerable<UserHomePageViewModel>
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<h3>Users</h3>
<br />
<div class="row">
<div class="col-md-5">
User Id
</div>
<div class="col-md-2">
Username
</div>
<div class="col-md-3">
Email
</div>
<div class="col-md-2">
CreatedOn
</div>
</div>
<hr />
@foreach (var user in Model)
{
<div class="row">
<div class="col-md-5">
@user.Id
</div>
<div class="col-md-2">
@user.UserName
</div>
<div class="col-md-3">
@user.Email
</div>
<div class="col-md-2">
@user.CreatedOn.ToLocalTime()
</div>
</div>
}
| mit | C# |
a1cdff0a06ee1a4bf6d2b2c75e927c296c0b14da | update conf var retrieve | WebmarksApp/webmarks.nancy,WebmarksApp/webmarks.nancy,WebmarksApp/webmarks.nancy | webmarks.nancy/Bootstrapper.cs | webmarks.nancy/Bootstrapper.cs | using MongoDB.Driver;
using Nancy;
using Nancy.Conventions;
using Nancy.TinyIoc;
using System;
using System.Configuration;
using webmarks.nancy.Models;
namespace webmarks.nancy
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
base.ConfigureConventions(nancyConventions);
Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", @"Content"));
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
//var connString = "mongodb://localhost:27017";
var connString = Environment.GetEnvironmentVariable("MONGOLAB_URI");
if(connString == null)
{
connString = ConfigurationManager.AppSettings.Get("MONGOLAB_URI");
}
var databaseName = "speakersdb";
var mongoClient = new MongoClient(connString);
//MongoServer server = mongoClient.GetServer();
var database = mongoClient.GetDatabase(databaseName);
var collection = database.GetCollection<Speaker>("speakers");
container.Register(database);
container.Register(collection);
}
}
} | using MongoDB.Driver;
using Nancy;
using Nancy.Conventions;
using Nancy.TinyIoc;
using System;
using System.Configuration;
using webmarks.nancy.Models;
namespace webmarks.nancy
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
base.ConfigureConventions(nancyConventions);
Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", @"Content"));
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
//var connString = "mongodb://localhost:27017";
//var connString = Environment.GetEnvironmentVariable("MONGOLAB_URI");
var connString = ConfigurationManager.AppSettings.Get("MONGOLAB_URI");
var databaseName = "speakersdb";
var mongoClient = new MongoClient(connString);
//MongoServer server = mongoClient.GetServer();
var database = mongoClient.GetDatabase(databaseName);
var collection = database.GetCollection<Speaker>("speakers");
container.Register(database);
container.Register(collection);
}
}
} | mit | C# |
7f79cbc3de12a45ce7b3485a614df2a058ee89cc | fix build yo | ryancormack/HipsterOfTheDay | HipsterOfTheDay.Tests/ControllerTests/HomeControllerTests.cs | HipsterOfTheDay.Tests/ControllerTests/HomeControllerTests.cs | using FluentAssertions;
using HipsterOfTheDay.Features.Home;
using Machine.Specifications;
using System.Web.Mvc;
namespace HipsterOfTheDay.Tests.ControllerTests
{
public class HomeControllerTests
{
public class When_getting_the_home_page
{
public Because of = () =>
{
_result = _controller.Index();
};
public It should_return_home_page = () =>
{
(_result as ViewResult).ViewName.Should().Be("Index");
};
public Establish context = () =>
{
//_controller = new HomeController();
};
private static HomeController _controller;
private static ActionResult _result;
}
}
}
| using FluentAssertions;
using HipsterOfTheDay.Features.Home;
using Machine.Specifications;
using System.Web.Mvc;
namespace HipsterOfTheDay.Tests.ControllerTests
{
public class HomeControllerTests
{
public class When_getting_the_home_page
{
public Because of = () =>
{
_result = _controller.Index();
};
public It should_return_home_page = () =>
{
(_result as ViewResult).ViewName.Should().Be("Index");
};
public Establish context = () =>
{
_controller = new HomeController();
};
private static HomeController _controller;
private static ActionResult _result;
}
}
}
| apache-2.0 | C# |
b32850a8042456c45871f4cc0e7b5b9d56641729 | fix possible `IndexOutOfRange` bug (#979) | TomPallister/Ocelot,geffzhang/Ocelot,geffzhang/Ocelot,TomPallister/Ocelot | src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs | src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs | namespace Ocelot.Infrastructure.Claims.Parser
{
using Microsoft.Extensions.Primitives;
using Responses;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
public class ClaimsParser : IClaimsParser
{
public Response<string> GetValue(IEnumerable<Claim> claims, string key, string delimiter, int index)
{
var claimResponse = GetValue(claims, key);
if (claimResponse.IsError)
{
return claimResponse;
}
if (string.IsNullOrEmpty(delimiter))
{
return claimResponse;
}
var splits = claimResponse.Data.Split(delimiter.ToCharArray());
if (splits.Length <= index || index < 0)
{
return new ErrorResponse<string>(new CannotFindClaimError($"Cannot find claim for key: {key}, delimiter: {delimiter}, index: {index}"));
}
var value = splits[index];
return new OkResponse<string>(value);
}
public Response<List<string>> GetValuesByClaimType(IEnumerable<Claim> claims, string claimType)
{
List<string> values = new List<string>();
values.AddRange(claims.Where(x => x.Type == claimType).Select(x => x.Value).ToList());
return new OkResponse<List<string>>(values);
}
private Response<string> GetValue(IEnumerable<Claim> claims, string key)
{
var claimValues = claims.Where(c => c.Type == key).Select(c => c.Value).ToArray();
if (claimValues.Length > 0)
{
return new OkResponse<string>(new StringValues(claimValues).ToString());
}
return new ErrorResponse<string>(new CannotFindClaimError($"Cannot find claim for key: {key}"));
}
}
}
| namespace Ocelot.Infrastructure.Claims.Parser
{
using Microsoft.Extensions.Primitives;
using Responses;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
public class ClaimsParser : IClaimsParser
{
public Response<string> GetValue(IEnumerable<Claim> claims, string key, string delimiter, int index)
{
var claimResponse = GetValue(claims, key);
if (claimResponse.IsError)
{
return claimResponse;
}
if (string.IsNullOrEmpty(delimiter))
{
return claimResponse;
}
var splits = claimResponse.Data.Split(delimiter.ToCharArray());
if (splits.Length < index || index < 0)
{
return new ErrorResponse<string>(new CannotFindClaimError($"Cannot find claim for key: {key}, delimiter: {delimiter}, index: {index}"));
}
var value = splits[index];
return new OkResponse<string>(value);
}
public Response<List<string>> GetValuesByClaimType(IEnumerable<Claim> claims, string claimType)
{
List<string> values = new List<string>();
values.AddRange(claims.Where(x => x.Type == claimType).Select(x => x.Value).ToList());
return new OkResponse<List<string>>(values);
}
private Response<string> GetValue(IEnumerable<Claim> claims, string key)
{
var claimValues = claims.Where(c => c.Type == key).Select(c => c.Value).ToArray();
if (claimValues.Length > 0)
{
return new OkResponse<string>(new StringValues(claimValues).ToString());
}
return new ErrorResponse<string>(new CannotFindClaimError($"Cannot find claim for key: {key}"));
}
}
}
| mit | C# |
e6e20da076444349a34d5a529830840374b24c8a | Update database consistency check report test to abstract report test | Kentico/KInspector,Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector | KenticoInspector.Reports.Tests/DatabaseConsistencyCheckTests.cs | KenticoInspector.Reports.Tests/DatabaseConsistencyCheckTests.cs | using System.Data;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Services.Interfaces;
using KenticoInspector.Reports.DatabaseConsistencyCheck;
using KenticoInspector.Reports.DatabaseConsistencyCheck.Models;
using KenticoInspector.Reports.Tests.Helpers;
using Moq;
using NUnit.Framework;
namespace KenticoInspector.Reports.Tests
{
[TestFixture(10)]
[TestFixture(11)]
[TestFixture(12)]
public class DatabaseConsistencyCheckTests : AbstractReportTest<Report, Terms>
{
private Report _mockReport;
public DatabaseConsistencyCheckTests(int majorVersion) : base(majorVersion)
{
_mockReport = new Report(_mockDatabaseService.Object, _mockReportMetadataService.Object);
}
[Test]
public void Should_ReturnGoodStatus_When_ResultsEmpty()
{
// Arrange
var emptyResult = new DataTable();
#pragma warning disable 0618 // This is a special exemption as the results of CheckDB are unknown
_mockDatabaseService
.Setup(p => p.ExecuteSqlFromFileAsDataTable(Scripts.GetCheckDbResults))
.Returns(emptyResult);
#pragma warning restore 0618
// Act
var results = _mockReport.GetResults();
//Assert
Assert.That(results.Status == ReportResultsStatus.Good);
}
[Test]
public void Should_ReturnErrorStatus_When_ResultsNotEmpty()
{
// Arrange
var result = new DataTable();
result.Columns.Add("TestColumn");
result.Rows.Add("value");
# pragma warning disable 0618 // This is a special exemption as the results of CheckDB are unknown
_mockDatabaseService
.Setup(p => p.ExecuteSqlFromFileAsDataTable(Scripts.GetCheckDbResults))
.Returns(result);
# pragma warning restore 0618
// Act
var results = _mockReport.GetResults();
//Assert
Assert.That(results.Status == ReportResultsStatus.Error);
}
}
} | using System.Data;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Services.Interfaces;
using KenticoInspector.Reports.DatabaseConsistencyCheck;
using KenticoInspector.Reports.DatabaseConsistencyCheck.Models;
using KenticoInspector.Reports.Tests.Helpers;
using Moq;
using NUnit.Framework;
namespace KenticoInspector.Reports.Tests
{
[TestFixture(10)]
[TestFixture(11)]
[TestFixture(12)]
public class DatabaseConsistencyCheckTests
{
private Mock<IDatabaseService> _mockDatabaseService;
private Mock<IReportMetadataService> _mockReportMetadataService;
private Report _mockReport;
public DatabaseConsistencyCheckTests(int majorVersion)
{
InitializeCommonMocks(majorVersion);
_mockReportMetadataService = MockReportMetadataServiceHelper.GetReportMetadataService();
_mockReport = new Report(_mockDatabaseService.Object, _mockReportMetadataService.Object);
MockReportMetadataServiceHelper.SetupReportMetadataService<Terms>(_mockReportMetadataService, _mockReport);
}
[Test]
public void Should_ReturnGoodStatus_When_ResultsEmpty()
{
// Arrange
var emptyResult = new DataTable();
#pragma warning disable 0618 // This is a special exemption as the results of CheckDB are unknown
_mockDatabaseService
.Setup(p => p.ExecuteSqlFromFileAsDataTable(Scripts.GetCheckDbResults))
.Returns(emptyResult);
#pragma warning restore 0618
// Act
var results = _mockReport.GetResults();
//Assert
Assert.That(results.Status == ReportResultsStatus.Good);
}
[Test]
public void Should_ReturnErrorStatus_When_ResultsNotEmpty()
{
// Arrange
var result = new DataTable();
result.Columns.Add("TestColumn");
result.Rows.Add("value");
# pragma warning disable 0618 // This is a special exemption as the results of CheckDB are unknown
_mockDatabaseService
.Setup(p => p.ExecuteSqlFromFileAsDataTable(Scripts.GetCheckDbResults))
.Returns(result);
# pragma warning restore 0618
// Act
var results = _mockReport.GetResults();
//Assert
Assert.That(results.Status == ReportResultsStatus.Error);
}
private void InitializeCommonMocks(int majorVersion)
{
var mockInstance = MockInstances.Get(majorVersion);
_mockDatabaseService = MockDatabaseServiceHelper.SetupMockDatabaseService(mockInstance);
}
}
} | mit | C# |
de4e4ad4d3d8627e380f37c9d0af0d8443ec000f | Simplify logic. | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.InlineReviews/Tags/ReviewGlyphMouseProcessor.cs | src/GitHub.InlineReviews/Tags/ReviewGlyphMouseProcessor.cs | using System;
using System.Linq;
using System.Windows.Input;
using GitHub.InlineReviews.Peek;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace GitHub.InlineReviews.Tags
{
class ReviewGlyphMouseProcessor : MouseProcessorBase
{
readonly IPeekBroker peekBroker;
readonly ITextView textView;
readonly IWpfTextViewMargin margin;
readonly ITagAggregator<ReviewTag> tagAggregator;
public ReviewGlyphMouseProcessor(
IPeekBroker peekBroker,
ITextView textView,
IWpfTextViewMargin margin,
ITagAggregator<ReviewTag> aggregator)
{
this.peekBroker = peekBroker;
this.textView = textView;
this.margin = margin;
this.tagAggregator = aggregator;
}
public override void PreprocessMouseLeftButtonUp(MouseButtonEventArgs e)
{
var y = e.GetPosition(margin.VisualElement).Y + textView.ViewportTop;
var line = textView.TextViewLines.GetTextViewLineContainingYCoordinate(y);
if (line != null)
{
var tag = tagAggregator.GetTags(line.ExtentAsMappingSpan).FirstOrDefault();
if (tag != null)
{
var trackingPoint = textView.TextSnapshot.CreateTrackingPoint(line.Start.Position, PointTrackingMode.Positive);
var session = peekBroker.TriggerPeekSession(
textView,
trackingPoint,
ReviewPeekRelationship.Instance.Name);
e.Handled = true;
}
}
}
}
}
| using System;
using System.Linq;
using System.Windows.Input;
using GitHub.InlineReviews.Peek;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace GitHub.InlineReviews.Tags
{
class ReviewGlyphMouseProcessor : MouseProcessorBase
{
readonly IPeekBroker peekBroker;
readonly ITextView textView;
readonly IWpfTextViewMargin margin;
readonly ITagAggregator<ReviewTag> tagAggregator;
public ReviewGlyphMouseProcessor(
IPeekBroker peekBroker,
ITextView textView,
IWpfTextViewMargin margin,
ITagAggregator<ReviewTag> aggregator)
{
this.peekBroker = peekBroker;
this.textView = textView;
this.margin = margin;
this.tagAggregator = aggregator;
}
public override void PreprocessMouseLeftButtonUp(MouseButtonEventArgs e)
{
var y = e.GetPosition(margin.VisualElement).Y + textView.ViewportTop;
var line = textView.TextViewLines.GetTextViewLineContainingYCoordinate(y);
if (line != null)
{
var tag = tagAggregator.GetTags(line.ExtentAsMappingSpan).FirstOrDefault();
if (tag != null)
{
var snapshotPoint = tag.Span.Start.GetPoint(textView.TextBuffer, PositionAffinity.Predecessor);
var trackingPoint = textView.TextSnapshot.CreateTrackingPoint(snapshotPoint.Value.Position, PointTrackingMode.Positive);
var session = peekBroker.TriggerPeekSession(
textView,
trackingPoint,
ReviewPeekRelationship.Instance.Name);
e.Handled = true;
}
}
}
}
}
| mit | C# |
76162baf6b22f5c452774093c2ec1a775d815680 | Update Framework.Runtime usings | hackathonvixion/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore,hackathonvixion/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,hackathonvixion/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore | test/Mvc6Framework45.FunctionalTests/Controllers/HomeController.cs | test/Mvc6Framework45.FunctionalTests/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNet.Mvc;
using Microsoft.Dnx.Runtime;
namespace Mvc6Framework45.FunctionalTests.Controllers
{
public class HomeController : Controller
{
private TelemetryClient telemetryClient;
private IApplicationEnvironment applicationEnvironment;
public HomeController(TelemetryClient telemetryClient, IApplicationEnvironment applicationEnvironment)
{
this.telemetryClient = telemetryClient;
this.applicationEnvironment = applicationEnvironment;
}
public IActionResult Index()
{
return View();
}
public IActionResult Exception()
{
throw new InvalidOperationException("Do not call the method called Exception");
}
public IActionResult About(int index)
{
ViewBag.Message = "Your application description page # " + index;
return View();
}
public async Task<IActionResult> Contact()
{
ViewBag.Message = await this.GetContactDetails();
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
private async Task<string> GetContactDetails()
{
var contactFilePath = Path.Combine(this.applicationEnvironment.ApplicationBasePath, "contact.txt");
this.telemetryClient.TrackEvent("GetContact");
using (var reader = System.IO.File.OpenText(contactFilePath))
{
var contactDetails = await reader.ReadToEndAsync();
this.telemetryClient.TrackMetric("ContactFile", 1);
this.telemetryClient.TrackTrace("Fetched contact details.", SeverityLevel.Information);
return contactDetails;
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.Runtime;
namespace Mvc6Framework45.FunctionalTests.Controllers
{
public class HomeController : Controller
{
private TelemetryClient telemetryClient;
private IApplicationEnvironment applicationEnvironment;
public HomeController(TelemetryClient telemetryClient, IApplicationEnvironment applicationEnvironment)
{
this.telemetryClient = telemetryClient;
this.applicationEnvironment = applicationEnvironment;
}
public IActionResult Index()
{
return View();
}
public IActionResult Exception()
{
throw new InvalidOperationException("Do not call the method called Exception");
}
public IActionResult About(int index)
{
ViewBag.Message = "Your application description page # " + index;
return View();
}
public async Task<IActionResult> Contact()
{
ViewBag.Message = await this.GetContactDetails();
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
private async Task<string> GetContactDetails()
{
var contactFilePath = Path.Combine(this.applicationEnvironment.ApplicationBasePath, "contact.txt");
this.telemetryClient.TrackEvent("GetContact");
using (var reader = System.IO.File.OpenText(contactFilePath))
{
var contactDetails = await reader.ReadToEndAsync();
this.telemetryClient.TrackMetric("ContactFile", 1);
this.telemetryClient.TrackTrace("Fetched contact details.", SeverityLevel.Information);
return contactDetails;
}
}
}
} | mit | C# |
5e338f8588a01f050d54a330c59cbb0672327a66 | Update IDocumentMetadataManager.cs | Ant-f/WorkingFilesList | Solution/WorkingFilesList.Core/Interface/IDocumentMetadataManager.cs | Solution/WorkingFilesList.Core/Interface/IDocumentMetadataManager.cs | // Working Files List
// Visual Studio extension tool window that shows a selectable list of files
// that are open in the editor
// Copyright © 2016 Anthony Fung
// 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 EnvDTE;
using System.ComponentModel;
using WorkingFilesList.Core.Model;
namespace WorkingFilesList.Core.Interface
{
public interface IDocumentMetadataManager : IPinnedMetadataManager
{
ICollectionView ActiveDocumentMetadata { get; }
string FilterString { get; set; }
void Activate(string fullName);
void Add(DocumentMetadataInfo info);
void AddPinned(DocumentMetadataInfo info);
void Clear();
bool UpdateFullName(string newName, string oldName);
void Synchronize(Documents documents, bool setUsageOrder);
}
}
| // Working Files List
// Visual Studio extension tool window that shows a selectable list of files
// that are open in the editor
// Copyright © 2016 Anthony Fung
// 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 EnvDTE;
using System.ComponentModel;
using WorkingFilesList.Core.Model;
namespace WorkingFilesList.Core.Interface
{
public interface IDocumentMetadataManager : IPinnedMetadataManager
{
ICollectionView ActiveDocumentMetadata { get; }
void Activate(string fullName);
void Add(DocumentMetadataInfo info);
void AddPinned(DocumentMetadataInfo info);
void Clear();
bool UpdateFullName(string newName, string oldName);
void Synchronize(Documents documents, bool setUsageOrder);
}
}
| apache-2.0 | C# |
9cc68aefb8b02c6d02225483a6b45f6ffff8ddab | Make more functions public. | TammiLion/TacoTinder | TacoTinder/Assets/Scripts/Player.cs | TacoTinder/Assets/Scripts/Player.cs | using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float baseCooldown;
public float baseSpeed;
public God god;
public Vector2 direction; // Maybe this should be private?
// public Weapon weapon;
private float cooldownTimeStamp;
// Use this for initialization
void Start () {
}
public void Move(float horizontal, float vertical) {
Vector2 moveDirection = new Vector2 (horizontal, vertical);
}
public void Fire () {
// Don't fire when the cooldown is still active.
if (this.cooldownTimeStamp >= Time.time) {
return;
}
// Fire the weapon.
// TODO
// Set the cooldown.
this.cooldownTimeStamp = Time.time + this.baseCooldown;
}
// Update is called once per frame
void Update () {
}
}
| using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float baseCooldown;
public float baseSpeed;
public God god;
public Vector2 direction;
// public Weapon weapon;
private float cooldownTimeStamp;
// Use this for initialization
void Start () {
}
void Fire () {
// Don't fire when the cooldown is still active.
if (this.cooldownTimeStamp >= Time.time) {
return;
}
// Fire the weapon.
// TODO
// Set the cooldown.
this.cooldownTimeStamp = Time.time + this.baseCooldown;
}
// Update is called once per frame
void Update () {
}
}
| apache-2.0 | C# |
c4dceb7bd59c834c0f00012520764c9ed85f6ee1 | Update Watchman.cs (#45) | BosslandGmbH/BuddyWing.DefaultCombat | trunk/DefaultCombat/Routines/Advanced/Sentinel/Watchman.cs | trunk/DefaultCombat/Routines/Advanced/Sentinel/Watchman.cs | // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class Watchman : RotationBase
{
public override string Name
{
get { return "Sentinel Watchman"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Force Might")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Buff("Rebuke", ret => Me.HealthPercent <= 50),
Spell.Buff("Guarded by the Force", ret => Me.HealthPercent <= 10),
Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 30)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
//Movement
CombatMovement.CloseDistance(Distance.Melee),
//Rotation
Spell.Cast("Force Kick", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled),
Spell.Buff("Zen", ret => Me.BuffCount("Centering") > 29),
Spell.Buff("Valorous Call", ret => Me.BuffCount("Centering") < 5),
Spell.Buff("Overload Saber", ret => !Me.HasBuff("Overload Saber")),
Spell.DoT("Cauterize", "Burning (Cauterize)"),
Spell.DoT("Force Melt", "Burning (Force Melt)"),
Spell.Cast("Dispatch", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Merciless Slash"),
Spell.Cast("Zealous Strike", ret => Me.ActionPoints <= 5),
Spell.Cast("Blade Barrage"),
Spell.Cast("Slash", ret => Me.Level < 41),
Spell.Cast("Strike", ret => Me.ActionPoints <= 10)
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldPbaoe,
new PrioritySelector(
Spell.Cast("Force Sweep"),
Spell.Cast("Twin Saber Throw"),
Spell.Cast("Cyclone Slash")
));
}
}
}
}
| // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class Watchman : RotationBase
{
public override string Name
{
get { return "Sentinel Watchman"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Juyo Form"),
Spell.Buff("Force Might")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Buff("Rebuke", ret => Me.HealthPercent <= 50),
Spell.Buff("Guarded by the Force", ret => Me.HealthPercent <= 10),
Spell.Buff("Saber Ward", ret => Me.HealthPercent <= 30)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
//Movement
CombatMovement.CloseDistance(Distance.Melee),
//Rotation
Spell.Cast("Force Kick", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled),
Spell.Buff("Zen", ret => Me.BuffCount("Centering") > 29),
Spell.Buff("Valorous Call", ret => Me.BuffCount("Centering") < 5),
Spell.Buff("Overload Saber", ret => !Me.HasBuff("Overload Saber")),
Spell.DoT("Cauterize", "Burning (Cauterize)"),
Spell.DoT("Force Melt", "Burning (Force Melt)"),
Spell.Cast("Dispatch", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Merciless Slash"),
Spell.Cast("Zealous Strike", ret => Me.ActionPoints <= 5),
Spell.Cast("Blade Dance"),
Spell.Cast("Slash", ret => Me.Level < 41),
Spell.Cast("Strike", ret => Me.ActionPoints <= 10)
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldPbaoe,
new PrioritySelector(
Spell.Cast("Force Sweep"),
Spell.Cast("Twin Saber Throw"),
Spell.Cast("Cyclone Slash")
));
}
}
}
} | apache-2.0 | C# |
50202d3e47835138d79519bf51278285e37f6b68 | Abort key handling if SDL2 passes us an unknown key | EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Input/Handlers/Keyboard/Sdl2KeyboardHandler.cs | osu.Framework/Input/Handlers/Keyboard/Sdl2KeyboardHandler.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.Input.StateChanges;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using Veldrid;
using TKKey = osuTK.Input.Key;
namespace osu.Framework.Input.Handlers.Keyboard
{
public class Sdl2KeyboardHandler : InputHandler
{
private readonly KeyboardState lastKeyboardState = new KeyboardState();
private readonly KeyboardState thisKeyboardState = new KeyboardState();
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host)
{
if (!(host.Window is Window window))
return false;
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
window.KeyDown += handleKeyboardEvent;
window.KeyUp += handleKeyboardEvent;
}
else
{
window.KeyDown -= handleKeyboardEvent;
window.KeyUp -= handleKeyboardEvent;
}
}, true);
return true;
}
private void handleKeyboardEvent(KeyEvent keyEvent)
{
if (keyEvent.Key == Key.Unknown)
return;
thisKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
PendingInputs.Enqueue(new KeyboardKeyInput(thisKeyboardState.Keys, lastKeyboardState.Keys));
lastKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
FrameStatistics.Increment(StatisticsCounterType.KeyEvents);
}
}
}
| // 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.Input.StateChanges;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using Veldrid;
using TKKey = osuTK.Input.Key;
namespace osu.Framework.Input.Handlers.Keyboard
{
public class Sdl2KeyboardHandler : InputHandler
{
private readonly KeyboardState lastKeyboardState = new KeyboardState();
private readonly KeyboardState thisKeyboardState = new KeyboardState();
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host)
{
if (!(host.Window is Window window))
return false;
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
window.KeyDown += handleKeyboardEvent;
window.KeyUp += handleKeyboardEvent;
}
else
{
window.KeyDown -= handleKeyboardEvent;
window.KeyUp -= handleKeyboardEvent;
}
}, true);
return true;
}
private void handleKeyboardEvent(KeyEvent keyEvent)
{
thisKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
PendingInputs.Enqueue(new KeyboardKeyInput(thisKeyboardState.Keys, lastKeyboardState.Keys));
lastKeyboardState.Keys.SetPressed((TKKey)keyEvent.Key, keyEvent.Down);
FrameStatistics.Increment(StatisticsCounterType.KeyEvents);
}
}
}
| mit | C# |
edfe47fb0268fdadd0848595cdcc1c7f046a32ed | Rename button | johnneijzen/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,peppy/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,smoogipooo/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,2yangk23/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu | osu.Game.Tests/Visual/UserInterface/TestSceneExpandingBar.cs | osu.Game.Tests/Visual/UserInterface/TestSceneExpandingBar.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.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneExpandingBar : OsuTestScene
{
public TestSceneExpandingBar()
{
Container container;
ExpandingBar expandingBar;
Add(container = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Gray,
Alpha = 0.5f,
RelativeSizeAxes = Axes.Both,
},
expandingBar = new ExpandingBar
{
Anchor = Anchor.Centre,
ExpandedSize = 10,
CollapsedSize = 2,
Colour = Color4.DeepSkyBlue,
}
}
});
AddStep(@"Collapse", () => expandingBar.Collapse());
AddStep(@"Expand", () => expandingBar.Expand());
AddSliderStep(@"Resize container", 1, 300, 150, value => container.ResizeTo(value));
AddStep(@"Horizontal", () => expandingBar.RelativeSizeAxes = Axes.X);
AddStep(@"Anchor top", () => expandingBar.Anchor = Anchor.TopCentre);
AddStep(@"Vertical", () => expandingBar.RelativeSizeAxes = Axes.Y);
AddStep(@"Anchor left", () => expandingBar.Anchor = Anchor.CentreLeft);
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneExpandingBar : OsuTestScene
{
public TestSceneExpandingBar()
{
Container container;
ExpandingBar expandingBar;
Add(container = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Gray,
Alpha = 0.5f,
RelativeSizeAxes = Axes.Both,
},
expandingBar = new ExpandingBar
{
Anchor = Anchor.Centre,
ExpandedSize = 10,
CollapsedSize = 2,
Colour = Color4.DeepSkyBlue,
}
}
});
AddStep(@"Collapse", () => expandingBar.Collapse());
AddStep(@"Uncollapse", () => expandingBar.Expand());
AddSliderStep(@"Resize container", 1, 300, 150, value => container.ResizeTo(value));
AddStep(@"Horizontal", () => expandingBar.RelativeSizeAxes = Axes.X);
AddStep(@"Anchor top", () => expandingBar.Anchor = Anchor.TopCentre);
AddStep(@"Vertical", () => expandingBar.RelativeSizeAxes = Axes.Y);
AddStep(@"Anchor left", () => expandingBar.Anchor = Anchor.CentreLeft);
}
}
}
| mit | C# |
5df44150804f90d763e01648b88b31c833b8b46b | remove debug log | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey/ViewModels/LoginPageViewModel.cs | client/BlueMonkey/BlueMonkey/ViewModels/LoginPageViewModel.cs | using BlueMonkey.LoginService;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace BlueMonkey.ViewModels
{
public class LoginPageViewModel : BindableBase
{
private readonly INavigationService _navigationService;
private readonly ILoginService _loginService;
private readonly IPageDialogService _pageDialogService;
public DelegateCommand LoginCommand { get; }
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set { SetProperty(ref _isBusy, value); }
}
public LoginPageViewModel(INavigationService navigationService, ILoginService loginService, IPageDialogService pageDialogService)
{
_navigationService = navigationService;
_loginService = loginService;
_pageDialogService = pageDialogService;
this.LoginCommand = new DelegateCommand(async () => await LoginAsync(), () => !IsBusy)
.ObservesProperty(() => IsBusy);
}
private async Task LoginAsync()
{
try
{
IsBusy = true;
if (!(await _loginService.LoginAsync()))
{
await _pageDialogService.DisplayAlertAsync(
"Information",
"Login failed.",
"OK");
return;
}
await _navigationService.NavigateAsync("/NavigationPage/MainPage");
}
catch (Exception ex)
{
await _pageDialogService.DisplayAlertAsync(
"Information",
"Login failed.",
"OK");
}
finally
{
IsBusy = false;
}
}
}
}
| using BlueMonkey.LoginService;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace BlueMonkey.ViewModels
{
public class LoginPageViewModel : BindableBase
{
private readonly INavigationService _navigationService;
private readonly ILoginService _loginService;
private readonly IPageDialogService _pageDialogService;
public DelegateCommand LoginCommand { get; }
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set { SetProperty(ref _isBusy, value); }
}
public LoginPageViewModel(INavigationService navigationService, ILoginService loginService, IPageDialogService pageDialogService)
{
_navigationService = navigationService;
_loginService = loginService;
_pageDialogService = pageDialogService;
this.LoginCommand = new DelegateCommand(async () => await LoginAsync(), () => !IsBusy)
.ObservesProperty(() => IsBusy);
}
private async Task LoginAsync()
{
try
{
IsBusy = true;
if (!(await _loginService.LoginAsync()))
{
await _pageDialogService.DisplayAlertAsync(
"Information",
"Login failed.",
"OK");
return;
}
await _navigationService.NavigateAsync("/NavigationPage/MainPage");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
await _pageDialogService.DisplayAlertAsync(
"Information",
"Login failed.",
"OK");
}
finally
{
IsBusy = false;
}
}
}
}
| mit | C# |
0f150576af0f161bec4c04640c2469067430202e | Add creating user to authentication context setup | tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server | src/Tgstation.Server.Host/Security/AuthenticationContextFactory.cs | src/Tgstation.Server.Host/Security/AuthenticationContextFactory.cs | using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host.Models;
namespace Tgstation.Server.Host.Security
{
/// <inheritdoc />
sealed class AuthenticationContextFactory : IAuthenticationContextFactory
{
/// <inheritdoc />
public IAuthenticationContext CurrentAuthenticationContext { get; private set; }
/// <summary>
/// The <see cref="ISystemIdentityFactory"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly ISystemIdentityFactory systemIdentityFactory;
/// <summary>
/// The <see cref="IDatabaseContext"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly IDatabaseContext databaseContext;
/// <summary>
/// The <see cref="IIdentityCache"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly IIdentityCache identityCache;
/// <summary>
/// Construct an <see cref="AuthenticationContextFactory"/>
/// </summary>
/// <param name="systemIdentityFactory">The value of <see cref="systemIdentityFactory"/></param>
/// <param name="databaseContext">The value of <see cref="databaseContext"/></param>
/// <param name="identityCache">The value of <see cref="identityCache"/></param>
public AuthenticationContextFactory(ISystemIdentityFactory systemIdentityFactory, IDatabaseContext databaseContext, IIdentityCache identityCache)
{
this.systemIdentityFactory = systemIdentityFactory ?? throw new ArgumentNullException(nameof(systemIdentityFactory));
this.databaseContext = databaseContext ?? throw new ArgumentNullException(nameof(databaseContext));
this.identityCache = identityCache ?? throw new ArgumentNullException(nameof(identityCache));
}
/// <inheritdoc />
public async Task CreateAuthenticationContext(long userId, long? instanceId, DateTimeOffset validBefore, CancellationToken cancellationToken)
{
if (CurrentAuthenticationContext != null)
throw new InvalidOperationException("Authentication context has already been loaded");
var userQuery = databaseContext.Users.Where(x => x.Id == userId)
.Include(x => x.CreatedBy)
.FirstOrDefaultAsync(cancellationToken);
var instanceUser = instanceId.HasValue ? (await databaseContext.InstanceUsers
.Where(x => x.UserId == userId && x.InstanceId == instanceId && x.Instance.Online.Value)
.Include(x => x.Instance)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false)) : null;
var user = await userQuery.ConfigureAwait(false);
if (user == default)
{
CurrentAuthenticationContext = new AuthenticationContext();
return;
}
ISystemIdentity systemIdentity;
if (user.SystemIdentifier != null)
{
systemIdentity = identityCache.LoadCachedIdentity(user);
if (systemIdentity == null)
throw new InvalidOperationException("Cached system identity has expired!");
}
else
{
if (user.LastPasswordUpdate.HasValue && user.LastPasswordUpdate > validBefore)
{
CurrentAuthenticationContext = new AuthenticationContext();
return;
}
systemIdentity = null;
}
CurrentAuthenticationContext = new AuthenticationContext(systemIdentity, user, instanceUser);
}
}
}
| using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host.Models;
namespace Tgstation.Server.Host.Security
{
/// <inheritdoc />
sealed class AuthenticationContextFactory : IAuthenticationContextFactory
{
/// <inheritdoc />
public IAuthenticationContext CurrentAuthenticationContext { get; private set; }
/// <summary>
/// The <see cref="ISystemIdentityFactory"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly ISystemIdentityFactory systemIdentityFactory;
/// <summary>
/// The <see cref="IDatabaseContext"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly IDatabaseContext databaseContext;
/// <summary>
/// The <see cref="IIdentityCache"/> for the <see cref="AuthenticationContextFactory"/>
/// </summary>
readonly IIdentityCache identityCache;
/// <summary>
/// Construct an <see cref="AuthenticationContextFactory"/>
/// </summary>
/// <param name="systemIdentityFactory">The value of <see cref="systemIdentityFactory"/></param>
/// <param name="databaseContext">The value of <see cref="databaseContext"/></param>
/// <param name="identityCache">The value of <see cref="identityCache"/></param>
public AuthenticationContextFactory(ISystemIdentityFactory systemIdentityFactory, IDatabaseContext databaseContext, IIdentityCache identityCache)
{
this.systemIdentityFactory = systemIdentityFactory ?? throw new ArgumentNullException(nameof(systemIdentityFactory));
this.databaseContext = databaseContext ?? throw new ArgumentNullException(nameof(databaseContext));
this.identityCache = identityCache ?? throw new ArgumentNullException(nameof(identityCache));
}
/// <inheritdoc />
public async Task CreateAuthenticationContext(long userId, long? instanceId, DateTimeOffset validBefore, CancellationToken cancellationToken)
{
if (CurrentAuthenticationContext != null)
throw new InvalidOperationException("Authentication context has already been loaded");
var userQuery = databaseContext.Users.Where(x => x.Id == userId).FirstOrDefaultAsync(cancellationToken);
var instanceUser = instanceId.HasValue ? (await databaseContext.InstanceUsers
.Where(x => x.UserId == userId && x.InstanceId == instanceId && x.Instance.Online.Value)
.Include(x => x.Instance)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false)) : null;
var user = await userQuery.ConfigureAwait(false);
if (user == default)
{
CurrentAuthenticationContext = new AuthenticationContext();
return;
}
ISystemIdentity systemIdentity;
if (user.SystemIdentifier != null)
{
systemIdentity = identityCache.LoadCachedIdentity(user);
if (systemIdentity == null)
throw new InvalidOperationException("Cached system identity has expired!");
}
else
{
if (user.LastPasswordUpdate.HasValue && user.LastPasswordUpdate > validBefore)
{
CurrentAuthenticationContext = new AuthenticationContext();
return;
}
systemIdentity = null;
}
CurrentAuthenticationContext = new AuthenticationContext(systemIdentity, user, instanceUser);
}
}
}
| agpl-3.0 | C# |
85e0f49cdf402cd990ad4797a939ece3d2707cf4 | Fix CompositeListOption not interpreting composite values by default | LouisTakePILLz/ArgumentParser | ArgumentParser/Factory/POSIXCompositeListOptionAttribute.cs | ArgumentParser/Factory/POSIXCompositeListOptionAttribute.cs | //-----------------------------------------------------------------------
// <copyright file="POSIXCompositeListOptionAttribute.cs" company="LouisTakePILLz">
// Copyright © 2015 LouisTakePILLz
// <author>LouisTakePILLz</author>
// </copyright>
//-----------------------------------------------------------------------
/*
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel;
using ArgumentParser.Arguments;
using ArgumentParser.Helpers;
namespace ArgumentParser.Factory
{
/// <summary>
/// Represents a POSIX-flavored option attribute that supports splitting using spaces.
/// </summary>
public class POSIXCompositeListOptionAttribute : POSIXOptionAttribute
{
private static readonly StringArrayConverter typeConverter = new StringArrayConverter('\x20', StringSplitOptions.RemoveEmptyEntries);
/// <summary>
/// Initializes a new instance of the <see cref="T:ArgumentParser.Factory.POSIXCompositeListOptionAttribute"/> class.
/// </summary>
/// <param name="tag">The tag that defines the argument.</param>
public POSIXCompositeListOptionAttribute(String tag) : base(tag)
{
this.ValueOptions = ValueOptions.Composite;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:ArgumentParser.Factory.POSIXCompositeListOptionAttribute"/> class.
/// </summary>
/// <param name="tag">The tag that defines the argument.</param>
public POSIXCompositeListOptionAttribute(Char tag) : base(tag)
{
this.ValueOptions = ValueOptions.Composite;
}
/// <summary>
/// Gets the type converter used for value conversion.
/// </summary>
public override TypeConverter TypeConverter
{
get { return typeConverter; }
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="POSIXCompositeListOptionAttribute.cs" company="LouisTakePILLz">
// Copyright © 2015 LouisTakePILLz
// <author>LouisTakePILLz</author>
// </copyright>
//-----------------------------------------------------------------------
/*
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel;
using ArgumentParser.Helpers;
namespace ArgumentParser.Factory
{
/// <summary>
/// Represents a POSIX-flavored option attribute that supports splitting using spaces.
/// </summary>
public class POSIXCompositeListOptionAttribute : POSIXOptionAttribute
{
private static readonly StringArrayConverter typeConverter = new StringArrayConverter('\x20', StringSplitOptions.RemoveEmptyEntries);
/// <summary>
/// Initializes a new instance of the <see cref="T:ArgumentParser.Factory.POSIXCompositeListOptionAttribute"/> class.
/// </summary>
/// <param name="tag">The tag that defines the argument.</param>
public POSIXCompositeListOptionAttribute(String tag) : base(tag) { }
/// <summary>
/// Initializes a new instance of the <see cref="T:ArgumentParser.Factory.POSIXCompositeListOptionAttribute"/> class.
/// </summary>
/// <param name="tag">The tag that defines the argument.</param>
public POSIXCompositeListOptionAttribute(Char tag) : base(tag) { }
/// <summary>
/// Gets the type converter used for value conversion.
/// </summary>
public override TypeConverter TypeConverter
{
get { return typeConverter; }
}
}
}
| apache-2.0 | C# |
bab454068c8805bc302a375e9ae3a6536493ff50 | Fix formatting on queued sender | mattgwagner/CertiPay.Common | CertiPay.Common.Notifications/Notifications/QueuedSender.cs | CertiPay.Common.Notifications/Notifications/QueuedSender.cs | using CertiPay.Common.Logging;
using CertiPay.Common.WorkQueue;
using System.Threading;
using System.Threading.Tasks;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Sends notifications to the background worker queue for async processing and retries
/// </summary>
public partial class QueuedSender :
INotificationSender<SMSNotification>,
INotificationSender<EmailNotification>
{
private static readonly ILog Log = LogManager.GetLogger<QueuedSender>();
private readonly IQueueManager _queue;
public QueuedSender(IQueueManager queue)
{
this._queue = queue;
}
public async Task SendAsync(EmailNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(EmailNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(EmailNotification.QueueName, notification);
}
}
public async Task SendAsync(SMSNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(SMSNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(SMSNotification.QueueName, notification);
}
}
}
} | using CertiPay.Common.Logging;
using CertiPay.Common.WorkQueue;
using System.Threading;
using System.Threading.Tasks;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Sends notifications to the background worker queue for async processing and retries
/// </summary>
public partial class QueuedSender :
INotificationSender<SMSNotification>,
INotificationSender<EmailNotification>
{
private static readonly ILog Log = LogManager.GetLogger<QueuedSender>();
private readonly IQueueManager _queue;
public QueuedSender(IQueueManager queue)
{
this._queue = queue;
}
public async Task SendAsync(EmailNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(EmailNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(EmailNotification.QueueName, notification);
}
}
public async Task SendAsync(SMSNotification notification)
{
await SendAsync(notification, CancellationToken.None);
}
public async Task SendAsync(SMSNotification notification, CancellationToken token)
{
using (Log.Timer("QueuedSender.SendAsync", context: notification))
{
await _queue.Enqueue(SMSNotification.QueueName, notification);
}
}
}
} | mit | C# |
8e01d04702da978856a94e60b761719bebb7217c | fix null warning in BooleanRequired | leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net | src/JoinRpg.Helpers.Web/BooleanRequired.cs | src/JoinRpg.Helpers.Web/BooleanRequired.cs | using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace JoinRpg.Helpers.Web;
/// <summary>
/// Makes boolean fields required (i.e. checkbox must be checked)
/// </summary>
/// <remarks>
/// Includes [Required] attribute logic, therefore no sense to use both attributes at once
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public class BooleanRequiredAttribute : RequiredAttribute, IClientModelValidator
{
/// <inheritdoc />
public override bool IsValid(object? value)
{
if (value is null)
{
return false;
}
if (value.GetType() != typeof(bool))
{
throw new InvalidOperationException("Can only be used on boolean properties.");
}
return (bool)value;
}
/// <inheritdoc cref="IClientModelValidator.AddValidation"/>
public void AddValidation(ClientModelValidationContext context)
{
ArgumentNullException.ThrowIfNull(context);
MergeAttribute("data-val", "true");
MergeAttribute("data-val-enforcetrue", ErrorMessage);
void MergeAttribute(string key, string? value)
{
if (context.Attributes.ContainsKey(key))
{
return;
}
if (value is null)
{
return;
}
context.Attributes.Add(key, value);
}
}
}
| using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace JoinRpg.Helpers.Web;
/// <summary>
/// Makes boolean fields required (i.e. checkbox must be checked)
/// </summary>
/// <remarks>
/// Includes [Required] attribute logic, therefore no sense to use both attributes at once
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public class BooleanRequiredAttribute : RequiredAttribute, IClientModelValidator
{
/// <inheritdoc />
public override bool IsValid(object? value)
{
if (value is null)
{
return false;
}
if (value.GetType() != typeof(bool))
{
throw new InvalidOperationException("Can only be used on boolean properties.");
}
return (bool)value;
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
/// <inheritdoc cref="IClientModelValidator.AddValidation"/>
public void AddValidation(ClientModelValidationContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
_ = MergeAttribute(context.Attributes, "data-val", "true");
_ = MergeAttribute(context.Attributes, "data-val-enforcetrue", ErrorMessage);
}
}
| mit | C# |
4cbbc024492c45c7501a6ecde05bb158e77d7322 | Change UpdateManager to actually call FixedUpdateMe and LateUpdateMe in their respective functions. | fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Managers/UpdateManager/UpdateManager.cs | UnityProject/Assets/Scripts/Managers/UpdateManager/UpdateManager.cs | using UnityEngine;
using UnityEngine.SceneManagement;
using System;
/// <summary>
/// Handles the update methods for in game objects
/// Handling the updates from a single point decreases cpu time
/// and increases performance
/// </summary>
public class UpdateManager : MonoBehaviour
{
private static UpdateManager updateManager;
private event Action UpdateMe;
private event Action FixedUpdateMe;
private event Action LateUpdateMe;
private event Action UpdateAction;
public static UpdateManager Instance
{
get
{
if (updateManager == null)
{
updateManager = FindObjectOfType<UpdateManager>();
}
return updateManager;
}
}
public void Add(ManagedNetworkBehaviour updatable)
{
UpdateMe += updatable.UpdateMe;
FixedUpdateMe += updatable.FixedUpdateMe;
LateUpdateMe += updatable.LateUpdateMe;
}
public void Add(Action updatable)
{
UpdateAction += updatable;
}
public void Remove(ManagedNetworkBehaviour updatable)
{
UpdateMe -= updatable.UpdateMe;
FixedUpdateMe -= updatable.FixedUpdateMe;
LateUpdateMe -= updatable.LateUpdateMe;
}
public void Remove(Action updatable)
{
UpdateAction -= updatable;
}
private void OnEnable()
{
SceneManager.activeSceneChanged += SceneChanged;
}
private void OnDisable()
{
SceneManager.activeSceneChanged -= SceneChanged;
}
private void SceneChanged(Scene prevScene, Scene newScene)
{
Reset();
}
private void Reset()
{
UpdateMe = null;
FixedUpdateMe = null;
LateUpdateMe = null;
}
private void Update()
{
UpdateMe?.Invoke();
UpdateAction?.Invoke();
}
private void FixedUpdate()
{
FixedUpdateMe?.Invoke();
}
private void LateUpdate()
{
LateUpdateMe?.Invoke();
}
} | using UnityEngine;
using UnityEngine.SceneManagement;
using System;
/// <summary>
/// Handles the update methods for in game objects
/// Handling the updates from a single point decreases cpu time
/// and increases performance
/// </summary>
public class UpdateManager : MonoBehaviour
{
private static UpdateManager updateManager;
private event Action UpdateMe;
private event Action FixedUpdateMe;
private event Action LateUpdateMe;
private event Action UpdateAction;
public static UpdateManager Instance
{
get
{
if (updateManager == null)
{
updateManager = FindObjectOfType<UpdateManager>();
}
return updateManager;
}
}
public void Add(ManagedNetworkBehaviour updatable)
{
UpdateMe += updatable.UpdateMe;
FixedUpdateMe += updatable.FixedUpdateMe;
LateUpdateMe += updatable.LateUpdateMe;
}
public void Add(Action updatable)
{
UpdateAction += updatable;
}
public void Remove(ManagedNetworkBehaviour updatable)
{
UpdateMe -= updatable.UpdateMe;
FixedUpdateMe -= updatable.FixedUpdateMe;
LateUpdateMe -= updatable.LateUpdateMe;
}
public void Remove(Action updatable)
{
UpdateAction -= updatable;
}
private void OnEnable()
{
SceneManager.activeSceneChanged += SceneChanged;
}
private void OnDisable()
{
SceneManager.activeSceneChanged -= SceneChanged;
}
private void SceneChanged(Scene prevScene, Scene newScene)
{
Reset();
}
private void Reset()
{
UpdateMe = null;
FixedUpdateMe = null;
LateUpdateMe = null;
}
private void Update()
{
UpdateMe?.Invoke();
FixedUpdateMe?.Invoke();
LateUpdateMe?.Invoke();
UpdateAction?.Invoke();
}
} | agpl-3.0 | C# |
940fcdab9c1f00777d662d6f914bf9a58aa8b766 | fix #76 | modulexcite/LogSearchShipper,cityindex/LogSearchShipper | src/LogsearchShipper.Core/ConfigWatcher.cs | src/LogsearchShipper.Core/ConfigWatcher.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using log4net;
namespace LogSearchShipper.Core
{
class ConfigWatcher : IDisposable
{
public ConfigWatcher(string fullPath, ILog log)
{
_log = log;
Watcher = new FileSystemWatcher(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath))
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters .LastWrite | NotifyFilters.Size,
};
}
public readonly FileSystemWatcher Watcher;
public void SubscribeConfigFileChanges(Action actionsToRun)
{
Watcher.Changed += (s, e) => OnChanged(actionsToRun, e);
Watcher.EnableRaisingEvents = true;
}
private void OnChanged(Action actionsToRun, FileSystemEventArgs e)
{
try
{
var lastWriteTime = File.GetLastWriteTimeUtc(e.FullPath);
lock (_sync)
{
if (_lastWriteTime == lastWriteTime)
return;
}
_log.InfoFormat("Detected change in file: {0}", e.FullPath);
actionsToRun();
lock (_sync)
{
_lastWriteTime = lastWriteTime;
}
}
catch (Exception exc)
{
_log.Error(exc);
}
}
public void Dispose()
{
Watcher.EnableRaisingEvents = false;
Watcher.Dispose();
}
private DateTime _lastWriteTime;
private readonly ILog _log;
readonly object _sync = new object();
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using log4net;
namespace LogSearchShipper.Core
{
class ConfigWatcher : IDisposable
{
public ConfigWatcher(string fullPath, ILog log)
{
_log = log;
Watcher = new FileSystemWatcher(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath));
Watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;
}
public DateTime LastWriteTime;
public readonly FileSystemWatcher Watcher;
public event Action Changed;
public void SubscribeConfigFileChanges(Action actionsToRun)
{
Watcher.Changed += (s, e) =>
{
try
{
_log.InfoFormat("Detected change in file: {0}", e.FullPath);
actionsToRun();
}
catch (Exception exc)
{
_log.Error(exc);
}
};
Watcher.EnableRaisingEvents = true;
}
public void Dispose()
{
Watcher.EnableRaisingEvents = false;
Watcher.Dispose();
}
private readonly ILog _log;
}
}
| apache-2.0 | C# |
a74a09ac93b11a5274c9e77c17df4a062ab68efe | refactor if to switch | LinqToDB4iSeries/linq2db,MaceWindu/linq2db,linq2db/linq2db,MaceWindu/linq2db,linq2db/linq2db,LinqToDB4iSeries/linq2db | Source/LinqToDB/Expressions/MappingExpressionsExtensions.cs | Source/LinqToDB/Expressions/MappingExpressionsExtensions.cs | using LinqToDB.Common;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace LinqToDB.Extensions
{
static class MappingExpressionsExtensions
{
public static TExpression GetExpressionFromExpressionMember<TExpression>(this Type type, string memberName)
where TExpression : Expression
{
var members = type.GetStaticMembersEx(memberName);
if (members.Length == 0)
throw new LinqToDBException($"Static member '{memberName}' for type '{type.Name}' not found");
if (members.Length > 1)
throw new LinqToDBException($"Ambiguous members '{memberName}' for type '{type.Name}' has been found");
switch (members[0])
{
case PropertyInfo propInfo:
{
var value = propInfo.GetValue(null, null);
if (value == null)
return null;
if (value is TExpression expression)
return expression;
throw new LinqToDBException($"Property '{memberName}' for type '{type.Name}' should return expression");
}
case MethodInfo method:
{
if (method.GetParameters().Length > 0)
throw new LinqToDBException($"Method '{memberName}' for type '{type.Name}' should have no parameters");
var value = method.Invoke(null, Array<object>.Empty);
if (value == null)
return null;
if (value is TExpression expression)
return expression;
throw new LinqToDBException($"Method '{memberName}' for type '{type.Name}' should return expression");
}
default:
throw new LinqToDBException(
$"Member '{memberName}' for type '{type.Name}' should be static property or method");
}
}
}
}
| using LinqToDB.Common;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace LinqToDB.Extensions
{
static class MappingExpressionsExtensions
{
public static TExpression GetExpressionFromExpressionMember<TExpression>(this Type type, string memberName)
where TExpression : Expression
{
var members = type.GetStaticMembersEx(memberName);
if (members.Length == 0)
throw new LinqToDBException($"Static member '{memberName}' for type '{type.Name}' not found");
if (members.Length > 1)
throw new LinqToDBException($"Ambiguous members '{memberName}' for type '{type.Name}' has been found");
if (members[0] is PropertyInfo propInfo)
{
var value = propInfo.GetValue(null, null);
if (value == null)
return null;
if (value is TExpression expression)
return expression;
throw new LinqToDBException($"Property '{memberName}' for type '{type.Name}' should return expression");
}
else
{
if (members[0] is MethodInfo method)
{
if (method.GetParameters().Length > 0)
throw new LinqToDBException($"Method '{memberName}' for type '{type.Name}' should have no parameters");
var value = method.Invoke(null, Array<object>.Empty);
if (value == null)
return null;
if (value is TExpression expression)
return expression;
throw new LinqToDBException($"Method '{memberName}' for type '{type.Name}' should return expression");
}
}
throw new LinqToDBException(
$"Member '{memberName}' for type '{type.Name}' should be static property or method");
}
}
}
| mit | C# |
072fbe5f6648a77584804f93f91ff01285c5075e | Rename Control_DragAndDrop_UsingDragAndDropUsingScriptBehavior test to Control_DragAndDrop_UsingDomEvents | YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata | src/Atata.Tests/ControlTests.cs | src/Atata.Tests/ControlTests.cs | using NUnit.Framework;
namespace Atata.Tests
{
public class ControlTests : UITestFixture
{
[Test]
public void Control_DragAndDrop_UsingDomEvents()
{
Go.To<DragAndDropPage>().
DropContainer.Items.Should.BeEmpty().
DragItems.Items.Should.HaveCount(2).
DragItems[x => x.Content == "Drag item 1"].DragAndDropTo(x => x.DropContainer).
DragItems[0].DragAndDropTo(x => x.DropContainer).
DropContainer.Items.Should.HaveCount(2).
DragItems.Items.Should.BeEmpty().
DropContainer[1].Content.Should.Equal("Drag item 2");
}
}
}
| using NUnit.Framework;
namespace Atata.Tests
{
public class ControlTests : UITestFixture
{
[Test]
public void Control_DragAndDrop_UsingDragAndDropUsingScriptBehavior()
{
Go.To<DragAndDropPage>().
DropContainer.Items.Should.BeEmpty().
DragItems.Items.Should.HaveCount(2).
DragItems[x => x.Content == "Drag item 1"].DragAndDropTo(x => x.DropContainer).
DragItems[0].DragAndDropTo(x => x.DropContainer).
DropContainer.Items.Should.HaveCount(2).
DragItems.Items.Should.BeEmpty().
DropContainer[1].Content.Should.Equal("Drag item 2");
}
}
}
| apache-2.0 | C# |
9c0a797a773f602ceefddb37c808ed62d31f5c8d | Use the new API | spaccabit/fluentmigrator,eloekset/fluentmigrator,igitur/fluentmigrator,amroel/fluentmigrator,amroel/fluentmigrator,fluentmigrator/fluentmigrator,stsrki/fluentmigrator,schambers/fluentmigrator,spaccabit/fluentmigrator,eloekset/fluentmigrator,stsrki/fluentmigrator,fluentmigrator/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator | samples/FluentMigrator.Example.Migrator/Program.DependencyInjection.cs | samples/FluentMigrator.Example.Migrator/Program.DependencyInjection.cs | #region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using FluentMigrator.Example.Migrations;
using FluentMigrator.Runner;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FluentMigrator.Example.Migrator
{
internal static partial class Program
{
private static void RunWithServices(string connectionString)
{
// Initialize the services
var serviceProvider = new ServiceCollection()
.AddLogging(lb => lb.AddDebug().AddFluentMigratorConsole())
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
.AddSQLite()
.WithGlobalConnectionString(connectionString)
.ScanIn(typeof(AddGTDTables).Assembly).For.Migrations())
.BuildServiceProvider();
// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();
// Run the migrations
runner.MigrateUp();
}
}
}
| #region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using FluentMigrator.Example.Migrations;
using FluentMigrator.Runner;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FluentMigrator.Example.Migrator
{
internal static partial class Program
{
private static void RunWithServices(string connectionString)
{
// Initialize the services
var serviceProvider = new ServiceCollection()
.AddLogging(lb => lb.AddDebug().AddFluentMigratorConsole())
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
.AddSQLite()
.WithGlobalConnectionString(connectionString)
.WithMigrationsIn(typeof(AddGTDTables).Assembly))
.BuildServiceProvider();
// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();
// Run the migrations
runner.MigrateUp();
}
}
}
| apache-2.0 | C# |
a492810715bfac6200ca526ada9e241977de9575 | Refactor Divide Integers Operation to use GetValujes and CloneWithValues | ajlopez/TensorSharp | Src/TensorSharp/Operations/DivideIntegerIntegerOperation.cs | Src/TensorSharp/Operations/DivideIntegerIntegerOperation.cs | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
int[] values1 = tensor1.GetValues();
int l = values1.Length;
int value2 = tensor2.GetValue();
int[] newvalues = new int[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] / value2;
return tensor1.CloneWithNewValues(newvalues);
}
}
}
| namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
Tensor<int> result = new Tensor<int>();
result.SetValue(tensor1.GetValue() / tensor2.GetValue());
return result;
}
}
}
| mit | C# |
93bb56cd577d9586748a8f9ccb095f4a940d62ec | add hbs file extension registration, its (possibly) the most common handlebars file extension | csainty/Veil,csainty/Veil | Src/Veil.Handlebars/HandlebarsTemplateParserRegistration.cs | Src/Veil.Handlebars/HandlebarsTemplateParserRegistration.cs | using System;
using System.Collections.Generic;
using Veil.Parser;
namespace Veil.Handlebars
{
/// <summary>
/// Used to auto-register this parser. You should not need touch it.
/// </summary>
public class HandlebarsTemplateParserRegistration : ITemplateParserRegistration
{
public IEnumerable<string> Keys
{
get { return new[] { "haml", "handlebars", "hbs" }; }
}
public Func<ITemplateParser> ParserFactory
{
get { return () => new HandlebarsParser(); }
}
}
} | using System;
using System.Collections.Generic;
using Veil.Parser;
namespace Veil.Handlebars
{
/// <summary>
/// Used to auto-register this parser. You should not need touch it.
/// </summary>
public class HandlebarsTemplateParserRegistration : ITemplateParserRegistration
{
public IEnumerable<string> Keys
{
get { return new[] { "haml", "handlebars" }; }
}
public Func<ITemplateParser> ParserFactory
{
get { return () => new HandlebarsParser(); }
}
}
} | mit | C# |
5ded548e809b60fff53bd7f8d6e2848b97b45bc0 | Make NextHopIpAddress an optional parameter. | AzureRT/azure-powershell,SarahRogers/azure-powershell,zhencui/azure-powershell,enavro/azure-powershell,rohmano/azure-powershell,jasper-schneider/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,hovsepm/azure-powershell,PashaPash/azure-powershell,krkhan/azure-powershell,AzureRT/azure-powershell,nickheppleston/azure-powershell,AzureRT/azure-powershell,jianghaolu/azure-powershell,haocs/azure-powershell,TaraMeyer/azure-powershell,pankajsn/azure-powershell,rhencke/azure-powershell,ClogenyTechnologies/azure-powershell,stankovski/azure-powershell,yoavrubin/azure-powershell,praveennet/azure-powershell,seanbamsft/azure-powershell,dominiqa/azure-powershell,dominiqa/azure-powershell,dulems/azure-powershell,yantang-msft/azure-powershell,pelagos/azure-powershell,hungmai-msft/azure-powershell,alfantp/azure-powershell,TaraMeyer/azure-powershell,yadavbdev/azure-powershell,arcadiahlyy/azure-powershell,seanbamsft/azure-powershell,yadavbdev/azure-powershell,atpham256/azure-powershell,shuagarw/azure-powershell,arcadiahlyy/azure-powershell,zhencui/azure-powershell,nickheppleston/azure-powershell,CamSoper/azure-powershell,pelagos/azure-powershell,nemanja88/azure-powershell,oaastest/azure-powershell,SarahRogers/azure-powershell,haocs/azure-powershell,AzureAutomationTeam/azure-powershell,praveennet/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,bgold09/azure-powershell,dulems/azure-powershell,ailn/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,AzureRT/azure-powershell,akurmi/azure-powershell,PashaPash/azure-powershell,TaraMeyer/azure-powershell,ailn/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,yadavbdev/azure-powershell,yoavrubin/azure-powershell,ClogenyTechnologies/azure-powershell,hallihan/azure-powershell,PashaPash/azure-powershell,hovsepm/azure-powershell,akurmi/azure-powershell,DeepakRajendranMsft/azure-powershell,PashaPash/azure-powershell,AzureAutomationTeam/azure-powershell,stankovski/azure-powershell,ankurchoubeymsft/azure-powershell,hallihan/azure-powershell,AzureRT/azure-powershell,CamSoper/azure-powershell,jianghaolu/azure-powershell,akurmi/azure-powershell,dulems/azure-powershell,yantang-msft/azure-powershell,pelagos/azure-powershell,rhencke/azure-powershell,rohmano/azure-powershell,jianghaolu/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,enavro/azure-powershell,pelagos/azure-powershell,SarahRogers/azure-powershell,rohmano/azure-powershell,zhencui/azure-powershell,alfantp/azure-powershell,kagamsft/azure-powershell,Matt-Westphal/azure-powershell,tonytang-microsoft-com/azure-powershell,praveennet/azure-powershell,ailn/azure-powershell,yoavrubin/azure-powershell,chef-partners/azure-powershell,SarahRogers/azure-powershell,bgold09/azure-powershell,ankurchoubeymsft/azure-powershell,Matt-Westphal/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,devigned/azure-powershell,akurmi/azure-powershell,oaastest/azure-powershell,juvchan/azure-powershell,pankajsn/azure-powershell,ClogenyTechnologies/azure-powershell,yantang-msft/azure-powershell,rhencke/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,nemanja88/azure-powershell,mayurid/azure-powershell,ankurchoubeymsft/azure-powershell,krkhan/azure-powershell,ailn/azure-powershell,jtlibing/azure-powershell,Matt-Westphal/azure-powershell,akurmi/azure-powershell,jtlibing/azure-powershell,Matt-Westphal/azure-powershell,hungmai-msft/azure-powershell,rohmano/azure-powershell,kagamsft/azure-powershell,SarahRogers/azure-powershell,arcadiahlyy/azure-powershell,chef-partners/azure-powershell,ailn/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,haocs/azure-powershell,nickheppleston/azure-powershell,arcadiahlyy/azure-powershell,haocs/azure-powershell,zhencui/azure-powershell,kagamsft/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,chef-partners/azure-powershell,bgold09/azure-powershell,mayurid/azure-powershell,tonytang-microsoft-com/azure-powershell,seanbamsft/azure-powershell,PashaPash/azure-powershell,alfantp/azure-powershell,jtlibing/azure-powershell,praveennet/azure-powershell,DeepakRajendranMsft/azure-powershell,DeepakRajendranMsft/azure-powershell,yadavbdev/azure-powershell,mayurid/azure-powershell,enavro/azure-powershell,pomortaz/azure-powershell,dominiqa/azure-powershell,zaevans/azure-powershell,TaraMeyer/azure-powershell,krkhan/azure-powershell,Matt-Westphal/azure-powershell,alfantp/azure-powershell,chef-partners/azure-powershell,nemanja88/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,pomortaz/azure-powershell,hallihan/azure-powershell,oaastest/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,nickheppleston/azure-powershell,zaevans/azure-powershell,dominiqa/azure-powershell,rhencke/azure-powershell,chef-partners/azure-powershell,jianghaolu/azure-powershell,ClogenyTechnologies/azure-powershell,DeepakRajendranMsft/azure-powershell,stankovski/azure-powershell,tonytang-microsoft-com/azure-powershell,zaevans/azure-powershell,naveedaz/azure-powershell,juvchan/azure-powershell,hovsepm/azure-powershell,dulems/azure-powershell,CamSoper/azure-powershell,ankurchoubeymsft/azure-powershell,jasper-schneider/azure-powershell,enavro/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,jasper-schneider/azure-powershell,yadavbdev/azure-powershell,yoavrubin/azure-powershell,rhencke/azure-powershell,seanbamsft/azure-powershell,zaevans/azure-powershell,pomortaz/azure-powershell,juvchan/azure-powershell,stankovski/azure-powershell,ClogenyTechnologies/azure-powershell,nickheppleston/azure-powershell,kagamsft/azure-powershell,haocs/azure-powershell,stankovski/azure-powershell,shuagarw/azure-powershell,devigned/azure-powershell,bgold09/azure-powershell,shuagarw/azure-powershell,pomortaz/azure-powershell,oaastest/azure-powershell,naveedaz/azure-powershell,arcadiahlyy/azure-powershell,enavro/azure-powershell,pankajsn/azure-powershell,naveedaz/azure-powershell,CamSoper/azure-powershell,pankajsn/azure-powershell,AzureAutomationTeam/azure-powershell,tonytang-microsoft-com/azure-powershell,jtlibing/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,juvchan/azure-powershell,jasper-schneider/azure-powershell,tonytang-microsoft-com/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,pomortaz/azure-powershell,oaastest/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,mayurid/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,pankajsn/azure-powershell,hungmai-msft/azure-powershell,jasper-schneider/azure-powershell,krkhan/azure-powershell,hovsepm/azure-powershell,DeepakRajendranMsft/azure-powershell,hallihan/azure-powershell,CamSoper/azure-powershell,shuagarw/azure-powershell,pelagos/azure-powershell,bgold09/azure-powershell,dulems/azure-powershell,zhencui/azure-powershell,shuagarw/azure-powershell,dominiqa/azure-powershell,TaraMeyer/azure-powershell,seanbamsft/azure-powershell,juvchan/azure-powershell,hallihan/azure-powershell,jtlibing/azure-powershell,jianghaolu/azure-powershell,yantang-msft/azure-powershell,mayurid/azure-powershell,kagamsft/azure-powershell,hovsepm/azure-powershell,zaevans/azure-powershell,praveennet/azure-powershell | src/ServiceManagement/Network/Commands.Network/Routes/SetAzureRoute.cs | src/ServiceManagement/Network/Commands.Network/Routes/SetAzureRoute.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Network.Gateway
{
using System.Management.Automation;
using WindowsAzure.Commands.Utilities.Common;
[Cmdlet(VerbsCommon.Set, "AzureRoute"), OutputType(typeof(ManagementOperationContext))]
public class SetAzureRoute : NetworkCmdletBase
{
[Parameter(Position = 0, Mandatory = true, HelpMessage = "The existing route table's name.")]
public string RouteTableName { get; set; }
[Parameter(Position = 1, Mandatory = true, HelpMessage = "The new route's name.")]
public string RouteName { get; set; }
[Parameter(Position = 2, Mandatory = true, HelpMessage = "The new route's address prefix (such as \"0.0.0.0/0\").")]
public string AddressPrefix { get; set; }
[Parameter(Position = 3, Mandatory = true, HelpMessage = "The new route's next hop type. Valid values are \"VPNGateway\".")]
public string NextHopType { get; set; }
[Parameter(Position = 4, Mandatory = false, HelpMessage = "The new route's next hop ip address." +
" This parameter can only be specifide for \"VirtualAppliance\" next hops.")]
public string NextHopIpAddress { get; set; }
public override void ExecuteCmdlet()
{
WriteObject(Client.SetRoute(RouteTableName, RouteName, AddressPrefix, NextHopType, NextHopIpAddress));
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Network.Gateway
{
using System.Management.Automation;
using WindowsAzure.Commands.Utilities.Common;
[Cmdlet(VerbsCommon.Set, "AzureRoute"), OutputType(typeof(ManagementOperationContext))]
public class SetAzureRoute : NetworkCmdletBase
{
[Parameter(Position = 0, Mandatory = true, HelpMessage = "The existing route table's name.")]
public string RouteTableName { get; set; }
[Parameter(Position = 1, Mandatory = true, HelpMessage = "The new route's name.")]
public string RouteName { get; set; }
[Parameter(Position = 2, Mandatory = true, HelpMessage = "The new route's address prefix (such as \"0.0.0.0/0\").")]
public string AddressPrefix { get; set; }
[Parameter(Position = 3, Mandatory = true, HelpMessage = "The new route's next hop type. Valid values are \"VPNGateway\".")]
public string NextHopType { get; set; }
[Parameter(Position = 4, Mandatory = true, HelpMessage = "The new route's next hop ip address." +
" This parameter can only be specifide for \"VirtualAppliance\" next hops.")]
public string NextHopIpAddress { get; set; }
public override void ExecuteCmdlet()
{
WriteObject(Client.SetRoute(RouteTableName, RouteName, AddressPrefix, NextHopType, NextHopIpAddress));
}
}
}
| apache-2.0 | C# |
2fc5004623e90dca345ccede6b57f3fd0afe60ae | Set max connections per server to 1024 by default. | MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore | Modules/AppBrix.Web.Client/Configuration/WebClientConfig.cs | Modules/AppBrix.Web.Client/Configuration/WebClientConfig.cs | // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using System;
using System.Linq;
using System.Threading;
namespace AppBrix.Web.Client.Configuration
{
public sealed class WebClientConfig : IConfig
{
#region Construction
/// <summary>
/// Creates a new instance of <see cref="WebClientConfig"/> with default values for the properties.
/// </summary>
public WebClientConfig()
{
this.MaxConnectionsPerServer = 1024;
this.RequestTimeout = Timeout.InfiniteTimeSpan;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public int MaxConnectionsPerServer { get; set; }
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public TimeSpan RequestTimeout { get; set; }
#endregion
}
}
| // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Configuration;
using System;
using System.Linq;
using System.Threading;
namespace AppBrix.Web.Client.Configuration
{
public sealed class WebClientConfig : IConfig
{
#region Construction
/// <summary>
/// Creates a new instance of <see cref="WebClientConfig"/> with default values for the properties.
/// </summary>
public WebClientConfig()
{
this.MaxConnectionsPerServer = 128;
this.RequestTimeout = Timeout.InfiniteTimeSpan;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public int MaxConnectionsPerServer { get; set; }
/// <summary>
/// Gets or sets the timeout used when making HTTP requests.
/// </summary>
public TimeSpan RequestTimeout { get; set; }
#endregion
}
}
| mit | C# |
b3510ed5816211c5cff964b70f4f3682e0fed2a6 | Fix (revert) the text in the information bar when the fleet is repairing. | yuyuvn/KanColleViewer,bllue78/KanColleViewer,SquallATF/KanColleViewer,the-best-flash/KanColleViewer,hazytint/KanColleViewer,twinkfrag/KanColleViewer,Cosmius/KanColleViewer,Yuubari/KanColleViewer,Grabacr07/KanColleViewer,KCV-Localisation/KanColleViewer,heartfelt-fancy/KanColleViewer,soap-DEIM/KanColleViewer,Astrologers/KanColleViewer,ShunKun/KanColleViewer,Zharay/KanColleViewer,kbinani/KanColleViewer,GreenDamTan/KanColleViewer,GIGAFortress/KanColleViewer,nagatoyk/KanColleViewer,fin-alice/KanColleViewer,balderm/KanColleViewer,kookxiang/KanColleViewer,ss840429/KanColleViewer,Yuubari/LegacyKCV,BossaGroove/KanColleViewer,about518/KanColleViewer,gakada/KanColleViewer,risingkav/KanColleViewer,gakada/KanColleViewer,lcxit/KanColleViewer,maron8676/KanColleViewer,KatoriKai/KanColleViewer,AnnaKutou/KanColleViewer,stu43005/KanColleViewer,gakada/KanColleViewer,kyoryo/test | Grabacr07.KanColleViewer/ViewModels/Fleets/RepairingBarViewModel.cs | Grabacr07.KanColleViewer/ViewModels/Fleets/RepairingBarViewModel.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Text;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper;
using Grabacr07.KanColleWrapper.Models;
using Livet;
using Livet.EventListeners;
namespace Grabacr07.KanColleViewer.ViewModels.Fleets
{
public class RepairingBarViewModel : TimerViewModel
{
private readonly Fleet source;
public RepairingBarViewModel(Fleet fleet)
{
this.source = fleet;
}
protected override string CreateMessage()
{
var dock = source.Ships
.Join(KanColleClient.Current.Homeport.Repairyard.Docks.Values.Where(d => d.Ship != null), s => s.Id, d => d.Ship.Id, (s, d) => d)
.OrderByDescending(d => d.CompleteTime)
.FirstOrDefault();
if (dock == null)
{
return "艦隊に入渠中の艦娘がいます。";
}
var remaining = dock.CompleteTime.Value - DateTimeOffset.Now - TimeSpan.FromMinutes(1.0);
return string.Format(@"艦隊に入渠中の艦娘がいます。 完了時刻: {0:MM/dd HH\:mm} 完了まで: {1}:{2:mm\:ss}",
dock.CompleteTime.Value, (int) remaining.TotalHours, remaining);
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Text;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper;
using Grabacr07.KanColleWrapper.Models;
using Livet;
using Livet.EventListeners;
namespace Grabacr07.KanColleViewer.ViewModels.Fleets
{
public class RepairingBarViewModel : TimerViewModel
{
private readonly Fleet source;
public RepairingBarViewModel(Fleet fleet)
{
this.source = fleet;
}
protected override string CreateMessage()
{
var dock = source.Ships
.Join(KanColleClient.Current.Homeport.Repairyard.Docks.Values.Where(d => d.Ship != null), s => s.Id, d => d.Ship.Id, (s, d) => d)
.OrderByDescending(d => d.CompleteTime)
.FirstOrDefault();
if (dock == null)
{
return "この艦隊は整備中です。";
}
var remaining = dock.CompleteTime.Value - DateTimeOffset.Now - TimeSpan.FromMinutes(1.0);
return string.Format(@"この艦隊は整備中です。 完了時刻: {0:MM/dd HH\:mm} 完了まで: {1}:{2:mm\:ss}",
dock.CompleteTime.Value, (int) remaining.TotalHours, remaining);
}
}
}
| mit | C# |
0afee301e6210aef6d3c261ab93c3c77d1b125e5 | Update ModModeEvent.cs | Yonom/BotBits | BotBits/Packages/MessageHandler/Events/ModModeEvent.cs | BotBits/Packages/MessageHandler/Events/ModModeEvent.cs | using PlayerIOClient;
namespace BotBits.Events
{
/// <summary>
/// Occurs when moderator toggles moderator mode.
/// </summary>
/// <seealso cref="PlayerEvent{T}" />
[ReceiveEvent("mod")]
public sealed class ModModeEvent : PlayerEvent<ModModeEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModModeEvent" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="client"></param>
internal ModModeEvent(BotBitsClient client, Message message)
: base(client, message)
{
this.ModMode = message.GetBoolean(1);
}
/// <summary>
/// Gets or sets a value indicating whether moderator is in moderator mode.
/// </summary>
/// <value><c>true</c> if mod; otherwise, <c>false</c>.</value>
public bool ModMode { get; set; }
}
}
| using PlayerIOClient;
namespace BotBits.Events
{
/// <summary>
/// Occurs when moderator toggles moderator mode.
/// </summary>
/// <seealso cref="PlayerEvent{T}" />
[ReceiveEvent("mod")]
public sealed class ModModeEvent : PlayerEvent<ModModeEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="ModModeEvent" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="client"></param>
internal ModModeEvent(BotBitsClient client, Message message)
: base(client, message)
{
this.ModMode = message.GetBoolean(1);
this.StaffAura = (StaffAura)message.GetInt(2);
}
public StaffAura StaffAura { get; set; }
/// <summary>
/// Gets or sets a value indicating whether moderator is in moderator mode.
/// </summary>
/// <value><c>true</c> if mod; otherwise, <c>false</c>.</value>
public bool ModMode { get; set; }
}
} | mit | C# |
9bbd281837e664696f366490e5e850c9e9cf9d63 | fix XmlCommentsSchemaFilter not unescape | domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore | src/Swashbuckle.AspNetCore.SwaggerGen/XmlComments/XmlCommentsSchemaFilter.cs | src/Swashbuckle.AspNetCore.SwaggerGen/XmlComments/XmlCommentsSchemaFilter.cs | using System;
using System.Xml.XPath;
using Microsoft.OpenApi.Models;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class XmlCommentsSchemaFilter : ISchemaFilter
{
private readonly XPathNavigator _xmlNavigator;
public XmlCommentsSchemaFilter(XPathDocument xmlDoc)
{
_xmlNavigator = xmlDoc.CreateNavigator();
}
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
ApplyTypeTags(schema, context.Type);
if (context.MemberInfo != null)
{
ApplyMemberTags(schema, context);
}
}
private void ApplyTypeTags(OpenApiSchema schema, Type type)
{
var typeMemberName = XmlCommentsNodeNameHelper.GetMemberNameForType(type);
var typeSummaryNode = _xmlNavigator.SelectSingleNode($"/doc/members/member[@name='{typeMemberName}']/summary");
if (typeSummaryNode != null)
{
schema.Description = XmlCommentsTextHelper.Humanize(typeSummaryNode.InnerXml);
}
}
private void ApplyMemberTags(OpenApiSchema schema, SchemaFilterContext context)
{
var fieldOrPropertyMemberName = XmlCommentsNodeNameHelper.GetMemberNameForFieldOrProperty(context.MemberInfo);
var fieldOrPropertyNode = _xmlNavigator.SelectSingleNode($"/doc/members/member[@name='{fieldOrPropertyMemberName}']");
if (fieldOrPropertyNode == null) return;
var summaryNode = fieldOrPropertyNode.SelectSingleNode("summary");
if (summaryNode != null)
schema.Description = XmlCommentsTextHelper.Humanize(summaryNode.InnerXml);
var exampleNode = fieldOrPropertyNode.SelectSingleNode("example");
if (exampleNode != null)
{
var exampleAsJson = (schema.ResolveType(context.SchemaRepository) == "string") && !exampleNode.Value.Equals("null")
? $"\"{exampleNode.ToString()}\""
: exampleNode.ToString();
schema.Example = OpenApiAnyFactory.CreateFromJson(exampleAsJson);
}
}
}
}
| using System;
using System.Xml.XPath;
using Microsoft.OpenApi.Models;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class XmlCommentsSchemaFilter : ISchemaFilter
{
private readonly XPathNavigator _xmlNavigator;
public XmlCommentsSchemaFilter(XPathDocument xmlDoc)
{
_xmlNavigator = xmlDoc.CreateNavigator();
}
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
ApplyTypeTags(schema, context.Type);
if (context.MemberInfo != null)
{
ApplyMemberTags(schema, context);
}
}
private void ApplyTypeTags(OpenApiSchema schema, Type type)
{
var typeMemberName = XmlCommentsNodeNameHelper.GetMemberNameForType(type);
var typeSummaryNode = _xmlNavigator.SelectSingleNode($"/doc/members/member[@name='{typeMemberName}']/summary");
if (typeSummaryNode != null)
{
schema.Description = XmlCommentsTextHelper.Humanize(typeSummaryNode.InnerXml);
}
}
private void ApplyMemberTags(OpenApiSchema schema, SchemaFilterContext context)
{
var fieldOrPropertyMemberName = XmlCommentsNodeNameHelper.GetMemberNameForFieldOrProperty(context.MemberInfo);
var fieldOrPropertyNode = _xmlNavigator.SelectSingleNode($"/doc/members/member[@name='{fieldOrPropertyMemberName}']");
if (fieldOrPropertyNode == null) return;
var summaryNode = fieldOrPropertyNode.SelectSingleNode("summary");
if (summaryNode != null)
schema.Description = XmlCommentsTextHelper.Humanize(summaryNode.InnerXml);
var exampleNode = fieldOrPropertyNode.SelectSingleNode("example");
if (exampleNode != null)
{
var exampleAsJson = (schema.ResolveType(context.SchemaRepository) == "string") && !exampleNode.Value.Equals("null")
? $"\"{exampleNode.InnerXml}\""
: exampleNode.InnerXml;
schema.Example = OpenApiAnyFactory.CreateFromJson(exampleAsJson);
}
}
}
}
| mit | C# |
951bf300064bd6d4ef1699ec390daecae38ecc68 | Update DoubleFetchHandler.cs | ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell | src/StackAdmin/Dns/Commands.Dns/Models/DoubleFetchHandler.cs | src/StackAdmin/Dns/Commands.Dns/Models/DoubleFetchHandler.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Commands.Dns.Models
{
public class DoubleFetchHandler : DelegatingHandler, ICloneable
{
public object Clone() {
return new DoubleFetchHandler();
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(response =>
{
var result = response.Result;
if (result.Headers.Contains("Location") && result.Headers.Contains("Azure-AsyncOperation"))
{
result.Headers.Remove("Location");
}
return result;
});
}
}
}
| using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Commands.Dns.Models
{
public class DoubleFetchHandler : DelegatingHandler, ICloneable
{
public object Clone() {
return new DoubleFetchHandler();
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(response =>
{
var result = response.Result;
if (result.Headers.Contains("Location") && result.Headers.Contains("Azure-AsyncOperation"))
{
result.Headers.Remove("Location");
}
return result;
});
}
}
}
| apache-2.0 | C# |
13a708779ff853381364cdc35accd117f02216df | test for all issues being returned | nsrnnnnn/octokit.net,devkhan/octokit.net,chunkychode/octokit.net,octokit-net-test/octokit.net,adamralph/octokit.net,gdziadkiewicz/octokit.net,mminns/octokit.net,geek0r/octokit.net,brramos/octokit.net,takumikub/octokit.net,devkhan/octokit.net,alfhenrik/octokit.net,fake-organization/octokit.net,eriawan/octokit.net,mminns/octokit.net,shana/octokit.net,editor-tools/octokit.net,SamTheDev/octokit.net,hitesh97/octokit.net,nsnnnnrn/octokit.net,ivandrofly/octokit.net,shiftkey/octokit.net,shiftkey-tester/octokit.net,magoswiat/octokit.net,dampir/octokit.net,SamTheDev/octokit.net,daukantas/octokit.net,Sarmad93/octokit.net,dlsteuer/octokit.net,michaKFromParis/octokit.net,chunkychode/octokit.net,forki/octokit.net,rlugojr/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,Sarmad93/octokit.net,octokit/octokit.net,thedillonb/octokit.net,kdolan/octokit.net,alfhenrik/octokit.net,TattsGroup/octokit.net,ChrisMissal/octokit.net,cH40z-Lord/octokit.net,rlugojr/octokit.net,naveensrinivasan/octokit.net,shana/octokit.net,thedillonb/octokit.net,khellang/octokit.net,fffej/octokit.net,editor-tools/octokit.net,kolbasov/octokit.net,octokit/octokit.net,shiftkey-tester/octokit.net,bslliw/octokit.net,octokit-net-test-org/octokit.net,Red-Folder/octokit.net,SmithAndr/octokit.net,eriawan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey/octokit.net,hahmed/octokit.net,SLdragon1989/octokit.net,TattsGroup/octokit.net,M-Zuber/octokit.net,hahmed/octokit.net,ivandrofly/octokit.net,octokit-net-test-org/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,darrelmiller/octokit.net,gabrielweyer/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,gabrielweyer/octokit.net | Octokit.Tests.Integration/Clients/SearchClientTests.cs | Octokit.Tests.Integration/Clients/SearchClientTests.cs | using System.Linq;
using System.Threading.Tasks;
using Octokit;
using Octokit.Tests.Integration;
using Xunit;
public class SearchClientTests
{
readonly IGitHubClient _gitHubClient;
public SearchClientTests()
{
_gitHubClient = new GitHubClient(new ProductHeaderValue("OctokitTests"))
{
Credentials = Helper.Credentials
};
}
[Fact]
public async Task SearchForCSharpRepositories()
{
var request = new SearchRepositoriesRequest("csharp");
var repos = await _gitHubClient.Search.SearchRepo(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForGitHub()
{
var request = new SearchUsersRequest("github");
var repos = await _gitHubClient.Search.SearchUsers(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForFunctionInCode()
{
var request = new SearchCodeRequest("addClass");
request.Repo = "jquery/jquery";
var repos = await _gitHubClient.Search.SearchCode(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForWordInCode()
{
var request = new SearchIssuesRequest("windows");
request.SortField = IssueSearchSort.Created;
request.Order = SortDirection.Descending;
var repos = await _gitHubClient.Search.SearchIssues(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForOpenIssues()
{
var request = new SearchIssuesRequest("phone");
request.Repo = "caliburn-micro/caliburn.micro";
request.State = ItemState.Open;
var issues = await _gitHubClient.Search.SearchIssues(request);
Assert.NotEmpty(issues.Items);
}
[Fact]
public async Task SearchForAllIssues()
{
var request = new SearchIssuesRequest("phone");
request.Repo = "caliburn-micro/caliburn.micro";
var issues = await _gitHubClient.Search.SearchIssues(request);
var closedIssues = issues.Items.Where(x => x.State == ItemState.Closed);
var openedIssues = issues.Items.Where(x => x.State == ItemState.Open);
Assert.NotEmpty(closedIssues);
Assert.NotEmpty(openedIssues);
}
}
| using System.Threading.Tasks;
using Octokit;
using Octokit.Tests.Integration;
using Xunit;
public class SearchClientTests
{
readonly IGitHubClient _gitHubClient;
public SearchClientTests()
{
_gitHubClient = new GitHubClient(new ProductHeaderValue("OctokitTests"))
{
Credentials = Helper.Credentials
};
}
[Fact]
public async Task SearchForCSharpRepositories()
{
var request = new SearchRepositoriesRequest("csharp");
var repos = await _gitHubClient.Search.SearchRepo(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForGitHub()
{
var request = new SearchUsersRequest("github");
var repos = await _gitHubClient.Search.SearchUsers(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForFunctionInCode()
{
var request = new SearchCodeRequest("addClass");
request.Repo = "jquery/jquery";
var repos = await _gitHubClient.Search.SearchCode(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForWordInCode()
{
var request = new SearchIssuesRequest("windows");
request.SortField = IssueSearchSort.Created;
request.Order = SortDirection.Descending;
var repos = await _gitHubClient.Search.SearchIssues(request);
Assert.NotEmpty(repos.Items);
}
[Fact]
public async Task SearchForOpenIssues()
{
var request = new SearchIssuesRequest("phone");
request.Repo = "caliburn-micro/caliburn.micro";
request.State = ItemState.Open;
var issues = await _gitHubClient.Search.SearchIssues(request);
Assert.NotEmpty(issues.Items);
}
}
| mit | C# |
14bb602cef7e4a71d3e899a7160c22c5fd5c0a4c | Enable default mapped span results for Razor. | mgoertz-msft/roslyn,tmat/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,tannergooding/roslyn,dotnet/roslyn,heejaechang/roslyn,physhi/roslyn,panopticoncentral/roslyn,sharwell/roslyn,panopticoncentral/roslyn,genlu/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,physhi/roslyn,mgoertz-msft/roslyn,tmat/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,aelij/roslyn,weltkante/roslyn,heejaechang/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,dotnet/roslyn,aelij/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,weltkante/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,gafter/roslyn,diryboy/roslyn,tmat/roslyn,eriawan/roslyn,sharwell/roslyn,wvdd007/roslyn,bartdesmet/roslyn,stephentoub/roslyn,gafter/roslyn,tannergooding/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,gafter/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,stephentoub/roslyn,sharwell/roslyn,brettfo/roslyn,AmadeusW/roslyn,physhi/roslyn,bartdesmet/roslyn,genlu/roslyn,mavasani/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,aelij/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,KevinRansom/roslyn,diryboy/roslyn | src/Tools/ExternalAccess/Razor/RazorSpanMappingServiceWrapper.cs | src/Tools/ExternalAccess/Razor/RazorSpanMappingServiceWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal sealed class RazorSpanMappingServiceWrapper : ISpanMappingService
{
private readonly IRazorSpanMappingService _razorSpanMappingService;
public RazorSpanMappingServiceWrapper(IRazorSpanMappingService razorSpanMappingService)
{
_razorSpanMappingService = razorSpanMappingService ?? throw new ArgumentNullException(nameof(razorSpanMappingService));
}
public async Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
var razorSpans = await _razorSpanMappingService.MapSpansAsync(document, spans, cancellationToken).ConfigureAwait(false);
var roslynSpans = new MappedSpanResult[razorSpans.Length];
for (var i = 0; i < razorSpans.Length; i++)
{
var razorSpan = razorSpans[i];
if (razorSpan.FilePath == null)
{
// Unmapped location
roslynSpans[i] = default;
}
else
{
roslynSpans[i] = new MappedSpanResult(razorSpan.FilePath, razorSpan.LinePositionSpan, razorSpan.Span);
}
}
return roslynSpans.ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal sealed class RazorSpanMappingServiceWrapper : ISpanMappingService
{
private readonly IRazorSpanMappingService _razorSpanMappingService;
public RazorSpanMappingServiceWrapper(IRazorSpanMappingService razorSpanMappingService)
{
_razorSpanMappingService = razorSpanMappingService ?? throw new ArgumentNullException(nameof(razorSpanMappingService));
}
public async Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
var razorSpans = await _razorSpanMappingService.MapSpansAsync(document, spans, cancellationToken).ConfigureAwait(false);
var roslynSpans = new MappedSpanResult[razorSpans.Length];
for (var i = 0; i < razorSpans.Length; i++)
{
var razorSpan = razorSpans[i];
roslynSpans[i] = new MappedSpanResult(razorSpan.FilePath, razorSpan.LinePositionSpan, razorSpan.Span);
}
return roslynSpans.ToImmutableArray();
}
}
}
| mit | C# |
c5b21bea43bede0d2b538b65a53dbf57261e1e07 | Fix script filter test on ES 1.4.0.Beta1 | robertlyson/elasticsearch-net,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,SeanKilleen/elasticsearch-net,LeoYao/elasticsearch-net,UdiBen/elasticsearch-net,wawrzyn/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,robrich/elasticsearch-net,junlapong/elasticsearch-net,starckgates/elasticsearch-net,mac2000/elasticsearch-net,azubanov/elasticsearch-net,elastic/elasticsearch-net,ststeiger/elasticsearch-net,wawrzyn/elasticsearch-net,azubanov/elasticsearch-net,KodrAus/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,geofeedia/elasticsearch-net,LeoYao/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,geofeedia/elasticsearch-net,geofeedia/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,faisal00813/elasticsearch-net,tkirill/elasticsearch-net,TheFireCookie/elasticsearch-net,abibell/elasticsearch-net,amyzheng424/elasticsearch-net,adam-mccoy/elasticsearch-net,junlapong/elasticsearch-net,KodrAus/elasticsearch-net,ststeiger/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,gayancc/elasticsearch-net,jonyadamit/elasticsearch-net,amyzheng424/elasticsearch-net,amyzheng424/elasticsearch-net,starckgates/elasticsearch-net,junlapong/elasticsearch-net,gayancc/elasticsearch-net,robrich/elasticsearch-net,faisal00813/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,jonyadamit/elasticsearch-net,tkirill/elasticsearch-net,jonyadamit/elasticsearch-net,mac2000/elasticsearch-net,robrich/elasticsearch-net,joehmchan/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,DavidSSL/elasticsearch-net,UdiBen/elasticsearch-net,robertlyson/elasticsearch-net,TheFireCookie/elasticsearch-net,starckgates/elasticsearch-net,SeanKilleen/elasticsearch-net,SeanKilleen/elasticsearch-net,faisal00813/elasticsearch-net,DavidSSL/elasticsearch-net,cstlaurent/elasticsearch-net,mac2000/elasticsearch-net,DavidSSL/elasticsearch-net,abibell/elasticsearch-net,wawrzyn/elasticsearch-net,azubanov/elasticsearch-net,LeoYao/elasticsearch-net,adam-mccoy/elasticsearch-net,tkirill/elasticsearch-net,ststeiger/elasticsearch-net,joehmchan/elasticsearch-net | src/Tests/Nest.Tests.Integration/Search/Filter/ScriptFilterTests.cs | src/Tests/Nest.Tests.Integration/Search/Filter/ScriptFilterTests.cs | using System;
using System.Linq;
using NUnit.Framework;
using Nest.Tests.MockData;
using Nest.Tests.MockData.Domain;
namespace Nest.Tests.Integration.Search.Filter
{
/// <summary>
/// Integrated tests of ScriptFilter with elasticsearch.
/// </summary>
[TestFixture]
public class ScriptFilterTests : IntegrationTests
{
/// <summary>
/// Document used in test.
/// </summary>
private ElasticsearchProject _LookFor = NestTestData.Data.First();
/// <summary>
/// Set of filters that should not filter de documento _LookFor.
/// </summary>
[Test]
public void TestScriptFilter()
{
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == " + _LookFor.Id)),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", _LookFor.Id))),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", _LookFor.Id))),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == " + (_LookFor.Id + 1))),
_LookFor,
false);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", (_LookFor.Id + 1)))),
_LookFor,
false);
}
}
}
| using System;
using System.Linq;
using NUnit.Framework;
using Nest.Tests.MockData;
using Nest.Tests.MockData.Domain;
namespace Nest.Tests.Integration.Search.Filter
{
/// <summary>
/// Integrated tests of ScriptFilter with elasticsearch.
/// </summary>
[TestFixture]
public class ScriptFilterTests : IntegrationTests
{
/// <summary>
/// Document used in test.
/// </summary>
private ElasticsearchProject _LookFor = NestTestData.Data.First();
/// <summary>
/// Set of filters that should not filter de documento _LookFor.
/// </summary>
[Test]
public void TestScriptFilter()
{
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == " + _LookFor.Id)),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", _LookFor.Id))),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", _LookFor.Id)).Lang("mvel")),
_LookFor,
true);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == " + (_LookFor.Id + 1))),
_LookFor,
false);
this.DoFilterTest(
f => f.Script(s => s.Script("doc['id'].value == param1").Params(p => p.Add("param1", (_LookFor.Id + 1)))),
_LookFor,
false);
}
}
}
| apache-2.0 | C# |
249f692a497b767bf41a75f32203ae7f2f61d64d | make AspectCoreProxyTypeFactory sealed | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common.Aspect.AspectCore/AspectCoreProxyTypeFactory.cs | src/WeihanLi.Common.Aspect.AspectCore/AspectCoreProxyTypeFactory.cs | using System;
namespace WeihanLi.Common.Aspect.AspectCore
{
internal sealed class AspectCoreProxyTypeFactory : IProxyTypeFactory
{
public Type CreateProxyType(Type serviceType)
{
if (null == serviceType)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (serviceType.IsInterface)
{
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateClassProxyType(serviceType, serviceType);
}
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateInterfaceProxyType(serviceType);
}
public Type CreateProxyType(Type serviceType, Type implementType)
{
if (null == serviceType)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (null == implementType)
{
throw new ArgumentNullException(nameof(implementType));
}
if (serviceType.IsInterface)
{
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateClassProxyType(serviceType, implementType);
}
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateInterfaceProxyType(serviceType, implementType);
}
}
}
| using System;
namespace WeihanLi.Common.Aspect.AspectCore
{
internal class AspectCoreProxyTypeFactory : IProxyTypeFactory
{
public Type CreateProxyType(Type serviceType)
{
if (null == serviceType)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (serviceType.IsInterface)
{
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateClassProxyType(serviceType, serviceType);
}
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateInterfaceProxyType(serviceType);
}
public Type CreateProxyType(Type serviceType, Type implementType)
{
if (null == serviceType)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (null == implementType)
{
throw new ArgumentNullException(nameof(implementType));
}
if (serviceType.IsInterface)
{
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateClassProxyType(serviceType, implementType);
}
return AspectCoreHelper.ProxyGenerator.TypeGenerator.CreateInterfaceProxyType(serviceType, implementType);
}
}
}
| mit | C# |
ffa38265ebad280dc9be07f46a6abb425b225336 | Add mediaStoreRoot to FileMediaStore | SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake | Snowflake.API/Information/MediaStore/FileMediaStore.cs | Snowflake.API/Information/MediaStore/FileMediaStore.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class FileMediaStore : IMediaStore
{
private Dictionary<string, IMediaStoreSection> sections;
public IMediaStoreSection Images
{
get { return this.sections["Images"]; }
}
public IMediaStoreSection Audio
{
get { return this.sections["Audio"]; }
}
public IMediaStoreSection Video
{
get { return this.sections["Video"]; }
}
public IMediaStoreSection Resources
{
get { return this.sections["Resources"]; }
}
public string MediaStoreKey { get; private set; }
public string MediaStoreRoot { get; private set; }
public FileMediaStore(string mediastoreKey, string mediastoreRoot)
{
if (!Directory.Exists(mediastoreRoot)) Directory.CreateDirectory(mediastoreRoot);
if (!Directory.Exists(Path.Combine(mediastoreRoot, mediastoreKey))) Directory.CreateDirectory(Path.Combine(mediastoreRoot, mediastoreKey));
this.MediaStoreKey = mediastoreKey;
this.MediaStoreRoot = mediaStoreRoot;
this.sections = new Dictionary<string, IMediaStoreSection>()
{
{"Images", new FileMediaStoreSection("Images", this) },
{"Audio", new FileMediaStoreSection("Audio", this) },
{"Video", new FileMediaStoreSection("Video", this) },
{"Resources", new FileMediaStoreSection("Resources", this) }
};
}
public FileMediaStore(string mediastoreKey) : this(mediastoreKey, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores")) { }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class FileMediaStore : IMediaStore
{
private Dictionary<string, IMediaStoreSection> sections;
public IMediaStoreSection Images
{
get { return this.sections["Images"]; }
}
public IMediaStoreSection Audio
{
get { return this.sections["Audio"]; }
}
public IMediaStoreSection Video
{
get { return this.sections["Video"]; }
}
public IMediaStoreSection Resources
{
get { return this.sections["Resources"]; }
}
public string MediaStoreKey { get; private set; }
public FileMediaStore(string mediastoreKey, string mediastoreRoot)
{
if (!Directory.Exists(mediastoreRoot)) Directory.CreateDirectory(mediastoreRoot);
if (!Directory.Exists(Path.Combine(mediastoreRoot, mediastoreKey))) Directory.CreateDirectory(Path.Combine(mediastoreRoot, mediastoreKey));
this.MediaStoreKey = mediastoreKey;
this.sections = new Dictionary<string, IMediaStoreSection>()
{
{"Images", new FileMediaStoreSection("Images", this) },
{"Audio", new FileMediaStoreSection("Audio", this) },
{"Video", new FileMediaStoreSection("Video", this) },
{"Resources", new FileMediaStoreSection("Resources", this) }
};
}
public FileMediaStore(string mediastoreKey) : this(mediastoreKey, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores")) { }
}
}
| mpl-2.0 | C# |
327e7b2c1400861626e26eae132f186f421ecbe2 | Select View from ContentTransition | Silphid/Silphid.Unity,Silphid/Silphid.Unity | Sources/Silphid.Showzup/Sources/Controls/TabControl.cs | Sources/Silphid.Showzup/Sources/Controls/TabControl.cs | using System;
using System.Linq;
using Silphid.Extensions;
using Silphid.Showzup.Navigation;
using UniRx;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Silphid.Showzup
{
public enum TabPlacement
{
Top = MoveDirection.Up,
Bottom = MoveDirection.Down,
Left = MoveDirection.Left,
Right = MoveDirection.Right
}
public class TabControl : MonoBehaviour, IPresenter, ISelectHandler, IMoveHandler
{
public SelectionControl TabSelectionControl;
public TransitionControl ContentTransitionControl;
public TabPlacement TabPlacement = TabPlacement.Top;
private readonly MoveHandler _moveHandler = new MoveHandler();
public void Start()
{
TabSelectionControl.Views
.Select(x => x.FirstOrDefault())
.BindTo(TabSelectionControl.SelectedView)
.AddTo(this);
TabSelectionControl.SelectedView
.WhereNotNull() // TODO SelectionControl should keep selection but can't with current unity select system
.Select(x => x?.ViewModel?.Model)
.BindTo(ContentTransitionControl);
_moveHandler.BindBidirectional(
ContentTransitionControl,
TabSelectionControl,
(MoveDirection) TabPlacement);
_moveHandler.SelectedGameObject
.Where(x => x == ContentTransitionControl.gameObject)
.Subscribe(x => ContentTransitionControl.View.Value.SelectDeferred())
.AddTo(this);
}
public bool CanPresent(object input, Options options = null) =>
TabSelectionControl.CanPresent(input, options);
public IObservable<IView> Present(object input, Options options = null) =>
TabSelectionControl.Present(input, options);
public void OnSelect(BaseEventData eventData)
{
TabSelectionControl.Select();
}
public void OnMove(AxisEventData eventData)
{
_moveHandler.OnMove(eventData);
}
}
} | using System;
using System.Linq;
using Silphid.Extensions;
using Silphid.Showzup.Navigation;
using UniRx;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Silphid.Showzup
{
public enum TabPlacement
{
Top = MoveDirection.Up,
Bottom = MoveDirection.Down,
Left = MoveDirection.Left,
Right = MoveDirection.Right
}
public class TabControl : MonoBehaviour, IPresenter, ISelectHandler, IMoveHandler
{
public SelectionControl TabSelectionControl;
public TransitionControl ContentTransitionControl;
public TabPlacement TabPlacement = TabPlacement.Top;
private readonly MoveHandler _moveHandler = new MoveHandler();
public void Start()
{
TabSelectionControl.Views
.Select(x => x.FirstOrDefault())
.BindTo(TabSelectionControl.SelectedView)
.AddTo(this);
TabSelectionControl.SelectedView
.Select(x => x?.ViewModel?.Model)
.BindTo(ContentTransitionControl);
_moveHandler.BindBidirectional(
ContentTransitionControl,
TabSelectionControl,
(MoveDirection) TabPlacement);
}
public bool CanPresent(object input, Options options = null) =>
TabSelectionControl.CanPresent(input, options);
public IObservable<IView> Present(object input, Options options = null) =>
TabSelectionControl.Present(input, options);
public void OnSelect(BaseEventData eventData)
{
TabSelectionControl.Select();
}
public void OnMove(AxisEventData eventData)
{
_moveHandler.OnMove(eventData);
}
}
} | mit | C# |
53c7ca414865cb97c3773fe3d65e906f1abcec58 | Set more specific return type to enable application/atom+xml response formatting. | Stift/NuGet.Lucene,googol/NuGet.Lucene,themotleyfool/NuGet.Lucene | source/NuGet.Lucene.Web/Controllers/PackagesODataController.cs | source/NuGet.Lucene.Web/Controllers/PackagesODataController.cs | using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;
namespace NuGet.Lucene.Web.Controllers
{
/// <summary>
/// OData provider for Lucene based NuGet package repository.
/// </summary>
public class PackagesODataController : ODataController
{
public ILucenePackageRepository Repository { get; set; }
public IMirroringPackageRepository MirroringRepository { get; set; }
[Queryable]
public IQueryable<ODataPackage> Get()
{
return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
}
public IHttpActionResult Get([FromODataUri] string id, [FromODataUri] string version)
{
SemanticVersion semanticVersion;
if (!SemanticVersion.TryParse(version, out semanticVersion))
{
return BadRequest("Invalid version");
}
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest("Invalid package id");
}
var package = MirroringRepository.FindPackage(id, semanticVersion);
return package == null ? (IHttpActionResult)NotFound() : Ok(package.AsDataServicePackage());
}
}
}
| using System.Linq;
using System.Web.Http;
using System.Web.Http.OData;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Util;
namespace NuGet.Lucene.Web.Controllers
{
/// <summary>
/// OData provider for Lucene based NuGet package repository.
/// </summary>
public class PackagesODataController : ODataController
{
public ILucenePackageRepository Repository { get; set; }
public IMirroringPackageRepository MirroringRepository { get; set; }
[Queryable]
public IQueryable<ODataPackage> Get()
{
return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable();
}
public object Get([FromODataUri] string id, [FromODataUri] string version)
{
SemanticVersion semanticVersion;
if (!SemanticVersion.TryParse(version, out semanticVersion))
{
return BadRequest("Invalid version");
}
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest("Invalid package id");
}
var package = MirroringRepository.FindPackage(id, semanticVersion);
return package == null ? (object)NotFound() : package.AsDataServicePackage();
}
}
}
| apache-2.0 | C# |
c362005abee852775d4f7ae464b340bdc7505677 | update error messages in ReadonlyDbContext | HighwayFramework/Highway.Data,ericburcham/Highway.Data | src/Highway.Data.EntityFramework/Contexts/ReadonlyDbContext.cs | src/Highway.Data.EntityFramework/Contexts/ReadonlyDbContext.cs | using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Threading;
using System.Threading.Tasks;
namespace Highway.Data
{
public abstract class ReadonlyDbContext : DbContext
{
protected ReadonlyDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected ReadonlyDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
public override int SaveChanges()
{
throw new InvalidOperationException($"Do not call {nameof(SaveChanges)} on a {nameof(ReadonlyDbContext)}.");
}
public override Task<int> SaveChangesAsync()
{
throw new InvalidOperationException($"Do not call {nameof(SaveChangesAsync)} on a {nameof(ReadonlyDbContext)}.");
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
throw new InvalidOperationException($"Do not call {nameof(SaveChangesAsync)} on a {nameof(ReadonlyDbContext)}.");
}
public override DbSet<TEntity> Set<TEntity>()
{
throw new InvalidOperationException($"Do not call {nameof(Set)} on a {nameof(ReadonlyDbContext)}.");
}
public override DbSet Set(Type entityType)
{
throw new InvalidOperationException($"Do not call {nameof(Set)} on a {nameof(ReadonlyDbContext)}.");
}
protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
throw new InvalidOperationException($"Do not call {nameof(ShouldValidateEntity)} on a {nameof(ReadonlyDbContext)}.");
}
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
throw new InvalidOperationException($"Do not call {nameof(ValidateEntity)} on a {nameof(ReadonlyDbContext)}.");
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Threading;
using System.Threading.Tasks;
namespace Highway.Data
{
public abstract class ReadonlyDbContext : DbContext
{
protected ReadonlyDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected ReadonlyDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
public override int SaveChanges()
{
throw new InvalidOperationException($"Do not call {nameof(SaveChanges)} on a {nameof(ReadonlyDbContext)}.");
}
public override Task<int> SaveChangesAsync()
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(SaveChangesAsync)}");
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(SaveChangesAsync)}");
}
public override DbSet<TEntity> Set<TEntity>()
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(Set)}");
}
public override DbSet Set(Type entityType)
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(Set)}");
}
protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(ShouldValidateEntity)}");
}
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
throw new InvalidOperationException($"{nameof(ReadonlyDataContext)} does not implement {nameof(ValidateEntity)}");
}
}
}
| mit | C# |
68b61c1ae7ab1fb64f9f4fd72e4d942ae71aa2e8 | Update InteractiveModuleBase to support latest Discord.Net | foxbot/Discord.Addons.InteractiveCommands,foxbot/Discord.Addons.InteractiveCommands | src/Discord.Addons.InteractiveCommands/InteractiveModuleBase.cs | src/Discord.Addons.InteractiveCommands/InteractiveModuleBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading;
namespace Discord.Addons.InteractiveCommands
{
public abstract class InteractiveModuleBase : InteractiveModuleBase<CommandContext> { }
public abstract class InteractiveModuleBase<T> : ModuleBase<T> where T : class, ICommandContext
{
/// <summary>
/// Waits for the user to send a message.
/// </summary>
/// <param name="user">Which user to wait for a message from.</param>
/// <param name="channel">Which channel the message should be sent in. (If null, will accept a response from any channel).</param>
/// <param name="timeout">How long to wait for a message before timing out. This value will default to 15 seconds.</param>
/// <param name="preconditions">Any preconditions to run to determine if a response is valid.</param>
/// <returns>The response.</returns>
/// <remarks>When you use this in a command, the command's RunMode MUST be set to 'async'. Otherwise, the gateway thread will be blocked, and this will never return.</remarks>
public async Task<IUserMessage> WaitForMessage(IUser user, IMessageChannel channel = null, TimeSpan? timeout = null, params ResponsePrecondition[] preconditions)
{
var client = Context.Client as DiscordSocketClient;
if (client == null) throw new NotSupportedException("This addon must be ran with a DiscordSocketClient.");
return await new InteractiveService(client).WaitForMessage(user, channel, timeout, preconditions);
}
protected virtual Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, EmbedBuilder embed = null, int deleteAfter = 5, RequestOptions options = null)
{
return Context.Channel.SendMessageAsync(message, isTTS, embed, deleteAfter, options);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading;
namespace Discord.Addons.InteractiveCommands
{
public class InteractiveModuleBase : ModuleBase
{
/// <summary>
/// Waits for the user to send a message.
/// </summary>
/// <param name="user">Which user to wait for a message from.</param>
/// <param name="channel">Which channel the message should be sent in. (If null, will accept a response from any channel).</param>
/// <param name="timeout">How long to wait for a message before timing out. This value will default to 15 seconds.</param>
/// <param name="preconditions">Any preconditions to run to determine if a response is valid.</param>
/// <returns>The response.</returns>
/// <remarks>When you use this in a command, the command's RunMode MUST be set to 'async'. Otherwise, the gateway thread will be blocked, and this will never return.</remarks>
public async Task<IUserMessage> WaitForMessage(IUser user, IMessageChannel channel = null, TimeSpan? timeout = null, params ResponsePrecondition[] preconditions)
{
var client = Context.Client as DiscordSocketClient;
if (client == null) throw new NotSupportedException("This addon must be ran with a DiscordSocketClient.");
return await new InteractiveService(client).WaitForMessage(user, channel, timeout, preconditions);
}
protected virtual Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, EmbedBuilder embed = null, int deleteAfter = 5, RequestOptions options = null)
{
return Context.Channel.SendMessageAsync(message, isTTS, embed, deleteAfter, options);
}
}
}
| isc | C# |
5141bf66eb56000e9585325c001e00841400348c | Add failing test case | ppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu | osu.Game.Tests/Visual/Playlists/TestScenePlaylistsLoungeSubScreen.cs | osu.Game.Tests/Visual/Playlists/TestScenePlaylistsLoungeSubScreen.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.Linq;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Graphics.Containers;
using osu.Game.Screens.OnlinePlay.Lounge;
using osu.Game.Screens.OnlinePlay.Lounge.Components;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Tests.Visual.OnlinePlay;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Playlists
{
public class TestScenePlaylistsLoungeSubScreen : OnlinePlayTestScene
{
protected new BasicTestRoomManager RoomManager => (BasicTestRoomManager)base.RoomManager;
private LoungeSubScreen loungeScreen;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("push screen", () => LoadScreen(loungeScreen = new PlaylistsLoungeSubScreen()));
AddUntilStep("wait for present", () => loungeScreen.IsCurrentScreen());
}
private RoomsContainer roomsContainer => loungeScreen.ChildrenOfType<RoomsContainer>().First();
[Test]
public void TestScrollByDraggingRooms()
{
AddStep("reset mouse", () => InputManager.ReleaseButton(MouseButton.Left));
AddStep("add rooms", () => RoomManager.AddRooms(30));
AddUntilStep("first room is not masked", () => checkRoomVisible(roomsContainer.Rooms[0]));
AddStep("move mouse to third room", () => InputManager.MoveMouseTo(roomsContainer.Rooms[2]));
AddStep("hold down", () => InputManager.PressButton(MouseButton.Left));
AddStep("drag to top", () => InputManager.MoveMouseTo(roomsContainer.Rooms[0]));
AddAssert("first and second room masked", ()
=> !checkRoomVisible(roomsContainer.Rooms[0]) &&
!checkRoomVisible(roomsContainer.Rooms[1]));
}
[Test]
public void TestScrollSelectedIntoView()
{
AddStep("add rooms", () => RoomManager.AddRooms(30));
AddUntilStep("first room is not masked", () => checkRoomVisible(roomsContainer.Rooms[0]));
AddStep("select last room", () => roomsContainer.Rooms[^1].Click());
AddUntilStep("first room is masked", () => !checkRoomVisible(roomsContainer.Rooms[0]));
AddUntilStep("last room is not masked", () => checkRoomVisible(roomsContainer.Rooms[^1]));
}
private bool checkRoomVisible(DrawableRoom room) =>
loungeScreen.ChildrenOfType<OsuScrollContainer>().First().ScreenSpaceDrawQuad
.Contains(room.ScreenSpaceDrawQuad.Centre);
}
}
| // 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.Linq;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Graphics.Containers;
using osu.Game.Screens.OnlinePlay.Lounge;
using osu.Game.Screens.OnlinePlay.Lounge.Components;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Tests.Visual.OnlinePlay;
namespace osu.Game.Tests.Visual.Playlists
{
public class TestScenePlaylistsLoungeSubScreen : OnlinePlayTestScene
{
protected new BasicTestRoomManager RoomManager => (BasicTestRoomManager)base.RoomManager;
private LoungeSubScreen loungeScreen;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("push screen", () => LoadScreen(loungeScreen = new PlaylistsLoungeSubScreen()));
AddUntilStep("wait for present", () => loungeScreen.IsCurrentScreen());
}
private RoomsContainer roomsContainer => loungeScreen.ChildrenOfType<RoomsContainer>().First();
[Test]
public void TestScrollSelectedIntoView()
{
AddStep("add rooms", () => RoomManager.AddRooms(30));
AddUntilStep("first room is not masked", () => checkRoomVisible(roomsContainer.Rooms.First()));
AddStep("select last room", () => roomsContainer.Rooms.Last().Click());
AddUntilStep("first room is masked", () => !checkRoomVisible(roomsContainer.Rooms.First()));
AddUntilStep("last room is not masked", () => checkRoomVisible(roomsContainer.Rooms.Last()));
}
private bool checkRoomVisible(DrawableRoom room) =>
loungeScreen.ChildrenOfType<OsuScrollContainer>().First().ScreenSpaceDrawQuad
.Contains(room.ScreenSpaceDrawQuad.Centre);
}
}
| mit | C# |
65005311e6a3eccb0051b907df1305222aefdb33 | remove some junk | jonnii/statr,jonnii/statr | src/Statr.Specifications/Storage/DataPointCacheSpecification.cs | src/Statr.Specifications/Storage/DataPointCacheSpecification.cs | using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Machine.Fakes;
using Machine.Specifications;
using Statr.Routing;
using Statr.Storage;
namespace Statr.Specifications.Storage
{
public class DataPointCacheSpecification
{
[Subject(typeof(DataPointCache))]
public class when_getting_bucket : WithSubject<DataPointCache>
{
Because of = () =>
points = Subject.Get(new BucketReference("metric.name", MetricType.Count));
It should_get_empty_result = () =>
points.ShouldBeEmpty();
static IEnumerable<DataPoint> points;
}
[Subject(typeof(DataPointCache))]
public class when_getting_bucket_with_points : with_points
{
Because of = () =>
points = Subject.Get(new BucketReference("metric.name", MetricType.Count));
It should_get_results = () =>
points.ShouldNotBeEmpty();
static IEnumerable<DataPoint> points;
}
public class with_points : WithSubject<DataPointCache>
{
Establish context = () =>
{
The<IDataPointStream>().WhenToldTo(g => g.DataPoints).Return(new Subject<DataPointEvent>());
Subject.Start();
Subject.Push(
new DataPointEvent(
new BucketReference("metric.name", MetricType.Count),
new DataPoint(DateTime.Now, 500, 1)));
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Machine.Fakes;
using Machine.Specifications;
using Statr.Routing;
using Statr.Storage;
namespace Statr.Specifications.Storage
{
public class DataPointCacheSpecification
{
[Subject(typeof(DataPointCache))]
public class when_getting_bucket : with_empty_cache
{
Because of = () =>
points = Subject.Get(new BucketReference("metric.name", MetricType.Count));
It should_get_empty_result = () =>
points.ShouldBeEmpty();
static IEnumerable<DataPoint> points;
}
[Subject(typeof(DataPointCache))]
public class when_getting_bucket_with_points : with_points
{
Because of = () =>
points = Subject.Get(new BucketReference("metric.name", MetricType.Count));
It should_get_results = () =>
points.ShouldNotBeEmpty();
static IEnumerable<DataPoint> points;
}
public class with_empty_cache : WithSubject<DataPointCache>
{
}
public class with_points : WithSubject<DataPointCache>
{
Establish context = () =>
{
The<IDataPointStream>().WhenToldTo(g => g.DataPoints).Return(new Subject<DataPointEvent>());
Subject.Start();
Subject.Push(
new DataPointEvent(
new BucketReference("metric.name", MetricType.Count),
new DataPoint(DateTime.Now, 500, 1)));
};
}
}
}
| apache-2.0 | C# |
1734861a9036e916dbbe5df615c03b23670db918 | Throw exception outside of catch | appharbor/appharbor-cli | src/AppHarbor/ApplicationConfiguration.cs | src/AppHarbor/ApplicationConfiguration.cs | using System;
using System.IO;
using AppHarbor.Model;
namespace AppHarbor
{
public class ApplicationConfiguration : IApplicationConfiguration
{
private readonly IFileSystem _fileSystem;
private readonly IGitExecutor _gitExecutor;
public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor)
{
_fileSystem = fileSystem;
_gitExecutor = gitExecutor;
}
public string GetApplicationId()
{
try
{
using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (FileNotFoundException)
{
}
throw new ApplicationConfigurationException("Application is not configured");
}
public virtual void SetupApplication(string id, User user)
{
var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id);
try
{
_gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id),
new DirectoryInfo(Directory.GetCurrentDirectory()));
Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master");
return;
}
catch (InvalidOperationException)
{
}
Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl);
using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName))
{
using (var writer = new StreamWriter(stream))
{
writer.Write(id);
}
}
Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile);
}
private static FileInfo ConfigurationFile
{
get
{
var directory = Directory.GetCurrentDirectory();
var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor"));
return appharborConfigurationFile;
}
}
}
}
| using System;
using System.IO;
using AppHarbor.Model;
namespace AppHarbor
{
public class ApplicationConfiguration : IApplicationConfiguration
{
private readonly IFileSystem _fileSystem;
private readonly IGitExecutor _gitExecutor;
public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor)
{
_fileSystem = fileSystem;
_gitExecutor = gitExecutor;
}
public string GetApplicationId()
{
try
{
using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
catch (FileNotFoundException)
{
throw new ApplicationConfigurationException("Application is not configured");
}
}
public virtual void SetupApplication(string id, User user)
{
var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id);
try
{
_gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id),
new DirectoryInfo(Directory.GetCurrentDirectory()));
Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master");
return;
}
catch (InvalidOperationException)
{
}
Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl);
using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName))
{
using (var writer = new StreamWriter(stream))
{
writer.Write(id);
}
}
Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile);
}
private static FileInfo ConfigurationFile
{
get
{
var directory = Directory.GetCurrentDirectory();
var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor"));
return appharborConfigurationFile;
}
}
}
}
| mit | C# |
fb3f64ecd9740a6a9e3720313d2d7e3b19f7ccbe | Update assembly info | vgrigoriu/FromString | src/FromString/Properties/AssemblyInfo.cs | src/FromString/Properties/AssemblyInfo.cs | using System.Resources;
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("FromString")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FromString")]
[assembly: AssemblyCopyright("Copyright © 2014 Teamnet")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Resources;
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("FromString")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FromString")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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# |
3d5eb0a092455da64905cc68da37f964ef0d26fb | Use net5-7 in Desktop.Tests | filipw/dotnet-script,filipw/dotnet-script | src/Dotnet.Script.Desktop.Tests/CompilationDepenencyTests.cs | src/Dotnet.Script.Desktop.Tests/CompilationDepenencyTests.cs | using System.IO;
using System.Linq;
using Dotnet.Script.DependencyModel.Compilation;
using Dotnet.Script.Shared.Tests;
using Xunit;
using Xunit.Abstractions;
namespace Dotnet.Script.Desktop.Tests
{
public class CompilationDependencyTests
{
public CompilationDependencyTests(ITestOutputHelper testOutputHelper)
{
testOutputHelper.Capture();
}
[Theory]
[InlineData("net5.0")]
[InlineData("net6.0")]
[InlineData("net7.0")]
public void ShouldGetCompilationDependenciesForNetCoreApp(string targetFramework)
{
var resolver = CreateResolver();
var targetDirectory = TestPathUtils.GetPathToTestFixtureFolder("HelloWorld");
var csxFiles = Directory.GetFiles(targetDirectory, "*.csx");
var dependencies = resolver.GetDependencies(targetDirectory, csxFiles, true, targetFramework);
Assert.True(dependencies.Count() > 0);
}
private CompilationDependencyResolver CreateResolver()
{
var resolver = new CompilationDependencyResolver(TestOutputHelper.CreateTestLogFactory());
return resolver;
}
}
} | using System.IO;
using System.Linq;
using Dotnet.Script.DependencyModel.Compilation;
using Dotnet.Script.Shared.Tests;
using Xunit;
using Xunit.Abstractions;
namespace Dotnet.Script.Desktop.Tests
{
public class CompilationDependencyTests
{
public CompilationDependencyTests(ITestOutputHelper testOutputHelper)
{
testOutputHelper.Capture();
}
[Theory]
[InlineData("netcoreapp3.1")]
[InlineData("net5.0")]
public void ShouldGetCompilationDependenciesForNetCoreApp(string targetFramework)
{
var resolver = CreateResolver();
var targetDirectory = TestPathUtils.GetPathToTestFixtureFolder("HelloWorld");
var csxFiles = Directory.GetFiles(targetDirectory, "*.csx");
var dependencies = resolver.GetDependencies(targetDirectory, csxFiles, true, targetFramework);
Assert.True(dependencies.Count() > 0);
}
private CompilationDependencyResolver CreateResolver()
{
var resolver = new CompilationDependencyResolver(TestOutputHelper.CreateTestLogFactory());
return resolver;
}
}
} | mit | C# |
2cae22b7c23dfdb13fdbd1a74b87c535e8961297 | Fix typo in UpdateFrequency.cs | AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css,AngleSharp/AngleSharp.Css | src/AngleSharp.Css/Dom/UpdateFrequency.cs | src/AngleSharp.Css/Dom/UpdateFrequency.cs | namespace AngleSharp.Css.Dom
{
/// <summary>
/// Available device update frequencies.
/// </summary>
public enum UpdateFrequency : byte
{
/// <summary>
/// Once it has been rendered, the layout can no longer
/// be updated. Example: documents printed on paper.
/// </summary>
None,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, but the output device is not
/// able to render or display changes quickly enough for
/// them to be perceived as a smooth animation.
/// Example: E-ink screens or severely under-powered
/// devices.
/// </summary>
Slow,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, and the output device is not
/// unusually constrained in speed, so regularly-updating
/// things like CSS Animations can be used.
/// Example: computer screens.
/// </summary>
Normal
}
}
| namespace AngleSharp.Css.Dom
{
/// <summary>
/// Available device update frequencies.
/// </summary>
public enum UpdateFrequency : byte
{
/// <summary>
/// Once it has been rendered, the layout can no longer
/// be updated. Example: documents printed on paper.
/// </summary>
None,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, but the output device is not
/// able to render or display changes quickly enough for
/// them to be percieved as a smooth animation.
/// Example: E-ink screens or severely under-powered
/// devices.
/// </summary>
Slow,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, and the output device is not
/// unusually constrained in speed, so regularly-updating
/// things like CSS Animations can be used.
/// Example: computer screens.
/// </summary>
Normal
}
}
| mit | C# |
7329c8364e2a94aa99226edfa48fb4d40373d363 | Select new points | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.Core/Editor/Tools/PointTool.cs | src/Draw2D.Core/Editor/Tools/PointTool.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Draw2D.Core.Shapes;
using Draw2D.Spatial;
namespace Draw2D.Core.Editor.Tools
{
public class PointTool : ToolBase
{
public override string Name { get { return "Point"; } }
public PointToolSettings Settings { get; set; }
public override void LeftDown(IToolContext context, double x, double y, Modifier modifier)
{
base.LeftDown(context, x, y, modifier);
Filters?.ForEach(f => f.Clear(context));
Filters?.Any(f => f.Process(context, ref x, ref y));
var point = new PointShape(x, y, context.PointShape);
var shape = context.HitTest?.TryToGetShape(
context.CurrentContainer.Shapes,
new Point2(x, y),
Settings?.HitTestRadius ?? 7.0);
if (shape != null && (Settings?.ConnectPoints ?? false))
{
if (shape is ConnectableShape connectable)
{
connectable.Points.Add(point);
context.Selected.Add(point);
}
}
else
{
context.CurrentContainer.Shapes.Add(point);
}
}
public override void Move(IToolContext context, double x, double y, Modifier modifier)
{
base.Move(context, x, y, modifier);
Filters?.ForEach(f => f.Clear(context));
Filters?.Any(f => f.Process(context, ref x, ref y));
}
public override void Clean(IToolContext context)
{
base.Clean(context);
Filters?.ForEach(f => f.Clear(context));
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Draw2D.Core.Shapes;
using Draw2D.Spatial;
namespace Draw2D.Core.Editor.Tools
{
public class PointTool : ToolBase
{
public override string Name { get { return "Point"; } }
public PointToolSettings Settings { get; set; }
public override void LeftDown(IToolContext context, double x, double y, Modifier modifier)
{
base.LeftDown(context, x, y, modifier);
Filters?.ForEach(f => f.Clear(context));
Filters?.Any(f => f.Process(context, ref x, ref y));
var point = new PointShape(x, y, context.PointShape);
var shape = context.HitTest?.TryToGetShape(
context.CurrentContainer.Shapes,
new Point2(x, y),
Settings?.HitTestRadius ?? 7.0);
if (shape != null && (Settings?.ConnectPoints ?? false))
{
if (shape is ConnectableShape connectable)
{
connectable.Points.Add(point);
}
}
else
{
context.CurrentContainer.Shapes.Add(point);
}
}
public override void Move(IToolContext context, double x, double y, Modifier modifier)
{
base.Move(context, x, y, modifier);
Filters?.ForEach(f => f.Clear(context));
Filters?.Any(f => f.Process(context, ref x, ref y));
}
public override void Clean(IToolContext context)
{
base.Clean(context);
Filters?.ForEach(f => f.Clear(context));
}
}
}
| mit | C# |
9f3ecab2c62e686f018fc5e89aa25820fcce610e | Remove unused using. | GiveCampUK/GiveCRM,GiveCampUK/GiveCRM | src/GiveCRM.Web/Views/Member/Index.cshtml | src/GiveCRM.Web/Views/Member/Index.cshtml | @{
ViewBag.Title = "Index";
}
<h2>Members Dashboard</h2>
<div id="actions">
<ul>
<li>@Html.ActionLink("Add New Member", "Add")</li>
<li>@Html.ActionLink("Import Excel Spreadsheet", "Index", "ExcelImport")</li>
</ul>
</div>
<div id="search">
@{ Html.RenderAction("Search"); }
</div>
<div id="results"> </div> | @using GiveCRM.Web.Models.Members
@{
ViewBag.Title = "Index";
}
<h2>Members Dashboard</h2>
<div id="actions">
<ul>
<li>@Html.ActionLink("Add New Member", "Add")</li>
<li>@Html.ActionLink("Import Excel Spreadsheet", "Index", "ExcelImport")</li>
</ul>
</div>
<div id="search">
@{ Html.RenderAction("Search"); }
</div>
<div id="results"> </div> | mit | C# |
52538dc7083f2063149c8f08a249921c3c429acc | Refactor `LatencyCursorContainer` to become a cursor container | peppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu | osu.Game/Screens/Utility/SampleComponents/LatencyCursorContainer.cs | osu.Game/Screens/Utility/SampleComponents/LatencyCursorContainer.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 enable
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Game.Screens.Utility.SampleComponents
{
public class LatencyCursorContainer : CursorContainer
{
protected override Drawable CreateCursor() => new LatencyCursor();
public override bool IsPresent => base.IsPresent || Scheduler.HasPendingTasks;
public LatencyCursorContainer()
{
State.Value = Visibility.Hidden;
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
// CursorContainer implements IRequireHighFrequencyMousePosition, which bypasses limited rate updating, therefore scheduling is required.
// We can alternatively solve this by a PassThroughInputManager layer inside LatencyArea,
// but that would mean including input lag to this test, which may not be desired.
Schedule(() => base.OnMouseMove(e));
return false;
}
private class LatencyCursor : LatencySampleComponent
{
public LatencyCursor()
{
AutoSizeAxes = Axes.Both;
Origin = Anchor.Centre;
InternalChild = new Circle { Size = new Vector2(40) };
}
protected override void UpdateAtLimitedRate(InputState inputState)
{
Colour = inputState.Mouse.IsPressed(MouseButton.Left) ? OverlayColourProvider.Content1 : OverlayColourProvider.Colour2;
}
}
}
}
| // 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 enable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osu.Game.Overlays;
using osuTK;
using osuTK.Input;
namespace osu.Game.Screens.Utility.SampleComponents
{
public class LatencyCursorContainer : LatencySampleComponent
{
private Circle cursor = null!;
[Resolved]
private OverlayColourProvider overlayColourProvider { get; set; } = null!;
public LatencyCursorContainer()
{
Masking = true;
}
protected override void LoadComplete()
{
base.LoadComplete();
InternalChild = cursor = new Circle
{
Size = new Vector2(40),
Origin = Anchor.Centre,
Colour = overlayColourProvider.Colour2,
};
}
protected override bool OnHover(HoverEvent e) => false;
protected override void UpdateAtLimitedRate(InputState inputState)
{
cursor.Colour = inputState.Mouse.IsPressed(MouseButton.Left) ? overlayColourProvider.Content1 : overlayColourProvider.Colour2;
if (IsActive.Value)
{
cursor.Position = ToLocalSpace(inputState.Mouse.Position);
cursor.Alpha = 1;
}
else
{
cursor.Alpha = 0;
}
}
}
}
| mit | C# |
ad8aa65e8317ad22d8185226577a31e49e6c7416 | Correct basic client config test | modulexcite/lokad-cqrs | Framework/Lokad.Cqrs.Azure.Tests/BasicClientConfigurationTests.cs | Framework/Lokad.Cqrs.Azure.Tests/BasicClientConfigurationTests.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using Lokad.Cqrs.Build.Client;
using Lokad.Cqrs.Build.Engine;
using Lokad.Cqrs.Core.Dispatch.Events;
using Microsoft.WindowsAzure;
using NUnit.Framework;
using System.Linq;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class BasicClientConfigurationTests
{
[DataContract]
public sealed class Message : Define.Command
{
}
// ReSharper disable InconsistentNaming
[Test]
public void Test()
{
var dev = AzureStorage.CreateConfigurationForDev();
WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
var events = new Subject<ISystemEvent>();
var b = new CqrsEngineBuilder();
b.Azure(c => c.AddAzureProcess(dev, "test-publish",HandlerComposer.Empty));
b.Advanced.RegisterObserver(events);
var engine = b.Build();
var source = new CancellationTokenSource();
engine.Start(source.Token);
var builder = new CqrsClientBuilder();
builder.Azure(c => c.AddAzureSender(dev, "test-publish"));
var client = builder.Build();
client.Sender.SendOne(new Message());
using (engine)
using (events.OfType<EnvelopeAcked>().Subscribe(e => source.Cancel()))
{
source.Token.WaitHandle.WaitOne(5000);
source.Cancel();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using Lokad.Cqrs.Build.Client;
using Lokad.Cqrs.Build.Engine;
using Lokad.Cqrs.Core.Dispatch.Events;
using Microsoft.WindowsAzure;
using NUnit.Framework;
using System.Linq;
namespace Lokad.Cqrs
{
[TestFixture]
public sealed class BasicClientConfigurationTests
{
[DataContract]
public sealed class Message : Define.Command
{
}
// ReSharper disable InconsistentNaming
[Test]
public void Test()
{
var dev = AzureStorage.CreateConfigurationForDev();
WipeAzureAccount.Fast(s => s.StartsWith("test-"), dev);
var events = new Subject<ISystemEvent>();
var b = new CqrsEngineBuilder();
b.Azure(c => c.AddAzureProcess(dev, "test-publish",container => { }));
b.Advanced.RegisterObserver(events);
var engine = b.Build();
var source = new CancellationTokenSource();
engine.Start(source.Token);
var builder = new CqrsClientBuilder();
builder.Azure(c => c.AddAzureSender(dev, "test-publish"));
var client = builder.Build();
client.Sender.SendOne(new Message());
using (engine)
using (events.OfType<EnvelopeAcked>().Subscribe(e => source.Cancel()))
{
source.Token.WaitHandle.WaitOne(5000);
source.Cancel();
}
}
}
} | bsd-3-clause | C# |
c00f4511b4ece5e5cb420c4c79ec55b9fed0f3dd | Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | jango2015/Autofac.Configuration,autofac/Autofac.Configuration | Properties/VersionAssemblyInfo.cs | Properties/VersionAssemblyInfo.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Configuration 3.2.0")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Configuration 3.2.0")]
| mit | C# |
579a708b7195ee37aeb0cca6e638fbd2d65188ad | Reduce object creation during map (compiler created display class for lambda logging) | David-Desmaisons/Neutronium,David-Desmaisons/Neutronium,NeutroniumCore/Neutronium,NeutroniumCore/Neutronium,NeutroniumCore/Neutronium,David-Desmaisons/Neutronium | Neutronium.Core/Binding/GlueBuilder/GlueObjectBuilder.cs | Neutronium.Core/Binding/GlueBuilder/GlueObjectBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Neutronium.Core.Binding.GlueObject;
using Neutronium.Core.Binding.GlueObject.Factory;
using Neutronium.Core.Infra;
using Neutronium.Core.Infra.Reflection;
namespace Neutronium.Core.Binding.GlueBuilder
{
internal sealed class GlueObjectBuilder
{
private readonly KeyValuePair<string, PropertyAccessor>[] _Properties;
private readonly IWebSessionLogger _Logger;
private readonly CSharpToJavascriptConverter _Converter;
public GlueObjectBuilder(CSharpToJavascriptConverter converter, IWebSessionLogger logger, Type objectType)
{
_Converter = converter;
_Logger = logger;
_Properties = objectType.GetReadProperties().ToArray();
}
public IJsCsGlue Convert(IGlueFactory factory, object @object)
{
var result = factory.Build(@object);
result.SetAttributes(MapNested(@object));
return result;
}
private AttributeDescription[] MapNested(object parentObject)
{
var attributes = new AttributeDescription[_Properties.Length];
var index = 0;
foreach (var propertyInfo in _Properties)
{
var propertyName = propertyInfo.Key;
object childvalue = null;
try
{
childvalue = propertyInfo.Value.Get(parentObject);
}
catch (Exception exception)
{
LogIntrospectionError(propertyName, parentObject, exception);
}
var child = _Converter.Map(childvalue).AddRef();
attributes[index++] = new AttributeDescription(propertyName, child);
}
return attributes;
}
private void LogIntrospectionError(string propertyName, object parentObject, Exception exception)
{
_Logger.Info(() => $"Unable to convert property {propertyName} from {parentObject} of type {parentObject.GetType().FullName} exception {exception.InnerException}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Neutronium.Core.Binding.GlueObject;
using Neutronium.Core.Binding.GlueObject.Factory;
using Neutronium.Core.Infra;
using Neutronium.Core.Infra.Reflection;
namespace Neutronium.Core.Binding.GlueBuilder
{
internal sealed class GlueObjectBuilder
{
private readonly KeyValuePair<string, PropertyAccessor>[] _Properties;
private readonly IWebSessionLogger _Logger;
private readonly CSharpToJavascriptConverter _Converter;
public GlueObjectBuilder(CSharpToJavascriptConverter converter, IWebSessionLogger logger, Type objectType)
{
_Converter = converter;
_Logger = logger;
_Properties = objectType.GetReadProperties().ToArray();
}
public IJsCsGlue Convert(IGlueFactory factory, object @object)
{
var result = factory.Build(@object);
result.SetAttributes(MapNested(@object));
return result;
}
private AttributeDescription[] MapNested(object parentObject)
{
var attributes = new AttributeDescription[_Properties.Length];
var index = 0;
foreach (var propertyInfo in _Properties)
{
var propertyName = propertyInfo.Key;
object childvalue = null;
try
{
childvalue = propertyInfo.Value.Get(parentObject);
}
catch (Exception e)
{
_Logger.Info(() => $"Unable to convert property {propertyName} from {parentObject} of type {parentObject.GetType().FullName} exception {e.InnerException}");
}
var child = _Converter.Map(childvalue).AddRef();
attributes[index++] = new AttributeDescription(propertyName, child);
}
return attributes;
}
}
}
| mit | C# |
131677ced7f3b4607d50fe8456082774edabe94a | Simplify names | sharwell/StyleCop.Analyzers.Status,DotNetAnalyzers/StyleCopAnalyzers,pdelvo/StyleCop.Analyzers.Status,pdelvo/StyleCop.Analyzers.Status,pdelvo/StyleCop.Analyzers.Status,sharwell/StyleCop.Analyzers.Status,sharwell/StyleCop.Analyzers.Status | StyleCop.Analyzers.Status.Generator/CompilationFailedException.cs | StyleCop.Analyzers.Status.Generator/CompilationFailedException.cs | namespace StyleCop.Analyzers.Status.Generator
{
using System;
/// <summary>
/// An exception that gets thrown if the compilation failed.
/// </summary>
[Serializable]
public class CompilationFailedException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
public CompilationFailedException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
/// <param name="message">The message that should be reported</param>
public CompilationFailedException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
/// <param name="message">The message that should be reported</param>
/// <param name="inner">The exception that caused this exception to be thrown</param>
public CompilationFailedException(string message, Exception inner) : base(message, inner)
{
}
}
}
| namespace StyleCop.Analyzers.Status.Generator
{
using System;
/// <summary>
/// An exception that gets thrown if the compilation failed.
/// </summary>
[Serializable]
public class CompilationFailedException : System.Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
public CompilationFailedException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
/// <param name="message">The message that should be reported</param>
public CompilationFailedException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompilationFailedException"/> class.
/// </summary>
/// <param name="message">The message that should be reported</param>
/// <param name="inner">The exception that caused this exception to be thrown</param>
public CompilationFailedException(string message, System.Exception inner) : base(message, inner)
{
}
}
}
| mit | C# |
cba8444a635c47cd5e647b4d65c21ca7c9e7209e | Stop testing for image shrinking, as we've disabled shrinking. | gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork | src/BloomTests/LowResImageProcessing/RuntimeImageProcessingTests.cs | src/BloomTests/LowResImageProcessing/RuntimeImageProcessingTests.cs | using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Bloom;
using NUnit.Framework;
using Palaso.IO;
using Bloom.ImageProcessing;
namespace BloomTests.RuntimeImageProcessing
{
[TestFixture]
public class RuntimeImageProcessingTests
{
#if ShrinkLargeImages
[Test]
public void GetWideImage_ReturnsShrunkImageWithCorrectProportions()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempPNGImage(200,80))
{
using(var img = Image.FromFile(cache.GetPathToResizedImage(file.Path)))
{
Assert.AreEqual(100, img.Width);
Assert.AreEqual(40, img.Height);
}
}
}
[Test]
public void GetJPG_ReturnsShrunkJPG()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempJPGImage(200, 80))
{
var pathToResizedImage = cache.GetPathToResizedImage(file.Path);
using (var img = Image.FromFile(pathToResizedImage))
{
Assert.AreEqual(".jpg", Path.GetExtension(pathToResizedImage));
//TODO: why does this always report PNG format? Checks by hand of the file show it as jpg
//Assert.AreEqual(ImageFormat.Jpeg.Guid, img.RawFormat.Guid);
Assert.AreEqual(100, img.Width);
Assert.AreEqual(40, img.Height);
}
}
}
#endif
[Test]
public void GetTinyImage_DoesNotChangeSize()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempPNGImage(10,10))
{
using (var img = Image.FromFile(cache.GetPathToResizedImage(file.Path)))
{
Assert.AreEqual(10, img.Width);
}
}
}
private TempFile MakeTempPNGImage(int width, int height)
{
var file = TempFile.WithExtension(".png");
File.Delete(file.Path);
using (var x = new Bitmap(width, height))
{
x.Save(file.Path, ImageFormat.Png);
}
return file;
}
private TempFile MakeTempJPGImage(int width, int height)
{
var file = TempFile.WithExtension(".jpg");
File.Delete(file.Path);
using (var x = new Bitmap(width, height))
{
x.Save(file.Path, ImageFormat.Jpeg);
}
return file;
}
}
}
| using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Bloom;
using NUnit.Framework;
using Palaso.IO;
using Bloom.ImageProcessing;
namespace BloomTests.RuntimeImageProcessing
{
[TestFixture]
public class RuntimeImageProcessingTests
{
[Test]
public void GetWideImage_ReturnsShrunkImageWithCorrectProportions()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempPNGImage(200,80))
{
using(var img = Image.FromFile(cache.GetPathToResizedImage(file.Path)))
{
Assert.AreEqual(100, img.Width);
Assert.AreEqual(40, img.Height);
}
}
}
/* we're not shrinking at the moment
[Test]
public void GetJPG_ReturnsShrunkJPG()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempJPGImage(200, 80))
{
var pathToResizedImage = cache.GetPathToResizedImage(file.Path);
using (var img = Image.FromFile(pathToResizedImage))
{
Assert.AreEqual(".jpg", Path.GetExtension(pathToResizedImage));
//TODO: why does this always report PNG format? Checks by hand of the file show it as jpg
//Assert.AreEqual(ImageFormat.Jpeg.Guid, img.RawFormat.Guid);
Assert.AreEqual(100, img.Width);
Assert.AreEqual(40, img.Height);
}
}
}*/
[Test]
public void GetTinyImage_DoesNotChangeSize()
{
using (var cache = new RuntimeImageProcessor(new BookRenamedEvent()) { TargetDimension = 100 })
using (var file = MakeTempPNGImage(10,10))
{
using (var img = Image.FromFile(cache.GetPathToResizedImage(file.Path)))
{
Assert.AreEqual(10, img.Width);
}
}
}
private TempFile MakeTempPNGImage(int width, int height)
{
var file = TempFile.WithExtension(".png");
File.Delete(file.Path);
using (var x = new Bitmap(width, height))
{
x.Save(file.Path, ImageFormat.Png);
}
return file;
}
private TempFile MakeTempJPGImage(int width, int height)
{
var file = TempFile.WithExtension(".jpg");
File.Delete(file.Path);
using (var x = new Bitmap(width, height))
{
x.Save(file.Path, ImageFormat.Jpeg);
}
return file;
}
}
}
| mit | C# |
89295bbdbb09a53e644b746a822dd615606358e1 | correct IAmVisualElement.Text() for text, ddl, check, radio | mvbalaw/FluentBrowserAutomation | src/FluentBrowserAutomation/Controls/Properties/IAmVisualElement.cs | src/FluentBrowserAutomation/Controls/Properties/IAmVisualElement.cs | using System;
using System.Linq;
using FluentBrowserAutomation.Accessors;
using FluentBrowserAutomation.Controls;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
//// ReSharper disable CheckNamespace
// ReSharper disable CheckNamespace
namespace FluentBrowserAutomation
// ReSharper restore CheckNamespace
//// ReSharper restore CheckNamespace
{
public interface IAmVisualElement : IHaveBasicInfo
{
}
public static class IAmVisualElementExtensions
{
public static void Focus(this IAmVisualElement element)
{
var action = new Actions(element.BrowserContext.Browser);
action.MoveToElement(element.Element).Perform();
}
public static void MoveMouseToIt(this IAmVisualElement element)
{
element.ScrollToIt();
element.Focus();
}
public static void ScrollToIt(this IAmVisualElement element)
{
var browser = element.BrowserContext.Browser;
var windowSize = browser.Manage().Window.Size;
var currentScreenLocation = ((ILocatable)browser.SwitchTo().ActiveElement()).LocationOnScreenOnceScrolledIntoView;
var elementPosition = ((ILocatable)element.Element).LocationOnScreenOnceScrolledIntoView;
var offset = windowSize.Height / 4;
var yOffset = currentScreenLocation.Y < elementPosition.Y ? offset : -offset;
var yPosition = elementPosition.Y + yOffset;
if (yPosition < 0)
{
yPosition = 0;
}
else if (yPosition > windowSize.Height)
{
yPosition = windowSize.Height;
}
var js = String.Format("window.scroll({0}, {1})", elementPosition.X, yPosition);
((IJavaScriptExecutor)browser).ExecuteScript(js);
}
public static ReadOnlyText Text(this IAmVisualElement input)
{
var textField = input as TextBoxWrapper;
if (textField != null)
{
input.Exists().ShouldBeTrue();
input.IsVisible().ShouldBeTrue();
return textField.Text();
}
var dropDown = input as DropDownListWrapper;
if (dropDown != null)
{
input.Exists().ShouldBeTrue();
input.IsVisible().ShouldBeTrue();
var selectedTexts = dropDown.GetSelectedTexts().ToArray();
if (selectedTexts.Length != 1)
{
throw new ArgumentException("drop down list " + input.HowFound + " must have exactly 1 selected value to call .Text()");
}
return new ReadOnlyText(input.HowFound, selectedTexts[0]);
}
var checkBoxOrRadio = input as IAmToggleableInput;
if (checkBoxOrRadio != null)
{
input.Exists().ShouldBeTrue();
input.IsVisible().ShouldBeTrue();
return new ReadOnlyText(input.HowFound, input.Element.GetAttribute("value"));
}
var text = input.Element.Text;
return new ReadOnlyText(input.HowFound, text);
}
}
} | using System;
using FluentBrowserAutomation.Accessors;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
//// ReSharper disable CheckNamespace
// ReSharper disable CheckNamespace
namespace FluentBrowserAutomation
// ReSharper restore CheckNamespace
//// ReSharper restore CheckNamespace
{
public interface IAmVisualElement : IHaveBasicInfo
{
}
public static class IAmVisualElementExtensions
{
public static void Focus(this IAmVisualElement element)
{
var action = new Actions(element.BrowserContext.Browser);
action.MoveToElement(element.Element).Perform();
}
public static void MoveMouseToIt(this IAmVisualElement element)
{
element.ScrollToIt();
element.Focus();
}
public static void ScrollToIt(this IAmVisualElement element)
{
var browser = element.BrowserContext.Browser;
var windowSize = browser.Manage().Window.Size;
var currentScreenLocation = ((ILocatable)browser.SwitchTo().ActiveElement()).LocationOnScreenOnceScrolledIntoView;
var elementPosition = ((ILocatable)element.Element).LocationOnScreenOnceScrolledIntoView;
var offset = windowSize.Height / 4;
var yOffset = currentScreenLocation.Y < elementPosition.Y ? offset : -offset;
var yPosition = elementPosition.Y + yOffset;
if (yPosition < 0)
{
yPosition = 0;
}
else if (yPosition > windowSize.Height)
{
yPosition = windowSize.Height;
}
var js = String.Format("window.scroll({0}, {1})", elementPosition.X, yPosition);
((IJavaScriptExecutor)browser).ExecuteScript(js);
}
public static ReadOnlyText Text(this IAmVisualElement element)
{
var text = element.Element.Text;
return new ReadOnlyText(element.HowFound, text);
}
}
} | mit | C# |
55fa223d7360f45d6c5c84d2cece175c8e851304 | Update ServiceCollectionExtensions.cs (#2137) | stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard | src/OrchardCore/OrchardCore.Entities/ServiceCollectionExtensions.cs | src/OrchardCore/OrchardCore.Entities/ServiceCollectionExtensions.cs | using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OrchardCore.Entities.Scripting;
using OrchardCore.Scripting;
namespace OrchardCore.Entities
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddIdGeneration(this IServiceCollection services)
{
services.TryAddSingleton<IIdGenerator, DefaultIdGenerator>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<IGlobalMethodProvider, IdGeneratorMethod>());
return services;
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OrchardCore.Entities.Scripting;
using OrchardCore.Scripting;
namespace OrchardCore.Entities
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddIdGeneration(this IServiceCollection services)
{
services.TryAddSingleton<IIdGenerator, DefaultIdGenerator>();
services.TryAddSingleton<IGlobalMethodProvider, IdGeneratorMethod>();
return services;
}
}
} | bsd-3-clause | C# |
c5c75025c652b55db6dc1f660e5db43bcb918efd | Add Fsm variable for text/initials | missionpinball/unity-bcp-server | Assets/BCP/Scripts/PlayMaker/SendBCPInputHighScoreComplete.cs | Assets/BCP/Scripts/PlayMaker/SendBCPInputHighScoreComplete.cs | using UnityEngine;
using System;
using HutongGames.PlayMaker;
using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute;
using BCP.SimpleJSON;
/// <summary>
/// Custom PlayMaker action for MPF that sends a Trigger BCP command to MPF.
/// </summary>
[ActionCategory("BCP")]
[Tooltip("Sends 'text_input_high_score_complete' Trigger BCP command to MPF.")]
public class SendBCPInputHighScoreComplete : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The variable containing text initials of the high score player to send to MPF")]
public FsmString text;
/// <summary>
/// Resets this instance to default values.
/// </summary>
public override void Reset()
{
text = null;
}
/// <summary>
/// Called when the state becomes active. Sends the BCP Trigger command to MPF.
/// </summary>
public override void OnEnter()
{
BcpMessage message = BcpMessage.TriggerMessage("text_input_high_score_complete");
message.Parameters["text"] = new JSONString(text.Value);
BcpServer.Instance.Send(message);
Finish();
}
}
| using UnityEngine;
using System;
using HutongGames.PlayMaker;
using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute;
using BCP.SimpleJSON;
/// <summary>
/// Custom PlayMaker action for MPF that sends a Trigger BCP command to MPF.
/// </summary>
[ActionCategory("BCP")]
[Tooltip("Sends 'text_input_high_score_complete' Trigger BCP command to MPF.")]
public class SendBCPInputHighScoreComplete : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The text initials of the high score player to send to MPF")]
public string text;
/// <summary>
/// Resets this instance to default values.
/// </summary>
public override void Reset()
{
text = null;
}
/// <summary>
/// Called when the state becomes active. Sends the BCP Trigger command to MPF.
/// </summary>
public override void OnEnter()
{
BcpMessage message = BcpMessage.TriggerMessage("text_input_high_score_complete");
message.Parameters["text"] = new JSONString(text);
BcpServer.Instance.Send(message);
Finish();
}
}
| mit | C# |
939d6c6a78a8376fa0525d6f6236c6add47894e9 | Add comments | BYVoid/distribox | Distribox/Distribox.CommonLib/VersionSystem/FileSubversion.cs | Distribox/Distribox.CommonLib/VersionSystem/FileSubversion.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Distribox.CommonLib
{
/// <summary>
/// File subversion type.
/// </summary>
public enum FileSubversionType
{
Created, Changed, Renamed, Deleted
}
/// <summary>
/// File subversion.
/// </summary>
public class FileSubversion
{
public string Name { get; set; }
public string SHA1 { get; set; }
public DateTime LastModify { get; set; }
public FileSubversionType Type { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Distribox.CommonLib
{
public enum FileSubversionType
{
Created, Changed, Renamed, Deleted
}
public class FileSubversion
{
public string Name { get; set; }
public string SHA1 { get; set; }
public DateTime LastModify { get; set; }
public FileSubversionType Type { get; set; }
}
}
| mit | C# |
95537838d81dd19b667611c129d8752b2c327caf | Add changing color of FPS Display based on FPS | fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/DebugConsole/DebugConsole.cs | UnityProject/Assets/Scripts/DebugConsole/DebugConsole.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DebugConsole : MonoBehaviour
{
private static DebugConsole debugConsole;
public static DebugConsole Instance
{
get
{
if (debugConsole == null)
{
debugConsole = FindObjectOfType<DebugConsole>();
}
return debugConsole;
}
}
protected static string DebugLog { get; private set; }
protected static string LastLog { get; private set; }
public Text displayText;
public Text fpsText;
public GameObject consoleObject;
bool isOpened = false;
public static void AmendLog(string msg)
{
DebugLog += msg + "\n";
LastLog = msg;
if (DebugLog.Length > 3000)
{
DebugLog = DebugLog.Substring(1500);
}
//if it is null it means the object is still disabled and is about be enabled
if (Instance != null)
{
Instance.RefreshLogDisplay();
}
}
void Start()
{
Instance.consoleObject.SetActive(false);
Instance.isOpened = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.F5))
{
ToggleConsole();
}
if (isOpened) {
var fps = 1f / Time.deltaTime;
fpsText.text = "FPS: " + fps.ToString("N1");
fpsText.color =
fps < 25 ? Color.red :
fps < 55 ? Color.yellow :
Color.green;
fpsText.color /= 2; //Decrease saturation
}
}
void ToggleConsole()
{
isOpened = !isOpened;
consoleObject.SetActive(isOpened);
}
void RefreshLogDisplay()
{
Instance.displayText.text = DebugLog;
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DebugConsole : MonoBehaviour
{
private static DebugConsole debugConsole;
public static DebugConsole Instance
{
get
{
if (debugConsole == null)
{
debugConsole = FindObjectOfType<DebugConsole>();
}
return debugConsole;
}
}
protected static string DebugLog { get; private set; }
protected static string LastLog { get; private set; }
public Text displayText;
public Text fpsText;
public GameObject consoleObject;
bool isOpened = false;
public static void AmendLog(string msg)
{
DebugLog += msg + "\n";
LastLog = msg;
if (DebugLog.Length > 3000)
{
DebugLog = DebugLog.Substring(1500);
}
//if it is null it means the object is still disabled and is about be enabled
if (Instance != null)
{
Instance.RefreshLogDisplay();
}
}
void Start()
{
Instance.consoleObject.SetActive(false);
Instance.isOpened = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.F5))
{
ToggleConsole();
}
if(isOpened)fpsText.text = "FPS: " + (1f / Time.deltaTime).ToString("N1");
}
void ToggleConsole()
{
isOpened = !isOpened;
consoleObject.SetActive(isOpened);
}
void RefreshLogDisplay()
{
Instance.displayText.text = DebugLog;
}
} | agpl-3.0 | C# |
885b571f59c4957488c0f57c959a893bb9e1c6ab | call update profile in view | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | XamarinApp/MyTrips/MyTrips.UWP/Views/ProfileView.xaml.cs | XamarinApp/MyTrips/MyTrips.UWP/Views/ProfileView.xaml.cs | using MyTrips.ViewModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MyTrips.UWP.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ProfileView : Page
{
ProfileViewModel profileViewModel;
public ProfileView()
{
profileViewModel = new ProfileViewModel();
DataContext = profileViewModel;
this.InitializeComponent();
TotalDistanceTab.Title1 = "Total";
TotalDistanceTab.Title2 = "DISTANCE";
TotalTimeTab.Title1 = "Total";
TotalTimeTab.Title2 = "TIME";
AvgSpeedTab.Title1 = "Avg";
AvgSpeedTab.Title2 = "SPEED";
HardBreaksTab.Title1 = "Hard";
HardBreaksTab.Title2 = "BREAKS";
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await profileViewModel.UpdateProfileAsync();
}
}
}
| using MyTrips.ViewModel;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MyTrips.UWP.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ProfileView : Page
{
ProfileViewModel profileViewModel;
public ProfileView()
{
profileViewModel = new ProfileViewModel();
DataContext = profileViewModel;
this.InitializeComponent();
//profileViewModel.DrivingSkills = new System.Random().Next(0, 100);
profileViewModel.DrivingSkills = 86;
TotalDistanceTab.Title1 = "Total";
TotalDistanceTab.Title2 = "DISTANCE";
TotalTimeTab.Title1 = "Total";
TotalTimeTab.Title2 = "TIME";
AvgSpeedTab.Title1 = "Avg";
AvgSpeedTab.Title2 = "SPEED";
HardBreaksTab.Title1 = "Hard";
HardBreaksTab.Title2 = "BREAKS";
//TipsTab.Title1 = "TIPS";
}
}
}
| mit | C# |
63381ff4f2a62335e851f266f84f8f422ec68e01 | change heading font weight | peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownHeading.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownHeading.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 Markdig.Syntax;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownHeading : MarkdownHeading
{
private readonly int level;
public OsuMarkdownHeading(HeadingBlock headingBlock)
: base(headingBlock)
{
level = headingBlock.Level;
}
public override MarkdownTextFlowContainer CreateTextFlow() => new HeadingTextFlowContainer
{
Weight = GetFontWeightByLevel(level),
};
protected override float GetFontSizeByLevel(int level)
{
const float base_font_size = 14;
switch (level)
{
case 1:
return 30 / base_font_size;
case 2:
return 26 / base_font_size;
case 3:
return 20 / base_font_size;
case 4:
return 18 / base_font_size;
case 5:
return 16 / base_font_size;
default:
return 1;
}
}
protected virtual FontWeight GetFontWeightByLevel(int level)
{
switch (level)
{
case 1:
case 2:
return FontWeight.SemiBold;
default:
return FontWeight.Bold;
}
}
private class HeadingTextFlowContainer : OsuMarkdownTextFlowContainer
{
public FontWeight Weight { get; set; }
protected override SpriteText CreateSpriteText()
{
var spriteText = base.CreateSpriteText();
spriteText.Font = spriteText.Font.With(weight: Weight);
return spriteText;
}
}
}
}
| // 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 Markdig.Syntax;
using osu.Framework.Graphics.Containers.Markdown;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownHeading : MarkdownHeading
{
public OsuMarkdownHeading(HeadingBlock headingBlock)
: base(headingBlock)
{
}
protected override float GetFontSizeByLevel(int level)
{
const float base_font_size = 14;
switch (level)
{
case 1:
return 30 / base_font_size;
case 2:
return 26 / base_font_size;
case 3:
return 20 / base_font_size;
case 4:
return 18 / base_font_size;
case 5:
return 16 / base_font_size;
default:
return 1;
}
}
}
}
| mit | C# |
3676eac0b17d929f3a93ba43985a501b1d064096 | Update CloudSecureOptions.cs | A51UK/File-Repository | File-Repository/Enum/CloudSecureOptions.cs | File-Repository/Enum/CloudSecureOptions.cs | /*
* Copyright 2017 Craig Lee Mark Adams
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.Collections.Generic;
using System.Text;
namespace File_Repository
{
public enum CloudSecureOptions
{
defualt,
file
}
}
| /*
* Copyright 2017 Criag Lee Mark Adams
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.Collections.Generic;
using System.Text;
namespace File_Repository
{
public enum CloudSecureOptions
{
defualt,
file
}
}
| apache-2.0 | C# |
5e42aeb043f0f9c5f588cdc9f54a698e816c3ada | Update HalJsonMediaTypeFormatter for serialisation | aliencube/Aliencube.WebApi.Hal,aliencube/Aliencube.WebApi.Hal | src/Aliencube.WebApi.Hal/Formatters/HalJsonMediaTypeFormatter.cs | src/Aliencube.WebApi.Hal/Formatters/HalJsonMediaTypeFormatter.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using Aliencube.WebApi.Hal.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Aliencube.WebApi.Hal.Formatters
{
public class HalJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public HalJsonMediaTypeFormatter()
{
this.SetSupportedMediaTypes();
}
public override bool CanReadType(Type type)
{
var isSupportedType = IsSupportedType(type);
return isSupportedType;
}
public override bool CanWriteType(Type type)
{
var isSupportedType = IsSupportedType(type);
return isSupportedType;
}
public override void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)
{
base.WriteToStream(type, value, writeStream, effectiveEncoding);
var formatting = this.Indent ? Formatting.Indented : Formatting.None;
var so = this.SerializerSettings == null
? JsonConvert.SerializeObject(value, formatting)
: JsonConvert.SerializeObject(value, formatting, this.SerializerSettings);
var jo = JObject.Parse(so);
var resource = value as LinkedResource;
if (resource == null)
{
return;
}
var links = resource.Links.Select(p => new KeyValuePair<string, object>(p.Rel, new { href = p.Href }));
var sls = this.SerializerSettings == null
? JsonConvert.SerializeObject(links, formatting)
: JsonConvert.SerializeObject(links, formatting, this.SerializerSettings);
var jlo = JObject.Parse(sls);
jo["_links"] = jlo;
using (var sw = new StreamWriter(writeStream))
using (var writer = new JsonTextWriter(sw))
{
jo.WriteTo(writer);
}
}
//public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
// TransportContext transportContext)
//{
// return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
//}
//public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
// TransportContext transportContext, CancellationToken cancellationToken)
//{
// return base.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken);
//}
private void SetSupportedMediaTypes()
{
this.SupportedMediaTypes.Clear();
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/hal+json"));
}
private static bool IsSupportedType(Type type)
{
var isLinkedResourceType = type.IsSubclassOf(typeof(LinkedResource));
return isLinkedResourceType;
}
}
} | using System;
using System.Net.Http.Formatting;
namespace Aliencube.WebApi.Hal.Formatters
{
public class HalJsonMediaTypeFormatter : BufferedMediaTypeFormatter
{
public override bool CanReadType(Type type)
{
throw new NotImplementedException();
}
public override bool CanWriteType(Type type)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
30c5c4e7b417045728b4089c61d7978da6fa89bf | Remove old points from back | petereichinger/unity-trail-advanced | Assets/Scripts/PointSource/AbstractPointSource.cs | Assets/Scripts/PointSource/AbstractPointSource.cs | using Nito;
using System.Collections;
using System.Net.NetworkInformation;
using UnityEngine;
namespace TrailAdvanced.PointSource {
public abstract class AbstractPointSource : MonoBehaviour {
public int maxPoints = 1000;
protected Deque<Vector3> points;
protected int minimumFreeCapacity = 10;
public Deque<Vector3> GetPoints() {
return points;
}
protected virtual void Start() {
points = new Deque<Vector3>(maxPoints);
}
protected virtual void Update() {
int count = points.Count - (points.Capacity - minimumFreeCapacity);
if (count > 0) {
points.RemoveRange(points.Count - count, count);
}
}
}
}
| using Nito;
using System.Collections;
using System.Net.NetworkInformation;
using UnityEngine;
namespace TrailAdvanced.PointSource {
public abstract class AbstractPointSource : MonoBehaviour {
public int maxPoints = 1000;
protected Deque<Vector3> points;
protected int minimumFreeCapacity = 10;
public Deque<Vector3> GetPoints() {
return points;
}
protected virtual void Start() {
points = new Deque<Vector3>(maxPoints);
}
protected virtual void Update() {
int count = points.Count - (points.Capacity - minimumFreeCapacity);
if (count > 0) {
points.RemoveRange(0, count);
}
}
}
} | mit | C# |
654c38a9d20b407a08213c829d4968723303a36e | Fix missing } | projectkudu/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS | SimpleWAWS/Code/SimpleSettings.cs | SimpleWAWS/Code/SimpleSettings.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Hosting;
namespace SimpleWAWS.Code
{
public static class SimpleSettings
{
private static string config(string @default = null, [CallerMemberName] string key = null)
{
var value = System.Environment.GetEnvironmentVariable(key) ?? ConfigurationManager.AppSettings[key];
return string.IsNullOrEmpty(value)
? @default
: value;
}
public static string TryTenantId { get { return config(); } }
public static string TryTenantName { get { return config(); } }
public static string SiteExpiryMinutes { get { return config("60"); } }
public static string GeoRegions { get { return config("East US,West US,North Europe,West Europe,South Central US,North Central US,East Asia,Southeast Asia,Japan West,Japan East,Brazil South"); } }
public static string TryUserName { get { return config(); } }
public static string TryPassword { get { return config(); } }
public static string Subscriptions { get { return config(); } }
public static string FreeSitesIISLogsBlob { get { return config(); } }
public static string FreeSitesIISLogsQueue { get { return config(); } }
public static string StorageConnectionString { get { return config(); } }
public static string DocumentDbUrl { get { return config(); } }
public static string DocumentDbKey { get { return config(); } }
public static string FromEmail { get { return config(); } }
public static string EmailServer { get { return config(); } }
public static string EmailUserName { get { return config(); } }
public static string EmailPassword { get { return config(); } }
public static string ToEmails { get { return config(); } }
public static string SearchServiceName { get { return config(); } }
public static string SearchServiceApiKeys { get { return config(); } }
public static string ExtendedResourceExpireHours { get { return config("24"); } }
private const string CommonApiAppsCsmTemplatePathLocal = @"C:\Users\fashaikh\Documents\GitHub\SimpleWAWS\SimpleWAWS\CSMTemplates\commonApiApps.json";
private const string AppDataPathLocal = @"C:\Users\fashaikh\Documents\GitHub\SimpleWAWS\SimpleWAWS\App_Data\";
public static string CommonApiAppsCsmTemplatePath { get; } = HostingEnvironment.MapPath("~/CSMTemplates/commonApiApps.json") ?? CommonApiAppsCsmTemplatePathLocal;
public static string AppDataPath { get; } = HostingEnvironment.MapPath(@"~/App_Data/")?? AppDataPathLocal;
public static string ElasticSearchUri = "http://10.0.0.4:9200";
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Hosting;
namespace SimpleWAWS.Code
{
public static class SimpleSettings
{
private static string config(string @default = null, [CallerMemberName] string key = null)
{
var value = System.Environment.GetEnvironmentVariable(key) ?? ConfigurationManager.AppSettings[key];
return string.IsNullOrEmpty(value)
? @default
: value;
}
public static string TryTenantId { get { return config(); } }
public static string TryTenantName { get { return config(); } }
public static string SiteExpiryMinutes { get { return config("60"); } }
public static string GeoRegions { get { return config("East US,West US,North Europe,West Europe,South Central US,North Central US,East Asia,Southeast Asia,Japan West,Japan East,Brazil South"); } }
public static string TryUserName { get { return config(); } }
public static string TryPassword { get { return config(); } }
public static string Subscriptions { get { return config(); } }
public static string FreeSitesIISLogsBlob { get { return config(); } }
public static string FreeSitesIISLogsQueue { get { return config(); } }
public static string StorageConnectionString { get { return config(); } }
public static string DocumentDbUrl { get { return config(); } }
public static string DocumentDbKey { get { return config(); } }
public static string FromEmail { get { return config(); } }
public static string EmailServer { get { return config(); } }
public static string EmailUserName { get { return config(); } }
public static string EmailPassword { get { return config(); } }
public static string ToEmails { get { return config(); } }
public static string SearchServiceName { get { return config(); } }
public static string SearchServiceApiKeys { get { return config(); } }
public static string ExtendedResourceExpireHours { get { return config("24"); } }
private const string CommonApiAppsCsmTemplatePathLocal = @"C:\Users\fashaikh\Documents\GitHub\SimpleWAWS\SimpleWAWS\CSMTemplates\commonApiApps.json";
private const string AppDataPathLocal = @"C:\Users\fashaikh\Documents\GitHub\SimpleWAWS\SimpleWAWS\App_Data\";
public static string CommonApiAppsCsmTemplatePath { get; } = HostingEnvironment.MapPath("~/CSMTemplates/commonApiApps.json") ?? CommonApiAppsCsmTemplatePathLocal;
public static string AppDataPath { get; } = HostingEnvironment.MapPath(@"~/App_Data/")?? AppDataPathLocal;
public static string ElasticSearchUri = "http://10.0.0.4:9200";
}
}
} | apache-2.0 | C# |
3a2a79ebbe7d86800e2067eed8caec9aa0d17a6b | Refactor around parametersToTidy-tracking forgot to initialise the collection! | ProductiveRage/SqlProxyAndReplay | DataProviderInterface/Implementations/SqlProxy.cs | DataProviderInterface/Implementations/SqlProxy.cs | using System;
using System.Data;
using System.Data.SqlClient;
using ProductiveRage.SqlProxyAndReplay.DataProviderInterface.IDs;
using ProductiveRage.SqlProxyAndReplay.DataProviderInterface.Interfaces;
namespace ProductiveRage.SqlProxyAndReplay.DataProviderInterface.Implementations
{
public sealed partial class SqlProxy : ISqlProxy
{
private readonly Store<ConnectionId, SqlConnection> _connectionStore;
private readonly Store<CommandId, IDbCommand> _commandStore;
private readonly Store<TransactionId, IDbTransaction> _transactionStore;
private readonly Store<ParameterId, IDbDataParameter> _parameterStore;
private readonly Store<DataReaderId, IDataReader> _readerStore;
private readonly ConcurrentParameterToCommandLookup _parametersToTidy;
public SqlProxy(
Store<ConnectionId, SqlConnection> connectionStore,
Store<CommandId, IDbCommand> commandStore,
Store<TransactionId, IDbTransaction> transactionStore,
Store<ParameterId, IDbDataParameter> parameterStore,
Store<DataReaderId, IDataReader> readerStore)
{
if (connectionStore == null)
throw new ArgumentNullException(nameof(connectionStore));
if (commandStore == null)
throw new ArgumentNullException(nameof(commandStore));
if (transactionStore == null)
throw new ArgumentNullException(nameof(transactionStore));
if (parameterStore == null)
throw new ArgumentNullException(nameof(parameterStore));
if (readerStore == null)
throw new ArgumentNullException(nameof(readerStore));
_connectionStore = connectionStore;
_commandStore = commandStore;
_transactionStore = transactionStore;
_parameterStore = parameterStore;
_readerStore = readerStore;
// Parameters are not disposed of individually (unlike connections, commands, transactions and readers) - instead, the parameters in
// the parameter store must be removed when the command that created them is disposed. The information to do that is recorded here.
_parametersToTidy = new ConcurrentParameterToCommandLookup();
}
public SqlProxy() : this(
DefaultStores.ConnectionStore,
DefaultStores.CommandStore,
DefaultStores.TransactionStore,
DefaultStores.ParameterStore,
DefaultStores.ReaderStore) { }
}
}
| using System;
using System.Data;
using System.Data.SqlClient;
using ProductiveRage.SqlProxyAndReplay.DataProviderInterface.IDs;
using ProductiveRage.SqlProxyAndReplay.DataProviderInterface.Interfaces;
namespace ProductiveRage.SqlProxyAndReplay.DataProviderInterface.Implementations
{
public sealed partial class SqlProxy : ISqlProxy
{
private readonly Store<ConnectionId, SqlConnection> _connectionStore;
private readonly Store<CommandId, IDbCommand> _commandStore;
private readonly Store<TransactionId, IDbTransaction> _transactionStore;
private readonly Store<ParameterId, IDbDataParameter> _parameterStore;
private readonly Store<DataReaderId, IDataReader> _readerStore;
private readonly ConcurrentParameterToCommandLookup _parametersToTidy;
public SqlProxy(
Store<ConnectionId, SqlConnection> connectionStore,
Store<CommandId, IDbCommand> commandStore,
Store<TransactionId, IDbTransaction> transactionStore,
Store<ParameterId, IDbDataParameter> parameterStore,
Store<DataReaderId, IDataReader> readerStore)
{
if (connectionStore == null)
throw new ArgumentNullException(nameof(connectionStore));
if (commandStore == null)
throw new ArgumentNullException(nameof(commandStore));
if (transactionStore == null)
throw new ArgumentNullException(nameof(transactionStore));
if (parameterStore == null)
throw new ArgumentNullException(nameof(parameterStore));
if (readerStore == null)
throw new ArgumentNullException(nameof(readerStore));
_connectionStore = connectionStore;
_commandStore = commandStore;
_transactionStore = transactionStore;
_parameterStore = parameterStore;
_readerStore = readerStore;
// Parameters are not disposed of individually (unlike connections, commands, transactions and readers) - instead, the parameters in
// the parameter store must be removed when the command that created them is disposed. The information to do that is recorded here.
}
public SqlProxy() : this(
DefaultStores.ConnectionStore,
DefaultStores.CommandStore,
DefaultStores.TransactionStore,
DefaultStores.ParameterStore,
DefaultStores.ReaderStore) { }
}
}
| mit | C# |
187b628e72587c06c1626790ef8827f0de522e2c | handle null project paths in solution | KevinRansom/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,dotnet/roslyn,diryboy/roslyn,diryboy/roslyn,weltkante/roslyn,dotnet/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,diryboy/roslyn | src/EditorFeatures/Core/EditorConfigSettings/Extensions/SolutionExtensions.cs | src/EditorFeatures/Core/EditorConfigSettings/Extensions/SolutionExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.IO;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions
{
internal static class SolutionExtensions
{
public static ImmutableArray<Project> GetProjectsForPath(this Solution solution, string givenPath)
{
if (Path.GetDirectoryName(givenPath) is not string givenFolderPath ||
solution.FilePath is not string solutionFilePath ||
new DirectoryInfo(solutionFilePath).Parent is not DirectoryInfo solutionParentDirectory ||
new DirectoryInfo(givenFolderPath).FullName == solutionParentDirectory.FullName)
{
return solution.Projects.ToImmutableArray();
}
var builder = ArrayBuilder<Project>.GetInstance();
foreach (var project in solution.Projects)
{
if (project.FilePath is not string projectFilePath ||
new DirectoryInfo(projectFilePath).Parent is not DirectoryInfo projectDirectoryPath)
{
continue;
}
if (ContainsPath(new DirectoryInfo(givenFolderPath), projectDirectoryPath))
{
builder.Add(project);
}
}
return builder.ToImmutableAndFree();
static bool ContainsPath(DirectoryInfo givenPath, DirectoryInfo projectPath)
{
if (projectPath.FullName == givenPath.FullName)
{
return true;
}
while (projectPath.Parent is not null)
{
if (projectPath.Parent.FullName == givenPath.FullName)
{
return true;
}
projectPath = projectPath.Parent;
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions
{
internal static class SolutionExtensions
{
public static ImmutableArray<Project> GetProjectsForPath(this Solution solution, string givenPath)
{
if (Path.GetDirectoryName(givenPath) is not string givenFolderPath ||
solution.FilePath is null)
{
return solution.Projects.ToImmutableArray();
}
var givenFolder = new DirectoryInfo(givenFolderPath);
if (givenFolder.FullName == (new DirectoryInfo(solution.FilePath).Parent).FullName)
{
return solution.Projects.ToImmutableArray();
}
var builder = ArrayBuilder<Project>.GetInstance();
foreach (var (projectDirectoryPath, project) in solution.Projects.Select(p => (new DirectoryInfo(p.FilePath).Parent, p)))
{
if (ContainsPath(givenFolder, projectDirectoryPath))
{
builder.Add(project);
}
}
return builder.ToImmutableAndFree();
static bool ContainsPath(DirectoryInfo givenPath, DirectoryInfo projectPath)
{
if (projectPath.FullName == givenPath.FullName)
{
return true;
}
while (projectPath.Parent is not null)
{
if (projectPath.Parent.FullName == givenPath.FullName)
{
return true;
}
projectPath = projectPath.Parent;
}
return false;
}
}
}
}
| mit | C# |
d8ceb75ee208d4947be7205531da1a5995518c87 | update model with userId | jamesmontemagno/app-coffeecups | CoffeeCups/Model/CupOfCoffee.cs | CoffeeCups/Model/CupOfCoffee.cs | using System;
using Humanizer;
namespace CoffeeCups
{
public class CupOfCoffee
{
/// <summary>
/// Gets or sets the user identifier.
/// </summary>
/// <value>The user identifier.</value>
[Newtonsoft.Json.JsonProperty("userId")]
public string UserId {get;set;}
[Newtonsoft.Json.JsonProperty("Id")]
public string Id { get; set; }
[Microsoft.WindowsAzure.MobileServices.Version]
public string AzureVersion { get; set; }
/// <summary>
/// Gets or sets the date UTC.
/// </summary>
/// <value>The date UTC.</value>
public DateTime DateUtc { get; set;}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="CoffeeCups.CupOfCoffee"/> made at home.
/// </summary>
/// <value><c>true</c> if made at home; otherwise, <c>false</c>.</value>
public bool MadeAtHome{ get; set; }
/// <summary>
/// Gets or sets the OS of the user
/// </summary>
/// <value>The OS</value>
public string OS { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string DateDisplay { get { return DateUtc.ToLocalTime().ToString("d"); } }
[Newtonsoft.Json.JsonIgnore]
public string TimeDisplay { get { return DateUtc.ToLocalTime().ToString("t"); } }
[Newtonsoft.Json.JsonIgnore]
public string AtHomeDisplay { get { return MadeAtHome ? "Made At Home" : string.Empty; } }
}
}
| using System;
using Humanizer;
namespace CoffeeCups
{
public class CupOfCoffee
{
/// <summary>
/// Gets or sets the user identifier.
/// </summary>
/// <value>The user identifier.</value>
public string UserId {get;set;}
[Newtonsoft.Json.JsonProperty("Id")]
public string Id { get; set; }
[Microsoft.WindowsAzure.MobileServices.Version]
public string AzureVersion { get; set; }
/// <summary>
/// Gets or sets the date UTC.
/// </summary>
/// <value>The date UTC.</value>
public DateTime DateUtc { get; set;}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="CoffeeCups.CupOfCoffee"/> made at home.
/// </summary>
/// <value><c>true</c> if made at home; otherwise, <c>false</c>.</value>
public bool MadeAtHome{ get; set; }
/// <summary>
/// Gets or sets the OS of the user
/// </summary>
/// <value>The OS</value>
public string OS { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string DateDisplay { get { return DateUtc.ToLocalTime().ToString("d"); } }
[Newtonsoft.Json.JsonIgnore]
public string TimeDisplay { get { return DateUtc.ToLocalTime().ToString("t"); } }
[Newtonsoft.Json.JsonIgnore]
public string AtHomeDisplay { get { return MadeAtHome ? "Made At Home" : string.Empty; } }
}
}
| mit | C# |
7c09df44e41adadc3ff6dd5bdaf310a58e3bf611 | Rename Cake's "Restore-NuGet-Packages" step to "Restore" | HangfireIO/Cronos | build.cake | build.cake | #tool "nuget:?package=xunit.runner.console"
#addin "Cake.FileHelpers"
// Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead!
var version = "0.2.0";
var configuration = Argument("configuration", "Release");
var newVersion = Argument("newVersion", version);
var target = Argument("target", "Pack");
Task("Restore")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectory("./build");
StartProcess("dotnet", "clean -c:" + configuration);
});
Task("Version")
.Does(() =>
{
if(newVersion == version) return;
var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}";
var cakeRegex = "var version = \"" + versionRegex + "\"";
ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\"");
ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + "");
});
Task("Build")
.IsDependentOn("Version")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(()=>
{
DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings
{
Configuration = configuration,
ArgumentCustomization = args => args.Append("/p:Version=" + version)
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings
{
Configuration = "Release",
ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false")
});
});
Task("AppVeyor")
.IsDependentOn("Test")
.Does(()=>
{
if (AppVeyor.Environment.Repository.Tag.IsTag)
{
var tagName = AppVeyor.Environment.Repository.Tag.Name;
if(tagName.StartsWith("v"))
{
version = tagName.Substring(1);
}
AppVeyor.UpdateBuildVersion(version);
}
});
Task("Local")
.Does(()=>
{
RunTarget("Test");
});
Task("Pack")
.Does(()=>
{
var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local";
RunTarget(target);
CreateDirectory("build");
Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip");
});
RunTarget(target); | #tool "nuget:?package=xunit.runner.console"
#addin "Cake.FileHelpers"
// Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead!
var version = "0.2.0";
var configuration = Argument("configuration", "Release");
var newVersion = Argument("newVersion", version);
var target = Argument("target", "Pack");
Task("Restore-NuGet-Packages")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectory("./build");
StartProcess("dotnet", "clean -c:" + configuration);
});
Task("Version")
.Does(() =>
{
if(newVersion == version) return;
var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}";
var cakeRegex = "var version = \"" + versionRegex + "\"";
ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\"");
ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + "");
});
Task("Build")
.IsDependentOn("Version")
.IsDependentOn("Clean")
.IsDependentOn("Restore-NuGet-Packages")
.Does(()=>
{
DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings
{
Configuration = configuration,
ArgumentCustomization = args => args.Append("/p:Version=" + version)
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings
{
Configuration = "Release",
ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false")
});
});
Task("AppVeyor")
.IsDependentOn("Test")
.Does(()=>
{
if (AppVeyor.Environment.Repository.Tag.IsTag)
{
var tagName = AppVeyor.Environment.Repository.Tag.Name;
if(tagName.StartsWith("v"))
{
version = tagName.Substring(1);
}
AppVeyor.UpdateBuildVersion(version);
}
});
Task("Local")
.Does(()=>
{
RunTarget("Test");
});
Task("Pack")
.Does(()=>
{
var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local";
RunTarget(target);
CreateDirectory("build");
Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip");
});
RunTarget(target); | mit | C# |
54738bb5d84bf30e4543e7bc761eaacf2fbc38e8 | Bump WebApi to 5.10.3 | MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net | Mindscape.Raygun4Net.WebApi/Properties/AssemblyVersionInfo.cs | Mindscape.Raygun4Net.WebApi/Properties/AssemblyVersionInfo.cs | using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.10.3.0")]
[assembly: AssemblyFileVersion("5.10.3.0")]
| using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.10.2.0")]
[assembly: AssemblyFileVersion("5.10.2.0")]
| mit | C# |
5cb48cccb6b13044bfbb24135942e11c3e56b2ba | Update Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs | GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA | Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs | Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs | //******************************************************************************************************
// RemoteXDAMeter.cs - Gbtc
//
// Copyright © 2019, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 05/19/2022 - Gabriel Santos
// Generated original version of source code.
//
//******************************************************************************************************
using GSF.Data.Model;
namespace openXDA.Model
{
/// <summary>
/// Model of a remote asset.
/// </summary>
[AllowSearch]
[DeleteRoles("Administrator")]
[TableName("MetersToDataPush"), CustomView(@"
SELECT
MetersToDataPush.ID,
MetersToDataPush.RemoteXDAInstanceID,
MetersToDataPush.LocalXDAMeterID,
MetersToDataPush.RemoteXDAMeterID,
MetersToDataPush.RemoteXDAName,
MetersToDataPush.RemoteXDAAssetKey,
MetersToDataPush.Obsfucate,
MetersToDataPush.Synced,
Meter.Alias as LocalAlias,
Meter.Name as LocalMeterName,
Meter.AssetKey as LocalAssetKey
FROM
MetersToDataPush LEFT JOIN
Meter ON MetersToDataPush.LocalXDAMeterID = Meter.ID")]
public class RemoteXDAMeter : MetersToDataPush
{
public string LocalAlias { get; set; }
public string LocalMeterName { get; set; }
public string LocalAssetKey { get; set; }
}
} | //******************************************************************************************************
// AdditionalField.cs - Gbtc
//
// Copyright © 2019, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 05/19/2022 - Gabriel Santos
// Generated original version of source code.
//
//******************************************************************************************************
using GSF.Data.Model;
namespace openXDA.Model
{
/// <summary>
/// Model of a remote asset.
/// </summary>
[AllowSearch]
[DeleteRoles("Administrator")]
[TableName("MetersToDataPush"), CustomView(@"
SELECT
MetersToDataPush.ID,
MetersToDataPush.RemoteXDAInstanceID,
MetersToDataPush.LocalXDAMeterID,
MetersToDataPush.RemoteXDAMeterID,
MetersToDataPush.RemoteXDAName,
MetersToDataPush.RemoteXDAAssetKey,
MetersToDataPush.Obsfucate,
MetersToDataPush.Synced,
Meter.Alias as LocalAlias,
Meter.Name as LocalMeterName,
Meter.AssetKey as LocalAssetKey
FROM
MetersToDataPush LEFT JOIN
Meter ON MetersToDataPush.LocalXDAMeterID = Meter.ID")]
public class RemoteXDAMeter : MetersToDataPush
{
public string LocalAlias { get; set; }
public string LocalMeterName { get; set; }
public string LocalAssetKey { get; set; }
}
} | mit | C# |
89dc7b344da0e735a2ffb3ad94f2e53f56633036 | add de/serilization into Entity | twoThirds/MDF24HourGame | 24hGame/24hGame/24hGame/BaseTypes/Entity.cs | 24hGame/24hGame/24hGame/BaseTypes/Entity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace _24hGame.BaseTypes
{
public class Entity
{
public void Serialize<Entity>(Entity data, string filePath)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Entity));
//Overridden to use UTF8 for compatability with Perl XML::DOM
using (TextWriter writer = new StreamWriter(filePath))
{
xmlSerializer.Serialize(writer, data);
}
}
public Entity DeSerilize(Entity data, string filePath)
{
XmlSerializer ser = new XmlSerializer(typeof(Entity));
using (XmlReader reader = XmlReader.Create(filePath))
{
data = (Entity)ser.Deserialize(reader);
}
return data;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _24hGame.BaseTypes
{
class Entity
{
static Entity()
{
random = new Random();
}
static Random random;
static Random Random
{
get
{
return random;
}
}
}
}
| apache-2.0 | C# |
185e9da72cc4341aa4bf3bb92b50ec09a8910b10 | remove icon (marker) for non-favorite items | SunboX/windows-universal,scherke85/windows-universal,DecaTec/windows-universal,TheScientist/windows-universal,scherke/windows-universal,TheScientist/windows-universal,TheScientist/windows-universal,altima/windows-universal,SunboX/windows-universal,scherke85/windows-universal,DecaTec/windows-universal,altima/windows-universal,scherke/windows-universal,SunboX/windows-universal,scherke/windows-universal,altima/windows-universal,scherke85/windows-universal,DecaTec/windows-universal | NextcloudApp/Converter/FavoriteToIconConverter.cs | NextcloudApp/Converter/FavoriteToIconConverter.cs | using NextcloudClient.Types;
using System;
using Windows.UI.Xaml.Data;
namespace NextcloudApp.Converter
{
public class FavoriteToIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var item = (ResourceInfo)value;
return item.IsFavorite ? "\uE735" : "";
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return new ResourceInfo();
}
}
}
| using NextcloudClient.Types;
using System;
using Windows.UI.Xaml.Data;
namespace NextcloudApp.Converter
{
public class FavoriteToIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var item = (ResourceInfo)value;
return item.IsFavorite ? "\uE735" : "\uE734";
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return new ResourceInfo();
}
}
}
| mpl-2.0 | C# |
ab0e80e0b7275cac6e03c52af15720e54cbf43f4 | Remove duplicated code from StubListener. | fixie/fixie,bardoloi/fixie,Duohong/fixie,bardoloi/fixie,KevM/fixie,JakeGinnivan/fixie,EliotJones/fixie | src/Fixie.Tests/StubListener.cs | src/Fixie.Tests/StubListener.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Fixie.Results;
namespace Fixie.Tests
{
public class StubListener : Listener
{
readonly List<string> log = new List<string>();
public void AssemblyStarted(Assembly assembly)
{
}
public void CaseSkipped(SkipResult result)
{
log.Add(string.Format("{0} skipped{1}", result.Case.Name, result.Reason == null ? "." : ": " + result.Reason));
}
public void CasePassed(PassResult result)
{
var @case = result.Case;
log.Add(string.Format("{0} passed.", @case.Name));
}
public void CaseFailed(FailResult result)
{
var @case = result.Case;
var entry = new StringBuilder();
entry.Append(string.Format("{0} failed: {1}", @case.Name, result.PrimaryExceptionMessage()));
foreach (var exception in result.Exceptions.Skip(1))
{
entry.AppendLine();
entry.Append(string.Format(" Secondary Failure: {0}", exception.Message));
}
log.Add(entry.ToString());
}
public void AssemblyCompleted(Assembly assembly, AssemblyResult result)
{
}
public IEnumerable<string> Entries
{
get { return log; }
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Fixie.Results;
namespace Fixie.Tests
{
public class StubListener : Listener
{
readonly List<string> log = new List<string>();
public void AssemblyStarted(Assembly assembly)
{
}
public void CaseSkipped(SkipResult result)
{
log.Add(string.Format("{0} skipped{1}", result.Case.Name, result.Reason == null ? "." : ": " + result.Reason));
}
public void CasePassed(PassResult result)
{
var @case = result.Case;
log.Add(string.Format("{0} passed.", @case.Name));
}
public void CaseFailed(FailResult result)
{
var @case = result.Case;
var exceptions = result.Exceptions;
var entry = new StringBuilder();
var primary = exceptions.First();
entry.Append(string.Format("{0} failed: {1}", @case.Name, primary.Message));
foreach (var exception in exceptions.Skip(1))
{
entry.AppendLine();
entry.Append(string.Format(" Secondary Failure: {0}", exception.Message));
}
log.Add(entry.ToString());
}
public void AssemblyCompleted(Assembly assembly, AssemblyResult result)
{
}
public IEnumerable<string> Entries
{
get { return log; }
}
}
} | mit | C# |
f12e0d6a0621d9472d46d2be1a79bac462d6959b | build 7.1.10 | agileharbor/channelAdvisorAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.10.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.9.0" ) ] | bsd-3-clause | C# |
0f1907e16e7fc68a571ae3684643e921440c9dc0 | Update CompositeExceptionTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/CompositeExceptionTelemeter.cs | TIKSN.Core/Analytics/Telemetry/CompositeExceptionTelemeter.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using TIKSN.Configuration;
namespace TIKSN.Analytics.Telemetry
{
public class CompositeExceptionTelemeter : IExceptionTelemeter
{
private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration;
private readonly IEnumerable<IExceptionTelemeter> exceptionTelemeters;
public CompositeExceptionTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration,
IEnumerable<IExceptionTelemeter> exceptionTelemeters)
{
this.commonConfiguration = commonConfiguration;
this.exceptionTelemeters = exceptionTelemeters;
}
public async Task TrackExceptionAsync(Exception exception)
{
if (this.commonConfiguration.GetConfiguration().IsExceptionTrackingEnabled)
{
foreach (var exceptionTelemeter in this.exceptionTelemeters)
{
try
{
await exceptionTelemeter.TrackExceptionAsync(exception).ConfigureAwait(false);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
public async Task TrackExceptionAsync(Exception exception, TelemetrySeverityLevel severityLevel)
{
if (this.commonConfiguration.GetConfiguration().IsExceptionTrackingEnabled)
{
foreach (var exceptionTelemeter in this.exceptionTelemeters)
{
try
{
await exceptionTelemeter.TrackExceptionAsync(exception, 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 CompositeExceptionTelemeter : IExceptionTelemeter
{
private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration;
private readonly IEnumerable<IExceptionTelemeter> exceptionTelemeters;
public CompositeExceptionTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration,
IEnumerable<IExceptionTelemeter> exceptionTelemeters)
{
this.commonConfiguration = commonConfiguration;
this.exceptionTelemeters = exceptionTelemeters;
}
public async Task TrackException(Exception exception)
{
if (this.commonConfiguration.GetConfiguration().IsExceptionTrackingEnabled)
{
foreach (var exceptionTelemeter in this.exceptionTelemeters)
{
try
{
await exceptionTelemeter.TrackException(exception);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
public async Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
if (this.commonConfiguration.GetConfiguration().IsExceptionTrackingEnabled)
{
foreach (var exceptionTelemeter in this.exceptionTelemeters)
{
try
{
await exceptionTelemeter.TrackException(exception, severityLevel);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
}
}
| mit | C# |
b137317757189700a18dfe608b6f0ced84a1e76f | Update DriverFactory.cs | ThebeRising/myTestGit | Implementation/DriverFactory.cs | Implementation/DriverFactory.cs | using System;
using Gauge.CSharp.Lib.Attribute;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
namespace Gauge.Example.Implementation
{
public class DriverFactory
{
public static IWebDriver Driver { get; private set; }
[BeforeSuite]
public void Setup() {
bool useIe;
bool.TryParse(Environment.GetEnvironmentVariable("USE_IE"), out useIe);
if (useIe)
{
Driver=new InternetExplorerDriver();
}
else
{
Driver =new ChromeDriver();
}
}
[AfterSuite]
public void TearDown() {
Driver.Close();
}
}
}
| using System;
using Gauge.CSharp.Lib.Attribute;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.ChromeDriver;
namespace Gauge.Example.Implementation
{
public class DriverFactory
{
public static IWebDriver Driver { get; private set; }
[BeforeSuite]
public void Setup() {
bool useIe;
bool.TryParse(Environment.GetEnvironmentVariable("USE_IE"), out useIe);
if (useIe)
{
Driver=new InternetExplorerDriver();
}
else
{
Driver =new ChromeDriver();
}
}
[AfterSuite]
public void TearDown() {
Driver.Close();
}
}
}
| apache-2.0 | C# |
a52976a839b682c4206f23662b7077e4d6366716 | Fix IAM use of unknown resource names | jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet | apis/Google.Cloud.Iam.V1/Google.Cloud.Iam.V1/ResourceNames.cs | apis/Google.Cloud.Iam.V1/Google.Cloud.Iam.V1/ResourceNames.cs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using gax = Google.Api.Gax;
namespace Google.Cloud.Iam.V1
{
public partial class SetIamPolicyRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get => string.IsNullOrEmpty(Resource) ? null : gax::UnparsedResourceName.Parse(Resource);
set => Resource = value?.ToString() ?? "";
}
}
public partial class GetIamPolicyRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get => string.IsNullOrEmpty(Resource) ? null : gax::UnparsedResourceName.Parse(Resource);
set => Resource = value?.ToString() ?? "";
}
}
public partial class TestIamPermissionsRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get => string.IsNullOrEmpty(Resource) ? null : gax::UnparsedResourceName.Parse(Resource);
set => Resource = value?.ToString() ?? "";
}
}
}
| // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using gax = Google.Api.Gax;
namespace Google.Cloud.Iam.V1
{
public partial class SetIamPolicyRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get { return string.IsNullOrEmpty(Resource) ? null : gax::UnknownResourceName.Parse(Resource); }
set { Resource = value != null ? value.ToString() : ""; }
}
}
public partial class GetIamPolicyRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get { return string.IsNullOrEmpty(Resource) ? null : gax::UnknownResourceName.Parse(Resource); }
set { Resource = value != null ? value.ToString() : ""; }
}
}
public partial class TestIamPermissionsRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Resource"/> resource name property.
/// </summary>
public gax::IResourceName ResourceAsResourceName
{
get { return string.IsNullOrEmpty(Resource) ? null : gax::UnknownResourceName.Parse(Resource); }
set { Resource = value != null ? value.ToString() : ""; }
}
}
}
| apache-2.0 | C# |
aae63d8626d12c8f90c0fda9141eaea53dc61be5 | Reformat tests for IntegralTypeExtension. | muhbaasu/fx-sharp | src/FxSharp.Tests/Extensions/IntegralTypeExtensionsTests.cs | src/FxSharp.Tests/Extensions/IntegralTypeExtensionsTests.cs | using FxSharp.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FxSharp.Tests.Extensions
{
/// <summary>
/// Internal test enum.
/// </summary>
internal enum DaysInt
{
Sat = 0,
Sun = 1,
Mon = 2
}
[TestClass]
public class IntegralTypeExtensionsTests
{
/// <summary>
/// Test if the parsing of an integer value returns Just when the
/// given value is not in range of the given enum type.
/// </summary>
[TestMethod]
public void ParseEnumInt()
{
const int value = (int) DaysInt.Mon;
value.ParseEnum<DaysInt>().Match_(
just: day => Assert.AreEqual(day, DaysInt.Mon),
nothing: () => Assert.Fail("Option should be nothing!"));
}
/// <summary>
/// Test if the parsing of an integer value returns Nothing when the
/// given value is not in range of the given enum type.
/// </summary>
[TestMethod]
public void ParseEnumIntFailsWhenNotInRange()
{
const int day = 3;
day.ParseEnum<DaysInt>()
.Select_(_ => Assert.Fail("Option should be nothing!"));
}
}
} | using FxSharp.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FxSharp.Tests.Extensions
{
/// <summary>
/// Internal test enum.
/// </summary>
internal enum DaysInt
{
Sat = 0,
Sun = 1,
Mon = 2
}
[TestClass]
public class IntegralTypeExtensionsTests
{
/// <summary>
/// Test if the parsing of an integer value returns Just when the
/// given value is not in range of the given enum type.
/// </summary>
[TestMethod]
public void ParseEnumInt()
{
var value = (int) DaysInt.Mon;
value.ParseEnum<DaysInt>().Match_(
just: day => Assert.AreEqual(day, DaysInt.Mon),
nothing: () => Assert.Fail("Option should be nothing!"));
}
/// <summary>
/// Test if the parsing of an integer value returns Nothing when the
/// given value is not in range of the given enum type.
/// </summary>
[TestMethod]
public void ParseEnumIntFailsWhenNotInRange()
{
var day = 3;
day.ParseEnum<DaysInt>()
.Select_(_ => Assert.Fail("Option should be nothing!"));
}
}
} | apache-2.0 | C# |
d434a4d205cd0da5d0b91af75c1195119197ea6e | Fix new lines in AssemblyInfo.cs (#39084) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Security/Authentication/Certificate/src/AssemblyInfo.cs | src/Security/Authentication/Certificate/src/AssemblyInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Authentication.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Authentication.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] | apache-2.0 | C# |
09eaa0a9aa02439c53050d2fea9a95619ba1705d | Reduce the date size for the email subject | deeja/Pigeon | Pigeon.Zipper/Pipelines/SetEmailSubject.cs | Pigeon.Zipper/Pipelines/SetEmailSubject.cs | namespace Pigeon.Pipelines
{
using System;
using Sitecore.Diagnostics;
public class SetEmailSubject:PigeonPipelineProcessor
{
public override void Process(PigeonPipelineArgs args)
{
Assert.IsNotNull(args,"args != null");
args.Subject = $"[Pigeon] {System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()} {Environment.MachineName} - Date Range: {args.StartDateTime:G} -> {args.EndDateTime:G}";
}
}
} | namespace Pigeon.Pipelines
{
using System;
using Sitecore.Diagnostics;
public class SetEmailSubject:PigeonPipelineProcessor
{
public override void Process(PigeonPipelineArgs args)
{
Assert.IsNotNull(args,"args != null");
args.Subject = $"[Pigeon] {System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()} {Environment.MachineName} - Date Range: {args.StartDateTime:O} -> {args.EndDateTime:O}";
}
}
} | mit | C# |
af2b677c3623caba1aa8dc94fdc84d8c11e1b912 | Fix test, it was checking the wrong md5 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | src/tests/IntegrationTests/UnzipTaskTests.cs | src/tests/IntegrationTests/UnzipTaskTests.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using GitHub.Unity;
using Microsoft.Win32.SafeHandles;
using NSubstitute;
using NUnit.Framework;
using Rackspace.Threading;
namespace IntegrationTests
{
[TestFixture]
class UnzipTaskTests : BaseTaskManagerTest
{
[Test]
public async Task UnzipWorks()
{
InitializeTaskManager();
var cacheContainer = Substitute.For<ICacheContainer>();
Environment = new IntegrationTestEnvironment(cacheContainer, TestBasePath, SolutionDirectory);
var destinationPath = TestBasePath.Combine("gitlfs_zip").CreateDirectory();
var archiveFilePath = AssemblyResources.ToFile(ResourceType.Platform, "git-lfs.zip", destinationPath, Environment);
var extractedPath = TestBasePath.Combine("gitlfs_zip_extracted").CreateDirectory();
var unzipTask = new UnzipTask(CancellationToken.None, archiveFilePath, extractedPath, Environment.FileSystem, GitInstaller.GitInstallDetails.GitLfsExtractedMD5)
.Progress(p =>
{
});
await unzipTask.StartAwait();
extractedPath.DirectoryExists().Should().BeTrue();
}
[Test]
public void FailsWhenMD5Incorrect()
{
InitializeTaskManager();
var cacheContainer = Substitute.For<ICacheContainer>();
Environment = new IntegrationTestEnvironment(cacheContainer, TestBasePath, SolutionDirectory);
var destinationPath = TestBasePath.Combine("gitlfs_zip").CreateDirectory();
var archiveFilePath = AssemblyResources.ToFile(ResourceType.Platform, "git-lfs.zip", destinationPath, Environment);
var extractedPath = TestBasePath.Combine("gitlfs_zip_extracted").CreateDirectory();
var unzipTask = new UnzipTask(CancellationToken.None, archiveFilePath, extractedPath, Environment.FileSystem, "AABBCCDD");
Assert.Throws<UnzipException>(async () => await unzipTask.StartAwait());
extractedPath.DirectoryExists().Should().BeFalse();
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using GitHub.Unity;
using Microsoft.Win32.SafeHandles;
using NSubstitute;
using NUnit.Framework;
using Rackspace.Threading;
namespace IntegrationTests
{
[TestFixture]
class UnzipTaskTests : BaseTaskManagerTest
{
[Test]
public async Task UnzipWorks()
{
InitializeTaskManager();
var cacheContainer = Substitute.For<ICacheContainer>();
Environment = new IntegrationTestEnvironment(cacheContainer, TestBasePath, SolutionDirectory);
var destinationPath = TestBasePath.Combine("gitlfs_zip").CreateDirectory();
var archiveFilePath = AssemblyResources.ToFile(ResourceType.Platform, "git-lfs.zip", destinationPath, Environment);
var extractedPath = TestBasePath.Combine("gitlfs_zip_extracted").CreateDirectory();
var unzipTask = new UnzipTask(CancellationToken.None, archiveFilePath, extractedPath, Environment.FileSystem, GitInstaller.GitInstallDetails.GitExtractedMD5)
.Progress(p =>
{
});
await unzipTask.StartAwait();
extractedPath.DirectoryExists().Should().BeTrue();
}
[Test]
public void FailsWhenMD5Incorrect()
{
InitializeTaskManager();
var cacheContainer = Substitute.For<ICacheContainer>();
Environment = new IntegrationTestEnvironment(cacheContainer, TestBasePath, SolutionDirectory);
var destinationPath = TestBasePath.Combine("gitlfs_zip").CreateDirectory();
var archiveFilePath = AssemblyResources.ToFile(ResourceType.Platform, "git-lfs.zip", destinationPath, Environment);
var extractedPath = TestBasePath.Combine("gitlfs_zip_extracted").CreateDirectory();
var unzipTask = new UnzipTask(CancellationToken.None, archiveFilePath, extractedPath, Environment.FileSystem, "AABBCCDD");
Assert.Throws<UnzipException>(async () => await unzipTask.StartAwait());
extractedPath.DirectoryExists().Should().BeFalse();
}
}
} | mit | C# |
17277e2abedfb58aa5b09139326b59e4c7542f42 | Fix the broken NuGet build. | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Examples/Demos/Input/Scenes/PrimaryPointer/PrimaryPointerHandlerExample.cs | Assets/MixedRealityToolkit.Examples/Demos/Input/Scenes/PrimaryPointer/PrimaryPointerHandlerExample.cs | using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
} | using System;
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor?.GameObjectReference?.transform;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
var controllerPointer = newPointer as BaseControllerPointer;
parentTransform = controllerPointer?.transform;
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
MixedRealityToolkit.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
| mit | C# |
662a4d3e19daf05dd82b0c48488e6c1d19769e42 | fix check helmet | bzn/naxs | Assets/Scripts/PlayerData_SetViveDevice.cs | Assets/Scripts/PlayerData_SetViveDevice.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class PlayerData_SetViveDevice : MonoBehaviour {
public bool isValid { get; private set; }
private IEnumerator coroutine;
void OnEnable()
{
if (gameObject.name.Contains("Camera"))
{
newPosesAction.enabled = true;
coroutine = WaitForCheckDeviceActivity(1.0f);
StartCoroutine(coroutine);
}
else if(gameObject.name.Contains("Controller (right)"))
{
PlayerDataControl.instance.isTracker = true;
}
}
void OnDisable()
{
if (gameObject.name.Contains("Camera"))
{
newPosesAction.enabled = false;
StopCoroutine(coroutine);
}
else if (gameObject.name.Contains("Controller (right)"))
{
PlayerDataControl.instance.isTracker = false;
}
}
private void OnNewPoses(TrackedDevicePose_t[] poses)
{
isValid = false;
if (!poses[0].bDeviceIsConnected)
{
return;
}
if (!poses[0].bPoseIsValid)
{
return;
}
isValid = true;
}
SteamVR_Events.Action newPosesAction;
PlayerData_SetViveDevice()
{
newPosesAction = SteamVR_Events.NewPosesAction(OnNewPoses);
}
IEnumerator WaitForCheckDeviceActivity(float waitTime)
{
while (true)
{
yield return new WaitForSeconds(waitTime);
PlayerDataControl.instance.isHelmet = isValid;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerData_SetViveDevice : MonoBehaviour {
void OnEnable()
{
if (gameObject.name.Contains("Camera"))
{
PlayerDataControl.instance.isHelmet = true;
}
else if(gameObject.name.Contains("Controller (right)"))
{
PlayerDataControl.instance.isTracker = true;
}
}
void OnDisable()
{
if (gameObject.name.Contains("Camera"))
{
PlayerDataControl.instance.isHelmet = false;
}
else if (gameObject.name.Contains("Controller (right)"))
{
PlayerDataControl.instance.isTracker = false;
}
}
}
| mit | C# |
6d667e2d78a0db0ca0ad8ce8ae92ade4b789beff | bump redoc | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Home/SwaggerDocs.cshtml | BTCPayServer/Views/Home/SwaggerDocs.cshtml | @inject BTCPayServer.Security.ContentSecurityPolicies csp
@{
Layout = null;
csp.Add("script-src", "https://cdn.jsdelivr.net");
csp.Add("worker-src", "blob:");
}
<!DOCTYPE html>
<html>
<head>
<title>BTCPay Server Greenfield API</title>
<!-- needed for adaptive design -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true">
<link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
@*Ignore this, this is for making the test ClickOnAllSideMenus happy*@
<div class="navbar-brand" style="visibility:collapse;"></div>
<redoc spec-url="@Url.ActionLink("Swagger")"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.54/bundles/redoc.standalone.js" integrity="sha384-pxWFJkxrlfignEDb+sJ8XrdnJQ+V2bsiRqgPnfmOk1i3KKSubbydbolVZJeKisNY" crossorigin="anonymous"></script>
</body>
</html>
| @inject BTCPayServer.Security.ContentSecurityPolicies csp
@{
Layout = null;
csp.Add("script-src", "https://cdn.jsdelivr.net");
csp.Add("worker-src", "blob: self");
}
<!DOCTYPE html>
<html>
<head>
<title>BTCPay Server Greenfield API</title>
<!-- needed for adaptive design -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true">
<link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
@*Ignore this, this is for making the test ClickOnAllSideMenus happy*@
<div class="navbar-brand" style="visibility:collapse;"></div>
<redoc spec-url="@Url.ActionLink("Swagger")"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script>
</body>
</html>
| mit | C# |
ce94ca41ea8fe143e46c1f890bc042e4c4b7b129 | Create directory if it doesnt exist | onionhammer/WebApiProxy,onionhammer/WebApiProxy | WebApiProxy.Tasks/Models/Configuration.cs | WebApiProxy.Tasks/Models/Configuration.cs | using System.IO;
using System.Xml;
using System.Xml.Serialization;
using WebApiProxy.Core.Models;
namespace WebApiProxy.Tasks.Models
{
[XmlRoot("proxy")]
public class Configuration
{
public const string ConfigFileName = "WebApiProxy.config";
public const string CacheFile = "WebApiProxy.generated.cache";
[XmlAttribute("generateOnBuild")]
public bool GenerateOnBuild { get; set; } = false;
string _clientSuffix = "Client";
[XmlAttribute("clientSuffix")]
public string ClientSuffix
{
get => _clientSuffix.DefaultIfEmpty("Client");
set => _clientSuffix = value;
}
[XmlAttribute("namespace")]
public string Namespace { get; set; } = "WebApi.Proxies";
[XmlAttribute("name")]
public string Name { get; set; } = "ApiProxy";
[XmlAttribute("endpoint")]
public string Endpoint { get; set; }
[XmlIgnore]
public Metadata Metadata { get; set; }
public static Configuration Load(string webapiRoot)
{
var filename = Path.Combine(webapiRoot, Configuration.ConfigFileName);
if (!File.Exists(filename))
return null;
var serializer = new XmlSerializer(typeof(Configuration), new XmlRootAttribute("proxy"));
using (var reader = new StreamReader(filename))
return serializer.Deserialize(reader) as Configuration;
}
public static Configuration Create(string webapiRoot, string apiEndpoint, string apiNamespace)
{
var filename = Path.Combine(webapiRoot, Configuration.ConfigFileName);
var newConfig = new Configuration
{
Endpoint = apiEndpoint,
Namespace = apiNamespace
};
if (Directory.Exists(webapiRoot) == false)
Directory.CreateDirectory(webapiRoot);
var serializer = new XmlSerializer(typeof(Configuration), new XmlRootAttribute("proxy"));
using (var writer = new StreamWriter(filename))
serializer.Serialize(writer, newConfig);
return newConfig;
}
}
} | using System.IO;
using System.Xml;
using System.Xml.Serialization;
using WebApiProxy.Core.Models;
namespace WebApiProxy.Tasks.Models
{
[XmlRoot("proxy")]
public class Configuration
{
public const string ConfigFileName = "WebApiProxy.config";
public const string CacheFile = "WebApiProxy.generated.cache";
[XmlAttribute("generateOnBuild")]
public bool GenerateOnBuild { get; set; } = false;
string _clientSuffix = "Client";
[XmlAttribute("clientSuffix")]
public string ClientSuffix
{
get => _clientSuffix.DefaultIfEmpty("Client");
set => _clientSuffix = value;
}
[XmlAttribute("namespace")]
public string Namespace { get; set; } = "WebApi.Proxies";
[XmlAttribute("name")]
public string Name { get; set; } = "ApiProxy";
[XmlAttribute("endpoint")]
public string Endpoint { get; set; }
[XmlIgnore]
public Metadata Metadata { get; set; }
public static Configuration Load(string webapiRoot)
{
var filename = Path.Combine(webapiRoot, Configuration.ConfigFileName);
if (!File.Exists(filename))
return null;
var serializer = new XmlSerializer(typeof(Configuration), new XmlRootAttribute("proxy"));
using (var reader = new StreamReader(filename))
return serializer.Deserialize(reader) as Configuration;
}
public static Configuration Create(string webapiRoot, string apiEndpoint, string apiNamespace)
{
var filename = Path.Combine(webapiRoot, Configuration.ConfigFileName);
var newConfig = new Configuration
{
Endpoint = apiEndpoint,
Namespace = apiNamespace
};
var serializer = new XmlSerializer(typeof(Configuration), new XmlRootAttribute("proxy"));
using (var writer = new StreamWriter(filename))
serializer.Serialize(writer, newConfig);
return newConfig;
}
}
} | mit | C# |
414439e028e895b9288a4b6728015a0426dafc1c | Fix getting stuck | H-POPS/Slingshot | CustomFlatRide/FlatRideScript/Slingshot.cs | CustomFlatRide/FlatRideScript/Slingshot.cs |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slingshot : FlatRide
{
public bool getOut;
public SpringJoint UpperLeft;
public SpringJoint UpperRight;
public SpringJoint Bottom;
public float speedDown = .15f;
public float strenghtDown = 20;
public float springVar = 1.5f;
new void Start()
{
UpperRight.spring = 0;
UpperLeft.spring = 0;
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void onStartRide()
{
getOut = false;
base.onStartRide();
foreach (MeshCollider coll in GetComponentsInChildren<MeshCollider>())
{
coll.convex = true;
}
StartCoroutine(Ride());
StartCoroutine(fix());
}
IEnumerator Ride()
{
Bottom.connectedBody.isKinematic = false;
Bottom.spring = 0;
Bottom.damper = 0;
UpperRight.spring = springVar;
UpperLeft.spring = springVar;
yield return new WaitForSeconds(10);
while (Vector3.Distance(Bottom.anchor + Bottom.transform.position, Bottom.connectedBody.transform.position + Bottom.connectedAnchor) > .1f)
{
Bottom.spring = Mathf.Lerp(Bottom.spring, strenghtDown, speedDown / 2 * Time.deltaTime);
Bottom.damper = Mathf.Lerp(Bottom.damper, strenghtDown * 1.4f , speedDown / 2 * Time.deltaTime); ;
UpperRight.spring = Mathf.Lerp(UpperRight.spring, 0, speedDown * Time.deltaTime); ;
UpperLeft.spring = Mathf.Lerp(UpperLeft.spring, 0, speedDown * Time.deltaTime); ;
yield return null;
}
UpperRight.spring = 0;
UpperLeft.spring = 0;
yield return new WaitForSeconds(1);
Bottom.connectedBody.isKinematic = true;
getOut = true;
StopAllCoroutines();
}
IEnumerator fix()
{
yield return new WaitForSeconds(23);
UpperRight.spring = 0;
UpperLeft.spring = 0;
yield return new WaitForSeconds(1);
Bottom.connectedBody.isKinematic = true;
getOut = true;
StopAllCoroutines();
}
public override void tick(StationController stationController)
{
}
public override bool shouldLetGuestsOut()
{
return getOut;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slingshot : FlatRide
{
public bool getOut;
public SpringJoint UpperLeft;
public SpringJoint UpperRight;
public SpringJoint Bottom;
public float speedDown = .15f;
public float strenghtDown = 20;
public float springVar = 1.5f;
new void Start()
{
UpperRight.spring = 0;
UpperLeft.spring = 0;
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void onStartRide()
{
getOut = false;
base.onStartRide();
foreach (MeshCollider coll in GetComponentsInChildren<MeshCollider>())
{
coll.convex = true;
}
StartCoroutine(Ride());
}
IEnumerator Ride()
{
Bottom.connectedBody.isKinematic = false;
Bottom.spring = 0;
Bottom.damper = 0;
UpperRight.spring = springVar;
UpperLeft.spring = springVar;
yield return new WaitForSeconds(10);
while (Vector3.Distance(Bottom.anchor + Bottom.transform.position, Bottom.connectedBody.transform.position + Bottom.connectedAnchor) > .1f)
{
Bottom.spring = Mathf.Lerp(Bottom.spring, strenghtDown, speedDown / 2 * Time.deltaTime);
Bottom.damper = Mathf.Lerp(Bottom.damper, strenghtDown * 1.4f , speedDown / 2 * Time.deltaTime); ;
UpperRight.spring = Mathf.Lerp(UpperRight.spring, 0, speedDown * Time.deltaTime); ;
UpperLeft.spring = Mathf.Lerp(UpperLeft.spring, 0, speedDown * Time.deltaTime); ;
yield return null;
}
UpperRight.spring = 0;
UpperLeft.spring = 0;
yield return new WaitForSeconds(1);
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void tick(StationController stationController)
{
}
public override bool shouldLetGuestsOut()
{
return getOut;
}
}
| mit | C# |
c23ddfe1b6d6dee621f29406bb4491c4a6413020 | adjust code so that HasTable returns a boolean from the database indicating that the table exists (or not) | DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor,DBCG/Dataphor,n8allan/Dataphor,n8allan/Dataphor,n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor | Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs | Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs | /*
Alphora Dataphor
Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
#define USESQLCONNECTION
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
#if USESQLCONNECTION
using Alphora.Dataphor.DAE.Connection;
using Alphora.Dataphor.DAE.Connection.PGSQL;
#else
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
#endif
namespace Alphora.Dataphor.DAE.Store.PGSQL
{
public class PostgreSQLStoreConnection : SQLStoreConnection
{
public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { }
#if USESQLCONNECTION
protected override SQLConnection InternalCreateConnection()
{
return new PostgreSQLConnection(Store.ConnectionString);
}
#else
protected override DbConnection InternalCreateConnection()
{
return new SqlConnection(Store.ConnectionString);
}
#endif
public override bool HasTable(string ATableName)
{
string LStatement = String.Format("select count(*)>0 from PG_TABLES where TABLENAME = '{0}'", ATableName);
bool LTableExists = (bool) this.ExecuteScalar(LStatement);
return LTableExists;
}
}
} | /*
Alphora Dataphor
Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
#define USESQLCONNECTION
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
#if USESQLCONNECTION
using Alphora.Dataphor.DAE.Connection;
using Alphora.Dataphor.DAE.Connection.PGSQL;
#else
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
#endif
namespace Alphora.Dataphor.DAE.Store.PGSQL
{
public class PostgreSQLStoreConnection : SQLStoreConnection
{
public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { }
#if USESQLCONNECTION
protected override SQLConnection InternalCreateConnection()
{
return new PostgreSQLConnection(Store.ConnectionString);
}
#else
protected override DbConnection InternalCreateConnection()
{
return new SqlConnection(Store.ConnectionString);
}
#endif
HasTable
public override bool (string ATableName)
{
string LStatement = String.Format("select count(*)>0 from PG_TABLES where TABLENAME = '{0}'", ATableName);
bool LTableExists = (bool) this.ExecuteScalar(LStatement);
return LTableExists;
}
}
} | bsd-3-clause | C# |
1df0528dbea365a39ff3a9f91b23b8fd97a97631 | Add GameToString test | ceddlyburge/canoe-polo-league-organiser-backend | CanoePoloLeagueOrganiserTests/GameTests.cs | CanoePoloLeagueOrganiserTests/GameTests.cs | using System;
using CanoePoloLeagueOrganiser;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CanoePoloLeagueOrganiserTests
{
public class GameTests
{
[Fact]
public void PlayingWithString()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing("Clapham"));
Assert.True(sut.Playing("Castle"));
Assert.False(sut.Playing("Battersea"));
}
[Fact]
public void PlayingWithTeam()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing(new Team("Clapham")));
Assert.True(sut.Playing(new Team("Castle")));
Assert.False(sut.Playing(new Team("Battersea")));
}
[Fact]
public void PlayingWithGame()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing(new Game("Clapham", "Any")));
Assert.True(sut.Playing(new Game("Any", "Castle")));
Assert.False(sut.Playing(new Game("Not Clapham", "Not Castle")));
}
[Fact]
public void GameToString()
{
var sut = new Game("Clapham", "Castle");
Assert.Equal("Clapham v Castle", sut.ToString());
}
}
}
| using System;
using CanoePoloLeagueOrganiser;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CanoePoloLeagueOrganiserTests
{
public class GameTests
{
[Fact]
public void PlayingWithString()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing("Clapham"));
Assert.True(sut.Playing("Castle"));
Assert.False(sut.Playing("Battersea"));
}
[Fact]
public void PlayingWithTeam()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing(new Team("Clapham")));
Assert.True(sut.Playing(new Team("Castle")));
Assert.False(sut.Playing(new Team("Battersea")));
}
[Fact]
public void PlayingWithGame()
{
var sut = new Game("Clapham", "Castle");
Assert.True(sut.Playing(new Game("Clapham", "Any")));
Assert.True(sut.Playing(new Game("Any", "Castle")));
Assert.False(sut.Playing(new Game("Not Clapham", "Not Castle")));
}
}
}
| mit | C# |
d0fa813a1169401c7f5741e814e730a7fe047a2d | Fix typo | Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module | GraphQL/Services/ContentItemTypeBuilder.cs | GraphQL/Services/ContentItemTypeBuilder.cs | using GraphQL.Types;
using OrchardCore.ContentManagement.GraphQL.Queries.Types;
using OrchardCore.ContentManagement.Metadata.Models;
using System.Linq;
namespace Lombiq.TrainingDemo.GraphQL.Services
{
// Services that implement IContentTypeBuilder extend the features of existing ContentItem type fields, including
// the top level fields automatically created by Orchard Core for every content type. You can use this to add new
// sub-fields or filter attributes to existing ContentItem type fields.
public class ContentItemTypeBuilder : IContentTypeBuilder
{
// It's a good practice to make the argument name a const because you will reuse it in the IGraphQLFilter.
public const string AgeFilterName = "age";
// Here you can add arguments to every Content Type (top level) field.
public void Build(
FieldType contentQuery,
ContentTypeDefinition contentTypeDefinition,
ContentItemType contentItemType)
{
// You can check to see if the field has any specific sub-field, if you want to rely on its features. For
// example if you only want to apply to ContentItem fields that have the "person" sub-field (i.e. those that
// have a PersonPart). This is useful if you want to expand your content part field in another module.
if (contentItemType.Fields.All(field => field.Name != "person")) return;
// The resolved type can be anything that can be represented with JSON and has a known graph type, but we
// stick with numbers for simplicity's sake. This one filters for equation.
contentQuery.Arguments.Add(new QueryArgument<IntGraphType>
{
Name = AgeFilterName,
ResolvedType = new IntGraphType(),
});
// You can't use special characters in the argument names so by GraphQL convention these two letter suffixes
// that represent the relational operators. Except equation which customarily gets no suffix.
AddFilter(contentQuery, "_lt");
AddFilter(contentQuery, "_le");
AddFilter(contentQuery, "_ge");
AddFilter(contentQuery, "_gt");
AddFilter(contentQuery, "_ne");
}
private static void AddFilter(FieldType contentQuery, string suffix) =>
contentQuery.Arguments.Add(new QueryArgument<IntGraphType>
{
Name = AgeFilterName + suffix,
ResolvedType = new IntGraphType(),
});
}
}
// NEXT STATION: Services/PersonAgeGraphQLFilter.cs
| using GraphQL.Types;
using OrchardCore.ContentManagement.GraphQL.Queries.Types;
using OrchardCore.ContentManagement.Metadata.Models;
using System.Linq;
namespace Lombiq.TrainingDemo.GraphQL.Services
{
// Services that implement IContentTypeBuilder extend the features of existing ContentItem type fields, including
// the top level fields automatically created by Orchard Core for every content type. You can use this to add new
// sub-fields or filter attributes to existing ContentItem type fields.
public class ContentItemTypeBuilder : IContentTypeBuilder
{
// It's a good practice to make the argument name a const because you will reuse it in the IGraphQLFilter.
public const string AgeFilterName = "age";
// Here you can add arguments to every Content Type (top level) field.
public void Build(
FieldType contentQuery,
ContentTypeDefinition contentTypeDefinition,
ContentItemType contentItemType)
{
// You can check to see if the field has any specific sub-filed, if you want to rely on its features. For
// example if you only want to apply to ContentItem fields that have the "person" sub-field (i.e. those that
// have a PersonPart). This is useful if you want to expand your content part field in another module.
if (contentItemType.Fields.All(field => field.Name != "person")) return;
// The resolved type can be anything that can be represented with JSON and has a known graph type, but we
// stick with numbers for simplicity's sake. This one filters for equation.
contentQuery.Arguments.Add(new QueryArgument<IntGraphType>
{
Name = AgeFilterName,
ResolvedType = new IntGraphType(),
});
// You can't use special characters in the argument names so by GraphQL convention these two letter suffixes
// that represent the relational operators. Except equation which customarily gets no suffix.
AddFilter(contentQuery, "_lt");
AddFilter(contentQuery, "_le");
AddFilter(contentQuery, "_ge");
AddFilter(contentQuery, "_gt");
AddFilter(contentQuery, "_ne");
}
private static void AddFilter(FieldType contentQuery, string suffix) =>
contentQuery.Arguments.Add(new QueryArgument<IntGraphType>
{
Name = AgeFilterName + suffix,
ResolvedType = new IntGraphType(),
});
}
}
// NEXT STATION: Services/PersonAgeGraphQLFilter.cs
| bsd-3-clause | C# |
a218e40e6d777f73d63846fb7441e5492a55e441 | rename the test to clarify. | jwChung/Experimentalism,jwChung/Experimentalism | test/ExperimentUnitTest/AssemblyLevelTest.cs | test/ExperimentUnitTest/AssemblyLevelTest.cs | using System.Linq;
using Xunit;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"System.Core",
"xunit",
"xunit.extensions"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
}
} | using System.Linq;
using Xunit;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutOnlyReferencesSpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"System.Core",
"xunit",
"xunit.extensions"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
}
} | mit | C# |
2d72a8c23b384d7b4b7a983b7314a83646860b5f | use Type.Assemlby instead of LoadFrom to get assembly. | jwChung/Experimentalism,jwChung/Experimentalism | test/ExperimentUnitTest/AssemblyLevelTest.cs | test/ExperimentUnitTest/AssemblyLevelTest.cs | using System.Linq;
using System.Reflection;
using Xunit;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutOnlyReferencesSpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"xunit",
"xunit.extensions"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
}
} | using System.Linq;
using System.Reflection;
using Xunit;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutOnlyReferencesSpecifiedAssemblies()
{
var sut = Assembly.LoadFrom("Jwc.Experiment.dll");
Assert.NotNull(sut);
var specifiedAssemblies = new []
{
"mscorlib",
"xunit",
"xunit.extensions"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
}
} | mit | C# |
adcfb92c6ef7a30eb1ab1332c3a5574b77fa8279 | Bump version. | JohanLarsson/Gu.Wpf.Geometry | Gu.Wpf.Geometry/Properties/AssemblyInfo.cs | Gu.Wpf.Geometry/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("Gu.Wpf.Geometry")]
[assembly: AssemblyDescription("Geometries for WPF.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Johan Larsson")]
[assembly: AssemblyProduct("Gu.Wpf.Geometry")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9cbadf5-65f8-4a81-858c-ea0cdfeb2e99")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Tests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Demo", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Benchmarks", AllInternalsVisible = true)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: XmlnsDefinition("http://gu.se/Geometry", "Gu.Wpf.Geometry")]
[assembly: XmlnsDefinition("http://gu.se/Geometry", "Gu.Wpf.Geometry.Effects")]
[assembly: XmlnsPrefix("http://gu.se/Geometry", "geometry")]
[assembly: XmlnsPrefix("http://gu.se/Geometry", "effects")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("Gu.Wpf.Geometry")]
[assembly: AssemblyDescription("Geometries for WPF.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Johan Larsson")]
[assembly: AssemblyProduct("Gu.Wpf.Geometry")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9cbadf5-65f8-4a81-858c-ea0cdfeb2e99")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Tests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Demo", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Gu.Wpf.Geometry.Benchmarks", AllInternalsVisible = true)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: XmlnsDefinition("http://gu.se/Geometry", "Gu.Wpf.Geometry")]
[assembly: XmlnsDefinition("http://gu.se/Geometry", "Gu.Wpf.Geometry.Effects")]
[assembly: XmlnsPrefix("http://gu.se/Geometry", "geometry")]
[assembly: XmlnsPrefix("http://gu.se/Geometry", "effects")]
| mit | C# |
2a4406cdae3bff53430d2dac034aa9bd0ed04c02 | Add Refund as paymentmethod so we can use it in SettlementPeriodRevenue. | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Models/Payment/PaymentMethod.cs | Mollie.Api/Models/Payment/PaymentMethod.cs | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
[EnumMember(Value = "refund")] Refund,
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "mistercash")] MisterCash,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "podiumcadeaukaart")] PodiumCadeaukaart,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "inghomepay")] IngHomePay,
}
} | mit | C# |
a15b231d5897f3936cda574c6244fba109f8f4ed | Add basic formatting support to GlobalStatisticsDisplay | EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Statistics/GlobalStatistic.cs | osu.Framework/Statistics/GlobalStatistic.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.Bindables;
namespace osu.Framework.Statistics
{
public class GlobalStatistic<T> : IGlobalStatistic
{
public string Group { get; }
public string Name { get; }
public IBindable<string> DisplayValue => displayValue;
private readonly Bindable<string> displayValue = new Bindable<string>();
public Bindable<T> Bindable { get; } = new Bindable<T>();
public T Value
{
get => Bindable.Value;
set => Bindable.Value = value;
}
public GlobalStatistic(string group, string name)
{
Group = group;
Name = name;
Bindable.BindValueChanged(val =>
{
switch (val.NewValue)
{
case double d:
displayValue.Value = d.ToString("#,0.##");
break;
case int i:
displayValue.Value = i.ToString("#,0");
break;
case long l:
displayValue.Value = l.ToString("#,0");
break;
default:
displayValue.Value = val.NewValue.ToString();
break;
}
}, true);
}
public virtual void Clear() => Bindable.SetDefault();
}
}
| // 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.Bindables;
namespace osu.Framework.Statistics
{
public class GlobalStatistic<T> : IGlobalStatistic
{
public string Group { get; }
public string Name { get; }
public IBindable<string> DisplayValue => displayValue;
private readonly Bindable<string> displayValue = new Bindable<string>();
public Bindable<T> Bindable { get; } = new Bindable<T>();
public T Value
{
get => Bindable.Value;
set => Bindable.Value = value;
}
public GlobalStatistic(string group, string name)
{
Group = group;
Name = name;
Bindable.BindValueChanged(val => displayValue.Value = val.NewValue.ToString(), true);
}
public virtual void Clear() => Bindable.SetDefault();
}
}
| mit | C# |
d99408e979baa50e01a22535757934f17990d641 | Fix SkinChanged events triggering after disposal (#5461) | ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,2yangk23/osu,smoogipooo/osu,ZLima12/osu,ZLima12/osu,UselessToucan/osu,2yangk23/osu,peppy/osu-new,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu | osu.Game/Skinning/SkinReloadableDrawable.cs | osu.Game/Skinning/SkinReloadableDrawable.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.Allocation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A drawable which has a callback when the skin changes.
/// </summary>
public abstract class SkinReloadableDrawable : CompositeDrawable
{
private readonly Func<ISkinSource, bool> allowFallback;
private ISkinSource skin;
/// <summary>
/// Whether fallback to default skin should be allowed if the custom skin is missing this resource.
/// </summary>
private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin);
/// <summary>
/// Create a new <see cref="SkinReloadableDrawable"/>
/// </summary>
/// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param>
protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null)
{
this.allowFallback = allowFallback;
}
[BackgroundDependencyLoader]
private void load(ISkinSource source)
{
skin = source;
skin.SourceChanged += onChange;
}
private void onChange() =>
// schedule required to avoid calls after disposed.
// note that this has the side-effect of components only performing a skin change when they are alive.
Scheduler.AddOnce(() => SkinChanged(skin, allowDefaultFallback));
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
SkinChanged(skin, allowDefaultFallback);
}
/// <summary>
/// Called when a change is made to the skin.
/// </summary>
/// <param name="skin">The new skin.</param>
/// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param>
protected virtual void SkinChanged(ISkinSource skin, bool allowFallback)
{
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (skin != null)
skin.SourceChanged -= onChange;
}
}
}
| // 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.Allocation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A drawable which has a callback when the skin changes.
/// </summary>
public abstract class SkinReloadableDrawable : CompositeDrawable
{
private readonly Func<ISkinSource, bool> allowFallback;
private ISkinSource skin;
/// <summary>
/// Whether fallback to default skin should be allowed if the custom skin is missing this resource.
/// </summary>
private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin);
/// <summary>
/// Create a new <see cref="SkinReloadableDrawable"/>
/// </summary>
/// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param>
protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null)
{
this.allowFallback = allowFallback;
}
[BackgroundDependencyLoader]
private void load(ISkinSource source)
{
skin = source;
skin.SourceChanged += onChange;
}
private void onChange() => SkinChanged(skin, allowDefaultFallback);
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
onChange();
}
/// <summary>
/// Called when a change is made to the skin.
/// </summary>
/// <param name="skin">The new skin.</param>
/// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param>
protected virtual void SkinChanged(ISkinSource skin, bool allowFallback)
{
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (skin != null)
skin.SourceChanged -= onChange;
}
}
}
| mit | C# |
fe825029b472249f39d7afd1c6a899b7680be56a | Add basics to load compiled client app | ChristopherJennings/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,Kentico/KInspector,Kentico/KInspector | KenticoInspector.WebApplication/Startup.cs | KenticoInspector.WebApplication/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc();
app.UseSpa(spa => {
spa.Options.SourcePath = "ClientApp";
//if (env.IsDevelopment()) {
// spa.UseProxyToSpaDevelopmentServer("http://localhost:1234");
//}
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace KenticoInspector.WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.