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 |
|---|---|---|---|---|---|---|---|---|
032379eb809c15a286d005aa1144cf1937be2898 | Convert to auto property with initializer | roman-yagodin/R7.Documents,roman-yagodin/R7.Documents,roman-yagodin/R7.Documents | R7.Documents/Models/DocumentSortColumnInfo.cs | R7.Documents/Models/DocumentSortColumnInfo.cs | //
// Copyright (c) 2002-2011 by DotNetNuke Corporation
// Copyright (c) 2014-2018 by Roman M. Yagodin <roman.yagodin@gmail.com>
//
// 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;
namespace R7.Documents.Models
{
[Serializable]
public class DocumentsSortColumnInfo
{
public enum SortDirection
{
Ascending,
Descending
}
public SortDirection Direction { get; set; } = SortDirection.Ascending;
public string ColumnName { get; set; }
public string LocalizedColumnName { get; set; }
}
}
| //
// Copyright (c) 2002-2011 by DotNetNuke Corporation
// Copyright (c) 2014-2015 by Roman M. Yagodin <roman.yagodin@gmail.com>
//
// 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;
namespace R7.Documents.Models
{
[Serializable]
public class DocumentsSortColumnInfo
{
SortDirection _direction = SortDirection.Ascending;
public enum SortDirection
{
Ascending,
Descending
}
public SortDirection Direction
{
get { return _direction; }
set { _direction = value; }
}
public string ColumnName { get; set; }
public string LocalizedColumnName { get; set; }
}
}
| mit | C# |
1e461dc17b04dbbdd4ec93eee1eddc89b9d6c529 | Fix null ref exception in Pipeline Witness. (#891) | tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools | tools/pipeline-witness/Azure.Sdk.Tools.PipelineWitness/Services/FailureAnalysis/MavenBrokenPipeFailureClassifier.cs | tools/pipeline-witness/Azure.Sdk.Tools.PipelineWitness/Services/FailureAnalysis/MavenBrokenPipeFailureClassifier.cs | using Azure.Sdk.Tools.PipelineWitness.Entities.AzurePipelines;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.PipelineWitness.Services.FailureAnalysis
{
public class MavenBrokenPipeFailureClassifier : IFailureClassifier
{
public MavenBrokenPipeFailureClassifier(VssConnection vssConnection)
{
this.vssConnection = vssConnection;
buildClient = vssConnection.GetClient<BuildHttpClient>();
}
private VssConnection vssConnection;
private BuildHttpClient buildClient;
public async Task ClassifyAsync(FailureAnalyzerContext context)
{
var failedTasks = from r in context.Timeline.Records
where r.Result == TaskResult.Failed
where r.RecordType == "Task"
where r.Task != null
where r.Task.Name == "Maven"
where r.Log != null
select r;
foreach (var failedTask in failedTasks)
{
var lines = await buildClient.GetBuildLogLinesAsync(
context.Build.Project.Id,
context.Build.Id,
failedTask.Log.Id
);
if (lines.Any(line => line.Contains("Connection reset")))
{
context.AddFailure(failedTask, "Maven Broken Pipe");
}
}
}
}
}
| using Azure.Sdk.Tools.PipelineWitness.Entities.AzurePipelines;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.PipelineWitness.Services.FailureAnalysis
{
public class MavenBrokenPipeFailureClassifier : IFailureClassifier
{
public MavenBrokenPipeFailureClassifier(VssConnection vssConnection)
{
this.vssConnection = vssConnection;
buildClient = vssConnection.GetClient<BuildHttpClient>();
}
private VssConnection vssConnection;
private BuildHttpClient buildClient;
public async Task ClassifyAsync(FailureAnalyzerContext context)
{
var failedTasks = from r in context.Timeline.Records
where r.Result == TaskResult.Failed
where r.RecordType == "Task"
where r.Task.Name == "Maven"
where r.Log != null
select r;
foreach (var failedTask in failedTasks)
{
var lines = await buildClient.GetBuildLogLinesAsync(
context.Build.Project.Id,
context.Build.Id,
failedTask.Log.Id
);
if (lines.Any(line => line.Contains("Connection reset")))
{
context.AddFailure(failedTask, "Maven Broken Pipe");
}
}
}
}
}
| mit | C# |
87959a59d980286daf6c082ef3edda8494e94bf6 | Add missing "announce" channel type | peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu | osu.Game/Online/Chat/ChannelType.cs | osu.Game/Online/Chat/ChannelType.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.Chat
{
public enum ChannelType
{
Public,
Private,
Multiplayer,
Spectator,
Temporary,
PM,
Group,
System,
Announce,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.Chat
{
public enum ChannelType
{
Public,
Private,
Multiplayer,
Spectator,
Temporary,
PM,
Group,
System,
}
}
| mit | C# |
b808b2681524baadb8ceb88c56e90c4257e52f9a | Delete unused conditions | Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net | src/ZBlog/Components/TopPostsComponent.cs | src/ZBlog/Components/TopPostsComponent.cs | using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using ZBlog.Models;
namespace ZBlog.Components
{
[ViewComponent(Name = "TopPosts")]
public class TopPostsComponent : ViewComponent
{
public TopPostsComponent(ZBlogDbContext dbContext)
{
DbContext = dbContext;
}
private ZBlogDbContext DbContext { get; }
public async Task<IViewComponentResult> InvokeAsync()
{
var posts =
await
DbContext.Posts
.OrderByDescending(p => p.Visits)
.Take(10)
.ToListAsync();
return View(posts);
}
}
} | using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using ZBlog.Models;
namespace ZBlog.Components
{
[ViewComponent(Name = "TopPosts")]
public class TopPostsComponent : ViewComponent
{
public TopPostsComponent(ZBlogDbContext dbContext)
{
DbContext = dbContext;
}
private ZBlogDbContext DbContext { get; }
public async Task<IViewComponentResult> InvokeAsync()
{
var posts =
await
DbContext.Posts.Include(p => p.Catalog)
.Include(p => p.PostTags)
.ThenInclude(p => p.Tag)
.Include(p => p.User)
.OrderByDescending(p => p.Visits)
.Take(10)
.ToListAsync();
return View(posts);
}
}
} | mit | C# |
85afb189673462254517f6625493f7bbf2ff9e66 | Change AssemblyVersion to 1.6.2.0 | gigya/microdot | SolutionVersion.cs | SolutionVersion.cs | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.6.2.0")]
[assembly: AssemblyFileVersion("1.6.2.0")]
[assembly: AssemblyInformationalVersion("1.6.2.0")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.6.1.0")]
[assembly: AssemblyFileVersion("1.6.1.0")]
[assembly: AssemblyInformationalVersion("1.6.1.0")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
b8236af5b7d71eea7af3ec31577cdaff7184c732 | Rename some projection test method names | huysentruitw/projecto | tests/Projecto.Tests/ProjectionTests.cs | tests/Projecto.Tests/ProjectionTests.cs | using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Projecto.Tests.TestClasses;
namespace Projecto.Tests
{
[TestFixture]
public class ProjectionTests
{
[Test]
public void NextSequence_ValueAfterConstruction_ShouldStartAtFetchedValue()
{
Assert.That(new TestProjection(3).NextSequenceNumber, Is.EqualTo(3));
Assert.That(new TestProjection().NextSequenceNumber, Is.EqualTo(1));
}
[Test]
public void NextSequence_GetValueTwice_ShouldNotIncrement()
{
var projection = new TestProjection();
Assert.That(projection.NextSequenceNumber, Is.EqualTo(1));
Assert.That(projection.NextSequenceNumber, Is.EqualTo(1));
}
[Test]
public async Task Handle_SomeMessage_ShouldIncrementNextSequence()
{
IProjection<FakeMessageEnvelope> projection = new TestProjection(5);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(5));
await projection.Handle(() => new FakeConnection(), new FakeMessageEnvelope(5, new MessageA()), CancellationToken.None);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(6));
}
[Test]
public void Handle_TwoDifferentMessages_ShouldCallCorrectHandlerWithCorrectArguments()
{
var connectionMock = new Mock<FakeConnection>();
var token = new CancellationToken();
var messageA = new MessageA();
var messageB = new MessageB();
var messageEnvelopeA = new FakeMessageEnvelope(1, messageA);
var messageEnvelopeB = new FakeMessageEnvelope(2, messageB);
IProjection<FakeMessageEnvelope> projection = new TestProjection();
projection.Handle(() => connectionMock.Object, messageEnvelopeA, token);
projection.Handle(() => connectionMock.Object, messageEnvelopeB, token);
connectionMock.Verify(x => x.UpdateA(messageEnvelopeA, messageA), Times.Once);
connectionMock.Verify(x => x.UpdateB(messageEnvelopeB, messageB, token), Times.Once);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(3));
}
}
}
| using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Projecto.Tests.TestClasses;
namespace Projecto.Tests
{
[TestFixture]
public class ProjectionTests
{
[Test]
public void NextSequence_ValueAfterConstruction_ShouldStartAtFetchedValue()
{
Assert.That(new TestProjection(3).NextSequenceNumber, Is.EqualTo(3));
Assert.That(new TestProjection().NextSequenceNumber, Is.EqualTo(1));
}
[Test]
public void NextSequence_GetValueTwice_ShouldNotIncrement()
{
var projection = new TestProjection();
Assert.That(projection.NextSequenceNumber, Is.EqualTo(1));
Assert.That(projection.NextSequenceNumber, Is.EqualTo(1));
}
[Test]
public async Task NextSequence_HandleMessage_ShouldIncrementNextSequence()
{
IProjection<FakeMessageEnvelope> projection = new TestProjection(5);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(5));
await projection.Handle(() => new FakeConnection(), new FakeMessageEnvelope(5, new MessageA()), CancellationToken.None);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(6));
}
[Test]
public void When_HandleMessages_ShouldCallCorrectHandlerWithCorrectArguments()
{
var connectionMock = new Mock<FakeConnection>();
var token = new CancellationToken();
var messageA = new MessageA();
var messageB = new MessageB();
var messageEnvelopeA = new FakeMessageEnvelope(1, messageA);
var messageEnvelopeB = new FakeMessageEnvelope(2, messageB);
IProjection<FakeMessageEnvelope> projection = new TestProjection();
projection.Handle(() => connectionMock.Object, messageEnvelopeA, token);
projection.Handle(() => connectionMock.Object, messageEnvelopeB, token);
connectionMock.Verify(x => x.UpdateA(messageEnvelopeA, messageA), Times.Once);
connectionMock.Verify(x => x.UpdateB(messageEnvelopeB, messageB, token), Times.Once);
Assert.That(projection.NextSequenceNumber, Is.EqualTo(3));
}
}
}
| apache-2.0 | C# |
10140dfdf426c9598b2e23b5ee183f8d2abcf2da | Format Projection | carbon/Amazon | src/Amazon.DynamoDb/Models/Projection.cs | src/Amazon.DynamoDb/Models/Projection.cs | #nullable disable
using System;
namespace Amazon.DynamoDb
{
public sealed class Projection
{
public Projection() { }
public Projection(string[] nonKeyAttributes, ProjectionType type)
{
NonKeyAttributes = nonKeyAttributes ?? Array.Empty<string>();
ProjectionType = type;
}
public string[] NonKeyAttributes { get; set; }
public ProjectionType ProjectionType { get; set; }
}
} | #nullable disable
using System;
namespace Amazon.DynamoDb
{
public sealed class Projection
{
public Projection() { }
public Projection(string[] nonKeyAttributes, ProjectionType type)
{
NonKeyAttributes = nonKeyAttributes ?? Array.Empty<string>();
ProjectionType = type;
}
public string[] NonKeyAttributes { get; set; }
public ProjectionType ProjectionType { get; set; }
}
} | mit | C# |
2fcc8e44255eb7693493fe9bd7872f3793fe0141 | Add Decode method | mstrother/BmpListener | src/BmpListener/Bgp/OptionalParameter.cs | src/BmpListener/Bgp/OptionalParameter.cs |
using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class OptionalParameter
{
public OptionalParameterType Type { get; private set; }
public int Length { get; private set; }
public virtual void Decode(ArraySegment<byte> data)
{
Type = (OptionalParameterType)data.First();
Length = data.ElementAt(1);
}
}
}
|
namespace BmpListener.Bgp
{
public abstract class OptionalParameter
{
public OptionalParameter(byte[] data, int offset)
{
ParameterType = data[offset];
ParameterLength = data[offset + 1];
}
public int ParameterType { get; }
public int ParameterLength { get; }
}
}
| mit | C# |
c45fb4d3b5c19b4119938ae4a07a560a776dec85 | Add default RepositoryConfigurationException constructor | appharbor/appharbor-cli | src/AppHarbor/RepositoryConfigurationException.cs | src/AppHarbor/RepositoryConfigurationException.cs | using System;
namespace AppHarbor
{
public class RepositoryConfigurationException : Exception
{
public RepositoryConfigurationException()
{
}
public RepositoryConfigurationException(string message)
: base(message)
{
}
}
}
| using System;
namespace AppHarbor
{
public class RepositoryConfigurationException : Exception
{
public RepositoryConfigurationException(string message)
: base(message)
{
}
}
}
| mit | C# |
7b684339ed64703c169dfccc27c3abfec521e586 | Undo public -> internal for `PathControlPoint.Changed` | ppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu | osu.Game/Rulesets/Objects/PathControlPoint.cs | osu.Game/Rulesets/Objects/PathControlPoint.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 Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Objects.Types;
using osuTK;
namespace osu.Game.Rulesets.Objects
{
public class PathControlPoint : IEquatable<PathControlPoint>
{
/// <summary>
/// The position of this <see cref="PathControlPoint"/>.
/// </summary>
[JsonProperty]
public readonly Bindable<Vector2> Position = new Bindable<Vector2>();
/// <summary>
/// The type of path segment starting at this <see cref="PathControlPoint"/>.
/// If null, this <see cref="PathControlPoint"/> will be a part of the previous path segment.
/// </summary>
[JsonProperty]
public readonly Bindable<PathType?> Type = new Bindable<PathType?>();
/// <summary>
/// Invoked when any property of this <see cref="PathControlPoint"/> is changed.
/// </summary>
internal event Action Changed;
/// <summary>
/// Creates a new <see cref="PathControlPoint"/>.
/// </summary>
public PathControlPoint()
{
Position.ValueChanged += _ => Changed?.Invoke();
Type.ValueChanged += _ => Changed?.Invoke();
}
/// <summary>
/// Creates a new <see cref="PathControlPoint"/> with a provided position and type.
/// </summary>
/// <param name="position">The initial position.</param>
/// <param name="type">The initial type.</param>
public PathControlPoint(Vector2 position, PathType? type = null)
: this()
{
Position.Value = position;
Type.Value = type;
}
public bool Equals(PathControlPoint other) => Position.Value == other?.Position.Value && Type.Value == other.Type.Value;
}
}
| // 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 Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Objects.Types;
using osuTK;
namespace osu.Game.Rulesets.Objects
{
public class PathControlPoint : IEquatable<PathControlPoint>
{
/// <summary>
/// The position of this <see cref="PathControlPoint"/>.
/// </summary>
[JsonProperty]
public readonly Bindable<Vector2> Position = new Bindable<Vector2>();
/// <summary>
/// The type of path segment starting at this <see cref="PathControlPoint"/>.
/// If null, this <see cref="PathControlPoint"/> will be a part of the previous path segment.
/// </summary>
[JsonProperty]
public readonly Bindable<PathType?> Type = new Bindable<PathType?>();
/// <summary>
/// Invoked when any property of this <see cref="PathControlPoint"/> is changed.
/// </summary>
public event Action Changed;
/// <summary>
/// Creates a new <see cref="PathControlPoint"/>.
/// </summary>
public PathControlPoint()
{
Position.ValueChanged += _ => Changed?.Invoke();
Type.ValueChanged += _ => Changed?.Invoke();
}
/// <summary>
/// Creates a new <see cref="PathControlPoint"/> with a provided position and type.
/// </summary>
/// <param name="position">The initial position.</param>
/// <param name="type">The initial type.</param>
public PathControlPoint(Vector2 position, PathType? type = null)
: this()
{
Position.Value = position;
Type.Value = type;
}
public bool Equals(PathControlPoint other) => Position.Value == other?.Position.Value && Type.Value == other.Type.Value;
}
}
| mit | C# |
c7f0e9135dd00448c5519da60fade9433e131f56 | Update Core | sunkaixuan/SqlSugar | Src/Asp.Net/SqlSugar/Realization/PostgreSQL/Queryable/PostgreSqlQueryable.cs | Src/Asp.Net/SqlSugar/Realization/PostgreSQL/Queryable/PostgreSqlQueryable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class PostgreSQLQueryable<T> : QueryableProvider<T>
{
public override ISugarQueryable<T> With(string withString)
{
return this;
}
public override ISugarQueryable<T> PartitionBy(string groupFileds)
{
this.GroupBy(groupFileds);
return this;
}
}
public class PostgreSQLQueryable<T, T2> : QueryableProvider<T, T2>
{
public new ISugarQueryable<T, T2> With(string withString)
{
return this;
}
}
public class PostgreSQLQueryable<T, T2, T3> : QueryableProvider<T, T2, T3>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4> : QueryableProvider<T, T2, T3, T4>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5> : QueryableProvider<T, T2, T3, T4, T5>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6> : QueryableProvider<T, T2, T3, T4, T5, T6>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7> : QueryableProvider<T, T2, T3, T4, T5, T6, T7>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class PostgreSQLQueryable<T> : QueryableProvider<T>
{
public override ISugarQueryable<T> With(string withString)
{
return this;
}
public override ISugarQueryable<T> PartitionBy(string groupFileds)
{
this.GroupBy(groupFileds);
return this;
}
}
public class PostgreSQLQueryable<T, T2> : QueryableProvider<T, T2>
{
public new ISugarQueryable<T, T2> With(string withString)
{
return this;
}
}
public class PostgreSQLQueryable<T, T2, T3> : QueryableProvider<T, T2, T3>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4> : QueryableProvider<T, T2, T3, T4>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5> : QueryableProvider<T, T2, T3, T4, T5>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6> : QueryableProvider<T, T2, T3, T4, T5, T6>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7> : QueryableProvider<T, T2, T3, T4, T5, T6, T7>
{
}
public class PostgreSqlQueryable<T, T2, T3, T4, T5, T6, T7, T8> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
{
}
public class PostgreSQLQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
{
}
}
| apache-2.0 | C# |
7b6619a16180a74c1bfbbfa2f107457573fa4242 | add split audio function | Haishi2016/Vault818,Haishi2016/Vault818,Haishi2016/Vault818,Haishi2016/Vault818,Haishi2016/Vault818,Haishi2016/Vault818,Haishi2016/Vault818 | Med-Bay/NAudioFunctions/NAudioFunctions/Program.cs | Med-Bay/NAudioFunctions/NAudioFunctions/Program.cs | using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NAudioFunctions
{
class Program
{
static void Main(string[] args)
{
string inputFile = "exciting.wav";
string outputFile = Path.GetFileNameWithoutExtension(inputFile) + "_mono.wav";
ConvertWaveToMonoWave(inputFile, outputFile);
SplitWaveFile(inputFile, Path.GetFileNameWithoutExtension(inputFile) + "{0}.wav", 1);
}
static void ConvertMP3toWave(string file, string outputFile)
{
using (Mp3FileReader reader = new Mp3FileReader(file))
{
WaveFileWriter.CreateWaveFile(outputFile, reader);
}
}
static void ConvertWaveToMonoWave(string file, string outputFile)
{
using (WaveFileReader reader = new WaveFileReader(file))
{
WaveFormat format = new WaveFormat(16000, 16, 1);
using (var conversionStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
using (var upSampler = new WaveFormatConversionStream(format, conversionStream))
{
WaveFileWriter.CreateWaveFile(outputFile, upSampler);
}
}
}
}
static void SplitWaveFile(string file, string outputFilePattern, int chunkSizeinSeconds)
{
using (WaveFileReader reader = new WaveFileReader(file))
{
int bufferSize = reader.WaveFormat.AverageBytesPerSecond;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
int fileCount = 1;
string fileName = string.Format(outputFilePattern, fileCount);
WaveFileWriter writer = null;
while ((bytesRead = reader.Read(buffer,0, buffer.Length)) > 0)
{
if (writer == null)
writer = new WaveFileWriter(string.Format(outputFilePattern, fileCount), reader.WaveFormat);
writer.Write(buffer, 0, bytesRead);
if (reader.Position >= reader.Length - 1 || reader.Position >= chunkSizeinSeconds * bufferSize * fileCount)
{
writer.Close();
writer.Dispose();
writer = null;
fileCount++;
}
}
}
}
}
}
| using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NAudioFunctions
{
class Program
{
static void Main(string[] args)
{
string inputFile = "exciting.wav";
string outputFile = Path.GetFileNameWithoutExtension(inputFile) + "_mono.wav";
ConvertWaveToMonoWave(inputFile, outputFile);
}
static void ConvertMP3toWave(string file, string outputFile)
{
using (Mp3FileReader reader = new Mp3FileReader(file))
{
WaveFileWriter.CreateWaveFile(outputFile, reader);
}
}
static void ConvertWaveToMonoWave(string file, string outputFile)
{
using (WaveFileReader reader = new WaveFileReader(file))
{
WaveFormat format = new WaveFormat(16000, 16, 1);
using (var conversionStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
using (var upSampler = new WaveFormatConversionStream(format, conversionStream))
{
WaveFileWriter.CreateWaveFile(outputFile, upSampler);
}
}
}
}
}
}
| mit | C# |
7596d33563c423516b20f10432854f525a6c0994 | Update PokemonExtension.cs | PokemonUnity/PokemonUnity | PokemonUnity.Shared/Extensions/PokemonExtension.cs | PokemonUnity.Shared/Extensions/PokemonExtension.cs | using System.Collections;
namespace PokemonUnity
{
public static class PokemonExtension
{
public static bool IsNotNullOrNone(this PokemonUnity.Monster.Pokemon pokemon)
{
return pokemon != null || pokemon.Species != Pokemons.NONE;
}
public static bool IsNotNullOrNone(this PokemonUnity.Battle.Pokemon pokemon)
{
return pokemon != null || pokemon.Species != Pokemons.NONE;
}
public static string ToString(this PokemonUnity.Monster.Stats stat, TextScripts text)
{
//create a switch, and return Locale Name or Description
return stat.ToString();
}
public static string ToString(this PokemonUnity.Battle.Stats stat, TextScripts text)
{
//create a switch, and return Locale Name or Description
return stat.ToString();
}
public static string ToString(this PokemonUnity.Monster.Forms form, TextScripts text)
{
//create an operator and return Locale Name
return form.ToString();
}
public static string ToString(this PokemonUnity.Pokemons pokemon, TextScripts text)
{
//create a switch, and return Locale Name or Description
return pokemon.ToString();
}
}
} | using System.Collections;
namespace PokemonUnity
{
public static class PokemonExtension
{
public static bool IsNotNullOrNone(this PokemonUnity.Monster.Pokemon pokemon)
{
return pokemon != null || pokemon.Species != Pokemons.NONE;
}
public static bool IsNotNullOrNone(this PokemonUnity.Battle.Pokemon pokemon)
{
return pokemon != null || pokemon.Species != Pokemons.NONE;
}
public static string ToString(this PokemonUnity.Monster.Stats stat, TextScripts text)
{
//create a switch, and return Locale Name or Description
return stat.ToString();
}
public static string ToString(this PokemonUnity.Battle.Stats stat, TextScripts text)
{
//create a switch, and return Locale Name or Description
return stat.ToString();
}
public static string ToString(this PokemonUnity.Pokemons pokemon, TextScripts text)
{
//create a switch, and return Locale Name or Description
return pokemon.ToString();
}
}
} | bsd-3-clause | C# |
8e5365cb65c2c4bea243dc3dad2b7db4500f1b6c | Add JsonConstructor attribute to Bounds (#92) | chadly/Geocoding.net | src/Geocoding.Core/Bounds.cs | src/Geocoding.Core/Bounds.cs | using Newtonsoft.Json;
using System;
namespace Geocoding
{
public class Bounds
{
readonly Location southWest;
readonly Location northEast;
public Location SouthWest
{
get { return southWest; }
}
public Location NorthEast
{
get { return northEast; }
}
public Bounds(double southWestLatitude, double southWestLongitude, double northEastLatitude, double northEastLongitude)
: this(new Location(southWestLatitude, southWestLongitude), new Location(northEastLatitude, northEastLongitude)) { }
[JsonConstructor]
public Bounds(Location southWest, Location northEast)
{
if (southWest == null)
throw new ArgumentNullException("southWest");
if (northEast == null)
throw new ArgumentNullException("northEast");
if (southWest.Latitude > northEast.Latitude)
throw new ArgumentException("southWest latitude cannot be greater than northEast latitude");
this.southWest = southWest;
this.northEast = northEast;
}
public override bool Equals(object obj)
{
return Equals(obj as Bounds);
}
public bool Equals(Bounds bounds)
{
if (bounds == null)
return false;
return (this.SouthWest.Equals(bounds.SouthWest) && this.NorthEast.Equals(bounds.NorthEast));
}
public override int GetHashCode()
{
return SouthWest.GetHashCode() ^ NorthEast.GetHashCode();
}
public override string ToString()
{
return string.Format("{0} | {1}", southWest, northEast);
}
}
}
| using System;
namespace Geocoding
{
public class Bounds
{
readonly Location southWest;
readonly Location northEast;
public Location SouthWest
{
get { return southWest; }
}
public Location NorthEast
{
get { return northEast; }
}
public Bounds(double southWestLatitude, double southWestLongitude, double northEastLatitude, double northEastLongitude)
: this(new Location(southWestLatitude, southWestLongitude), new Location(northEastLatitude, northEastLongitude)) { }
public Bounds(Location southWest, Location northEast)
{
if (southWest == null)
throw new ArgumentNullException("southWest");
if (northEast == null)
throw new ArgumentNullException("northEast");
if (southWest.Latitude > northEast.Latitude)
throw new ArgumentException("southWest latitude cannot be greater than northEast latitude");
this.southWest = southWest;
this.northEast = northEast;
}
public override bool Equals(object obj)
{
return Equals(obj as Bounds);
}
public bool Equals(Bounds bounds)
{
if (bounds == null)
return false;
return (this.SouthWest.Equals(bounds.SouthWest) && this.NorthEast.Equals(bounds.NorthEast));
}
public override int GetHashCode()
{
return SouthWest.GetHashCode() ^ NorthEast.GetHashCode();
}
public override string ToString()
{
return string.Format("{0} | {1}", southWest, northEast);
}
}
}
| mit | C# |
2195d7be7103d6dec462735d8525082afaa11384 | edit TODO list | yaronthurm/Pinger | Pinger/Code/Program.cs | Pinger/Code/Program.cs | using System;
using System.IO;
using System.Windows.Forms;
namespace PingTester
{
static class Program
{
/* TODO:
* issue 1: add support to new file format (xml)
* issue 2: add full support for telnet, ssh, remote desktop, vnc (icons and prebuilt passwords)
* issue 3: add log file to ping responses and state changes
* issue 4: add indication to name of opend file
* issue 5: add status bar indication how much online/offline
*
* issue 6: add support for rapid ping (lots of users sending ping at once)
* issue 7: add response time to stats (min, max, avg)
*/
public const string LastPingerFileName = "pinger_history.txt";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] Args)
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmMain main = new FrmMain();
main.LastPingerFileName = Path.Combine(System.Environment.CurrentDirectory, Program.LastPingerFileName);
if (Args.Length > 0)
main.StartupFileName = Args[0];
else
main.StartupFileName = main.LastPingerFileName;
Application.Run(main);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
}
}
| using System;
using System.IO;
using System.Windows.Forms;
namespace PingTester
{
static class Program
{
/* TODO:
* add support to new file format (xml)
* add full support for telnet, ssh, remote desktop, vnc (icons and prebuilt passwords)
* add log file to ping responses and state changes
* add indication to name of opend file
* add status bar indication how much online/offline
*
* add support for rapid ping (lots of users sending ping at once)
* add response time to stats (min, max, avg)
*/
public const string LastPingerFileName = "pinger_history.txt";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] Args)
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmMain main = new FrmMain();
main.LastPingerFileName = Path.Combine(System.Environment.CurrentDirectory, Program.LastPingerFileName);
if (Args.Length > 0)
main.StartupFileName = Args[0];
else
main.StartupFileName = main.LastPingerFileName;
Application.Run(main);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
}
}
| mit | C# |
f7a9c86794efd323970b655e9009d6cb05d4705f | Tidy up code to meet stylecop rules | daniellor/Nancy,tsdl2013/Nancy,lijunle/Nancy,EIrwin/Nancy,charleypeng/Nancy,albertjan/Nancy,MetSystem/Nancy,danbarua/Nancy,grumpydev/Nancy,jmptrader/Nancy,AlexPuiu/Nancy,cgourlay/Nancy,VQComms/Nancy,wtilton/Nancy,AcklenAvenue/Nancy,EliotJones/NancyTest,Worthaboutapig/Nancy,felipeleusin/Nancy,sadiqhirani/Nancy,EIrwin/Nancy,davidallyoung/Nancy,nicklv/Nancy,jchannon/Nancy,sroylance/Nancy,JoeStead/Nancy,xt0rted/Nancy,ayoung/Nancy,ccellar/Nancy,rudygt/Nancy,JoeStead/Nancy,jeff-pang/Nancy,jeff-pang/Nancy,anton-gogolev/Nancy,JoeStead/Nancy,blairconrad/Nancy,nicklv/Nancy,vladlopes/Nancy,albertjan/Nancy,horsdal/Nancy,adamhathcock/Nancy,sloncho/Nancy,anton-gogolev/Nancy,charleypeng/Nancy,damianh/Nancy,Crisfole/Nancy,sadiqhirani/Nancy,tareq-s/Nancy,sroylance/Nancy,jchannon/Nancy,Crisfole/Nancy,albertjan/Nancy,tsdl2013/Nancy,lijunle/Nancy,khellang/Nancy,wtilton/Nancy,danbarua/Nancy,malikdiarra/Nancy,joebuschmann/Nancy,rudygt/Nancy,sloncho/Nancy,AlexPuiu/Nancy,damianh/Nancy,sadiqhirani/Nancy,AIexandr/Nancy,EIrwin/Nancy,tsdl2013/Nancy,NancyFx/Nancy,jonathanfoster/Nancy,AIexandr/Nancy,davidallyoung/Nancy,jchannon/Nancy,tparnell8/Nancy,albertjan/Nancy,ayoung/Nancy,EIrwin/Nancy,daniellor/Nancy,adamhathcock/Nancy,murador/Nancy,lijunle/Nancy,joebuschmann/Nancy,kekekeks/Nancy,charleypeng/Nancy,VQComms/Nancy,hitesh97/Nancy,blairconrad/Nancy,joebuschmann/Nancy,dbolkensteyn/Nancy,wtilton/Nancy,dbabox/Nancy,NancyFx/Nancy,ayoung/Nancy,jeff-pang/Nancy,felipeleusin/Nancy,asbjornu/Nancy,ayoung/Nancy,jmptrader/Nancy,AIexandr/Nancy,rudygt/Nancy,asbjornu/Nancy,thecodejunkie/Nancy,NancyFx/Nancy,AcklenAvenue/Nancy,jchannon/Nancy,malikdiarra/Nancy,Novakov/Nancy,sloncho/Nancy,jongleur1983/Nancy,sloncho/Nancy,EliotJones/NancyTest,phillip-haydon/Nancy,AlexPuiu/Nancy,daniellor/Nancy,AcklenAvenue/Nancy,jongleur1983/Nancy,malikdiarra/Nancy,cgourlay/Nancy,tparnell8/Nancy,SaveTrees/Nancy,guodf/Nancy,Worthaboutapig/Nancy,jongleur1983/Nancy,dbolkensteyn/Nancy,guodf/Nancy,danbarua/Nancy,jonathanfoster/Nancy,cgourlay/Nancy,nicklv/Nancy,jmptrader/Nancy,EliotJones/NancyTest,VQComms/Nancy,dbolkensteyn/Nancy,adamhathcock/Nancy,vladlopes/Nancy,jeff-pang/Nancy,MetSystem/Nancy,Novakov/Nancy,sadiqhirani/Nancy,asbjornu/Nancy,VQComms/Nancy,murador/Nancy,davidallyoung/Nancy,grumpydev/Nancy,dbabox/Nancy,murador/Nancy,MetSystem/Nancy,asbjornu/Nancy,Worthaboutapig/Nancy,vladlopes/Nancy,VQComms/Nancy,xt0rted/Nancy,dbabox/Nancy,thecodejunkie/Nancy,SaveTrees/Nancy,guodf/Nancy,tareq-s/Nancy,sroylance/Nancy,hitesh97/Nancy,AIexandr/Nancy,kekekeks/Nancy,phillip-haydon/Nancy,blairconrad/Nancy,xt0rted/Nancy,sroylance/Nancy,guodf/Nancy,charleypeng/Nancy,jongleur1983/Nancy,fly19890211/Nancy,cgourlay/Nancy,grumpydev/Nancy,duszekmestre/Nancy,EliotJones/NancyTest,phillip-haydon/Nancy,ccellar/Nancy,tsdl2013/Nancy,JoeStead/Nancy,jonathanfoster/Nancy,joebuschmann/Nancy,Novakov/Nancy,dbabox/Nancy,duszekmestre/Nancy,daniellor/Nancy,grumpydev/Nancy,tareq-s/Nancy,danbarua/Nancy,kekekeks/Nancy,rudygt/Nancy,ccellar/Nancy,phillip-haydon/Nancy,tparnell8/Nancy,thecodejunkie/Nancy,lijunle/Nancy,hitesh97/Nancy,SaveTrees/Nancy,fly19890211/Nancy,horsdal/Nancy,asbjornu/Nancy,adamhathcock/Nancy,SaveTrees/Nancy,AIexandr/Nancy,khellang/Nancy,Crisfole/Nancy,Novakov/Nancy,MetSystem/Nancy,fly19890211/Nancy,horsdal/Nancy,felipeleusin/Nancy,horsdal/Nancy,xt0rted/Nancy,damianh/Nancy,AlexPuiu/Nancy,vladlopes/Nancy,blairconrad/Nancy,anton-gogolev/Nancy,davidallyoung/Nancy,fly19890211/Nancy,davidallyoung/Nancy,malikdiarra/Nancy,tareq-s/Nancy,AcklenAvenue/Nancy,thecodejunkie/Nancy,felipeleusin/Nancy,NancyFx/Nancy,charleypeng/Nancy,tparnell8/Nancy,jonathanfoster/Nancy,khellang/Nancy,jmptrader/Nancy,duszekmestre/Nancy,dbolkensteyn/Nancy,wtilton/Nancy,Worthaboutapig/Nancy,jchannon/Nancy,murador/Nancy,ccellar/Nancy,hitesh97/Nancy,anton-gogolev/Nancy,duszekmestre/Nancy,nicklv/Nancy,khellang/Nancy | src/Nancy.Testing/BrowserContextExtensions.cs | src/Nancy.Testing/BrowserContextExtensions.cs | namespace Nancy.Testing
{
using System.IO;
using Nancy.Responses;
/// <summary>
/// Defines extensions for the <see cref="BrowserContext"/> type.
/// </summary>
public static class BrowserContextExtensions
{
/// <summary>
/// Adds a multipart/form-data encoded request body to the <see cref="Browser"/>, using the default boundary name.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="multipartFormData">The multipart/form-data encoded data that should be added.</param>
public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData)
{
MultiPartFormData(browserContext, multipartFormData, BrowserContextMultipartFormData.DefaultBoundaryName);
}
/// <summary>
/// Adds a multipart/form-data encoded request body to the <see cref="Browser"/>.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="multipartFormData">The multipart/form-data encoded data that should be added.</param>
/// <param name="boundaryName">The name of the boundary to be used</param>
public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData, string boundaryName)
{
var contextValues =
(IBrowserContextValues)browserContext;
contextValues.Body = multipartFormData.Body;
contextValues.Headers["Content-Type"] = new[] { "multipart/form-data; boundary=" + boundaryName };
}
/// <summary>
/// Adds a application/json request body to the <see cref="Browser"/>.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="model">The model to be serialized to json.</param>
/// <param name="serializer">Optionally opt in to using a different JSON serializer.</param>
public static void JsonBody<TModel>(this BrowserContext browserContext, TModel model, ISerializer serializer = null)
{
if (serializer == null)
{
serializer = new DefaultJsonSerializer();
}
var contextValues =
(IBrowserContextValues)browserContext;
contextValues.Body = new MemoryStream();
serializer.Serialize("application/json", model, contextValues.Body);
browserContext.Header("Content-Type", "application/json");
}
}
} | namespace Nancy.Testing
{
using Nancy.Json;
/// <summary>
/// Defines extensions for the <see cref="BrowserContext"/> type.
/// </summary>
public static class BrowserContextExtensions
{
/// <summary>
/// Adds a multipart/form-data encoded request body to the <see cref="Browser"/>, using the default boundary name.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="multipartFormData">The multipart/form-data encoded data that should be added.</param>
public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData)
{
MultiPartFormData(browserContext, multipartFormData, BrowserContextMultipartFormData.DefaultBoundaryName);
}
/// <summary>
/// Adds a multipart/form-data encoded request body to the <see cref="Browser"/>.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="multipartFormData">The multipart/form-data encoded data that should be added.</param>
/// <param name="boundaryName">The name of the boundary to be used</param>
public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData, string boundaryName)
{
var contextValues =
(IBrowserContextValues)browserContext;
contextValues.Body = multipartFormData.Body;
contextValues.Headers["Content-Type"] = new[] { "multipart/form-data; boundary=" + boundaryName };
}
/// <summary>
/// Adds a application/json request body to the <see cref="Browser"/>.
/// </summary>
/// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
/// <param name="model">The model to be serialized to json.</param>
public static void JsonBody(this BrowserContext browserContext, object model)
{
var serializer = new JavaScriptSerializer();
var content = serializer.Serialize(model);
browserContext.Body(content);
browserContext.Header("Content-Type", "application/json");
}
}
} | mit | C# |
7bc6cab72e3bc3ec3cffe026257fa3d8d4b5f6ba | Fix samples | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/CookieSample/Startup.cs | samples/CookieSample/Startup.cs | using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Framework.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddWebEncoders();
services.AddDataProtection();
}
public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthentication = true;
});
app.Run(async context =>
{
if (string.IsNullOrEmpty(context.User.Identity.Name))
{
context.Response.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") })));
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello First timer");
return;
}
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello old timer");
});
}
}
} | using System.Security.Claims;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Framework.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddWebEncoders();
services.AddDataProtection();
}
public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(options =>
{
});
app.Run(async context =>
{
if (context.User == null || !context.User.Identity.IsAuthenticated)
{
context.Response.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("name", "bob") })));
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello First timer");
return;
}
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello old timer");
});
}
}
} | apache-2.0 | C# |
81ec54e7cf3abcee0fb7d44b9cf4c2e5f68414a4 | Correct second copy of severity mappings to be compatible with Loupe. | GibraltarSoftware/Loupe.Agent.Core,GibraltarSoftware/Loupe.Agent.Core,GibraltarSoftware/Loupe.Agent.Core | src/Agent/LogMessageSeverity.cs | src/Agent/LogMessageSeverity.cs | using System;
using Microsoft.Extensions.Logging;
namespace Gibraltar.Agent
{
/// <summary>
/// This enumerates the severity levels used by Loupe log messages.
/// </summary>
/// <remarks>The values for these levels are chosen to directly map to the TraceEventType enum
/// for the five levels we support. These also can be mapped from Log4Net event levels,
/// with slight name changes for Fatal->Critical and for Debug->Verbose.</remarks>
[Flags]
public enum LogMessageSeverity
{
/// <summary>
/// The severity level is uninitialized and thus unknown.
/// </summary>
None = 0, // FxCop demands we have a defined 0.
/// <summary>
/// Fatal error or application crash.
/// </summary>
Critical = Loupe.Extensibility.Data.LogMessageSeverity.Critical,
/// <summary>
/// Recoverable error.
/// </summary>
Error = Loupe.Extensibility.Data.LogMessageSeverity.Error,
/// <summary>
/// Noncritical problem.
/// </summary>
Warning = Loupe.Extensibility.Data.LogMessageSeverity.Warning,
/// <summary>
/// Informational message.
/// </summary>
Information = Loupe.Extensibility.Data.LogMessageSeverity.Information,
/// <summary>
/// Debugging trace.
/// </summary>
Verbose = Loupe.Extensibility.Data.LogMessageSeverity.Verbose,
}
}
| using System;
using Microsoft.Extensions.Logging;
namespace Gibraltar.Agent
{
/// <summary>
/// This enumerates the severity levels used by Loupe log messages.
/// </summary>
/// <remarks>The values for these levels are chosen to directly map to the TraceEventType enum
/// for the five levels we support. These also can be mapped from Log4Net event levels,
/// with slight name changes for Fatal->Critical and for Debug->Verbose.</remarks>
[Flags]
public enum LogMessageSeverity
{
/// <summary>
/// The severity level is uninitialized and thus unknown.
/// </summary>
None = 0, // FxCop demands we have a defined 0.
/// <summary>
/// Fatal error or application crash.
/// </summary>
Critical = LogLevel.Critical,
/// <summary>
/// Recoverable error.
/// </summary>
Error = LogLevel.Error,
/// <summary>
/// Noncritical problem.
/// </summary>
Warning = LogLevel.Warning,
/// <summary>
/// Informational message.
/// </summary>
Information = LogLevel.Information,
/// <summary>
/// Debugging trace.
/// </summary>
Verbose = LogLevel.Debug,
}
}
| mit | C# |
a5098e9cc86be2650e8dcb5c166b77ccb10a8d7e | Update Signing.cs | stunney/NAntExtensions,stunney/NAntExtensions | NAnt.Extensions/Functions/Microsoft/Signing.cs | NAnt.Extensions/Functions/Microsoft/Signing.cs | /*
The MIT License (MIT)
Copyright (c) 2013-2014 Dave Tuchlinsky, Stephen Tunney, Canada (stephen.tunney@gmail.com)
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 NAnt.Core;
using NAnt.Core.Attributes;
using System.Linq;
using System.Management.Automation;
namespace NAnt.Extensions.Functions.Microsoft
{
[FunctionSet("signtool", "Signtool")]
public class SigningFunctions : FunctionSetBase
{
public SigningFunctions(Project project, PropertyDictionary dictionary): base(project, dictionary)
{
}
[Function("is-signed")]
public static bool IsSigned(string filePath)
{
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Get-AuthenticodeSignature", true);
ps.AddParameter("FilePath", filePath);
return ((Signature)ps.Invoke().First().BaseObject).Status.Equals(SignatureStatus.Valid);
}
}
}
}
| /*
The MIT License (MIT)
Copyright (c) 2013-2014 Dave Tuchlinsky, Stephen Tunney, Canada (stephen.tunney@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using NAnt.Core;
using NAnt.Core.Attributes;
namespace NAnt.Extensions.Functions.Microsoft
{
/// <summary>
///
/// </summary>
[FunctionSet("signtool", "Signtool")]
public class SigningFunctions : NAnt.Core.FunctionSetBase
{
public SigningFunctions(Project project, PropertyDictionary dictionary)
: base(project, dictionary)
{
}
/// <summary>
///
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
[Function("is-signed")]
public static bool IsSigned(string filePath)
{
if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
try
{
System.Security.Cryptography.X509Certificates.X509Certificate certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(filePath);
// An exception would be thrown if the file was not signed
return true;
}
catch (Exception e) { }
return false;
}
}
}
| mit | C# |
5ebae2e9625164f77acd2a68bc7a62b81846cc80 | fix duplciated X-App-Version | signumsoftware/framework,signumsoftware/framework,AlejandroCano/framework,AlejandroCano/framework,avifatal/framework,avifatal/framework | Signum.React/Filters/VersionFilterAttribute.cs | Signum.React/Filters/VersionFilterAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Signum.React.Filters
{
public class VersionFilterAttribute : ActionFilterAttribute
{
//In Global.asax: VersionFilterAttribute.CurrentVersion = CustomAssembly.GetName().Version.ToString()
public static string CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
public override void OnActionExecuted(HttpActionExecutedContext actionContext)
{
base.OnActionExecuted(actionContext);
SetHeader(actionContext.Response.Headers);
}
private void SetHeader(HttpResponseHeaders headers)
{
if (!headers.Contains("X-App-Version"))
headers.Add("X-App-Version", CurrentVersion);
}
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
SetHeader(actionExecutedContext.Response.Headers);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Signum.React.Filters
{
public class VersionFilterAttribute : ActionFilterAttribute
{
//In Global.asax: VersionFilterAttribute.CurrentVersion = CustomAssembly.GetName().Version.ToString()
public static string CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
public override void OnActionExecuted(HttpActionExecutedContext actionContext)
{
base.OnActionExecuted(actionContext);
actionContext.Response.Headers.Add("X-App-Version", CurrentVersion);
}
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
actionExecutedContext.Response.Headers.Add("X-App-Version", CurrentVersion);
}
}
} | mit | C# |
2361eee47dbdee8b5052312af265105c5b0d37e5 | Update version number. | MarimerLLC/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,rockfordlhotka/csla,jonnybee/csla,BrettJaner/csla,ronnymgm/csla-light,BrettJaner/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,jonnybee/csla,ronnymgm/csla-light,JasonBock/csla,BrettJaner/csla,JasonBock/csla | Source/Csla.Android/Properties/AssemblyInfo.cs | Source/Csla.Android/Properties/AssemblyInfo.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
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("CSLA .NET for Android")]
[assembly: AssemblyDescription("CSLA .NET for Android")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Marimer LLC")]
[assembly: AssemblyProduct("CSLA .NET")]
[assembly: AssemblyCopyright("Copyright 2010-11 Marimer LLC")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(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.*")]
[assembly: AssemblyVersion("4.2.0.0")]
[assembly: AssemblyFileVersion("4.2.0.0")]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
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("CSLA .NET for Android")]
[assembly: AssemblyDescription("CSLA .NET for Android")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Marimer LLC")]
[assembly: AssemblyProduct("CSLA .NET")]
[assembly: AssemblyCopyright("Copyright 2010-11 Marimer LLC")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(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.*")]
[assembly: AssemblyVersion("4.1.0.0")]
[assembly: AssemblyFileVersion("4.1.0.0")]
| mit | C# |
20914162ea7391098df9b8b62e0c789be08665d3 | Increase version number. | stackia/SteamFriendsManager | SteamFriendsManager/Properties/AssemblyInfo.cs | SteamFriendsManager/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Steam Friends Manager")]
[assembly: AssemblyDescription("Manage your Steam friends without the original Steam client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stackia")]
[assembly: AssemblyProduct("Steam Friends Manager")]
[assembly: AssemblyCopyright("Copyright © Stackia 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.*")]
[assembly: AssemblyFileVersion("1.1")]
[assembly: NeutralResourcesLanguage("zh")] | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Steam Friends Manager")]
[assembly: AssemblyDescription("Manage your Steam friends without the original Steam client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stackia")]
[assembly: AssemblyProduct("Steam Friends Manager")]
[assembly: AssemblyCopyright("Copyright © Stackia 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")]
[assembly: NeutralResourcesLanguage("zh")] | bsd-3-clause | C# |
95a0652c02703760e5e7cccea72017c58b4a25ec | fix NUnit test identification warnings | ssg/HashDepot | test/FnvTestVector.cs | test/FnvTestVector.cs | // Copyright (c) 2015, 2016 Sedat Kapanoglu
// MIT License - see LICENSE file for details
using System;
namespace HashDepot.Test
{
public class FnvTestVector
{
public byte[] Buffer { get; set; }
public uint ExpectedResult32 { get; set; }
public ulong ExpectedResult64 { get; set; }
public override string ToString()
{
return BitConverter.ToString(Buffer)
+ ExpectedResult32.ToString()
+ ExpectedResult64.ToString();
}
}
} | // Copyright (c) 2015, 2016 Sedat Kapanoglu
// MIT License - see LICENSE file for details
namespace HashDepot.Test
{
public class FnvTestVector
{
public byte[] Buffer { get; set; }
public uint ExpectedResult32 { get; set; }
public ulong ExpectedResult64 { get; set; }
}
} | mit | C# |
4d47fa9fa0153d183854fc677463fe754d85e40f | allow setting inputsmodel to null | ResourceDataInc/Simpler.Data,gregoryjscott/Simpler,ResourceDataInc/Simpler.Data,gregoryjscott/Simpler,ResourceDataInc/Simpler.Data | Simpler/TaskTITO.cs | Simpler/TaskTITO.cs | using Simpler.Injection;
namespace Simpler
{
/// <summary>
/// Task that accepts Type In and Type Out, meaning that generic types that are provided
/// to this Task subclass that will be used to produce strongly typed inputs and outputs
/// made available through the InputsModels and OutputsModels properties.
/// </summary>
/// <typeparam name="TI">The type for InputsModel.</typeparam>
/// <typeparam name="TO">The type for OutputsModel.</typeparam>
[InjectSubTasks]
public abstract class Task<TI, TO> : Task
{
public override dynamic Inputs
{
get { return InputsModel; }
set
{
InputsModel = value == null
? default(TI)
: Mapper.Map<TI>(value);
}
}
public override dynamic Outputs
{
get { return OutputsModel; }
set
{
OutputsModel = value == null
? default(TO)
: Mapper.Map<TO>(value);
}
}
/// <summary>
/// Typed container for the data the task needs to execute.
/// </summary>
public virtual TI InputsModel { get; set; }
/// <summary>
/// Typed container for the data the task produces.
/// </summary>
public virtual TO OutputsModel { get; set; }
/// <summary>
/// Shorthand method for setting the InputsModel, executing, and receiving the outputs in one line of code.
/// </summary>
/// <param name="inputsModel">Used to set InputsModel prior to execution.</param>
/// <returns>The TaskTITO that allows for .Outputs or .OutputsModel.</returns>
public Task<TI, TO> Execute(TI inputsModel)
{
InputsModel = inputsModel;
Execute();
return this;
}
}
}
| using Simpler.Injection;
namespace Simpler
{
/// <summary>
/// Task that accepts Type In and Type Out, meaning that generic types that are provided
/// to this Task subclass that will be used to produce strongly typed inputs and outputs
/// made available through the InputsModels and OutputsModels properties.
/// </summary>
/// <typeparam name="TI">The type for InputsModel.</typeparam>
/// <typeparam name="TO">The type for OutputsModel.</typeparam>
[InjectSubTasks]
public abstract class Task<TI, TO> : Task
{
public override dynamic Inputs
{
get { return InputsModel; }
set
{
InputsModel = Mapper.Map<TI>(value);
}
}
public override dynamic Outputs
{
get { return OutputsModel; }
set
{
OutputsModel = Mapper.Map<TO>(value);
}
}
/// <summary>
/// Typed container for the data the task needs to execute.
/// </summary>
public virtual TI InputsModel { get; set; }
/// <summary>
/// Typed container for the data the task produces.
/// </summary>
public virtual TO OutputsModel { get; set; }
/// <summary>
/// Shorthand method for setting the InputsModel, executing, and receiving the outputs in one line of code.
/// </summary>
/// <param name="inputsModel">Used to set InputsModel prior to execution.</param>
/// <returns>The TaskTITO that allows for .Outputs or .OutputsModel.</returns>
public Task<TI, TO> Execute(TI inputsModel)
{
InputsModel = inputsModel;
Execute();
return this;
}
}
}
| mit | C# |
6ed115dbf89cdd96755d0acb2a15ddcf24deefdc | Add clear history functionality | tsolarin/readline,tsolarin/readline | src/ReadLine/ReadLine.cs | src/ReadLine/ReadLine.cs | using System.Collections.Generic;
namespace System
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
private static List<string> _history;
public static List<string> History
{
get
{
return _history;
}
}
public static Func<string, int, string[]> AutoCompletionHandler { private get; set; }
static ReadLine()
{
_history = new List<string>();
}
public static void AddHistory(params string[] text) => _history.AddRange(text);
public static void ClearHistory() => _history = new List<string>();
public static string Read()
{
_keyHandler = new KeyHandler(_history, AutoCompletionHandler);
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
Console.WriteLine();
string text = _keyHandler.Text;
_history.Add(text);
return text;
}
}
}
| using System.Collections.Generic;
namespace System
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
private static List<string> _history;
public static List<string> History
{
get
{
return _history;
}
}
public static Func<string, int, string[]> AutoCompletionHandler { private get; set; }
static ReadLine()
{
_history = new List<string>();
}
public static void AddHistory(params string[] text) => _history.AddRange(text);
public static string Read()
{
_keyHandler = new KeyHandler(_history, AutoCompletionHandler);
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
Console.WriteLine();
string text = _keyHandler.Text;
_history.Add(text);
return text;
}
}
}
| mit | C# |
5c9310b475cf87256ce772cb959cf66deefd3a3e | Update ActivateTests.cs | z4kn4fein/stashbox | test/ActivateTests.cs | test/ActivateTests.cs | using Stashbox.Attributes;
using System;
using Xunit;
namespace Stashbox.Tests
{
public class ActivateTests
{
[Fact]
public void ActivateTests_Full()
{
var inst = new StashboxContainer().Register<Test>().Activate<Test1>();
Assert.NotNull(inst.Test);
Assert.NotNull(inst.Test2);
Assert.True(inst.InjectionMethodCalled);
}
[Fact]
public void ActivateTests_Full_DepOverride()
{
var test = new Test();
var inst = new StashboxContainer().Activate<Test1>(test);
Assert.Same(test, inst.Test);
Assert.Same(test, inst.Test2);
Assert.True(inst.InjectionMethodCalled);
}
[Fact]
public void ActivateTests_Fail()
{
Assert.Throws<ArgumentException>(() => new StashboxContainer().Activate<ITest>());
}
[Fact]
public void ActivateTests_Fail_On_Scope()
{
Assert.Throws<ArgumentException>(() => new StashboxContainer().BeginScope().Activate<ITest>());
}
interface ITest { }
class Test : ITest { }
class Test1
{
public bool InjectionMethodCalled { get; set; }
public Test Test { get; set; }
[Dependency]
public Test Test2 { get; set; }
public Test1(Test test)
{
this.Test = test;
}
[InjectionMethod]
public void InjectMethod()
{
this.InjectionMethodCalled = true;
}
}
}
}
| using Stashbox.Attributes;
using System;
using Xunit;
namespace Stashbox.Tests
{
public class ActivateTests
{
[Fact]
public void ActivateTests_Full()
{
var inst = new StashboxContainer().Register<Test>().Activate<Test1>();
Assert.NotNull(inst.Test);
Assert.NotNull(inst.Test2);
Assert.True(inst.InjectionMethodCalled);
}
[Fact]
public void ActivateTests_Full_DepOverride()
{
var test = new Test();
var inst = new StashboxContainer().Activate<Test1>(test);
Assert.Same(test, inst.Test);
Assert.Same(test, inst.Test2);
Assert.True(inst.InjectionMethodCalled);
}
[Fact]
public void ActivateTests_Fail()
{
Assert.Throws<ArgumentException>(() => new StashboxContainer().Activate<ITest>());
}
interface ITest { }
class Test : ITest { }
class Test1
{
public bool InjectionMethodCalled { get; set; }
public Test Test { get; set; }
[Dependency]
public Test Test2 { get; set; }
public Test1(Test test)
{
this.Test = test;
}
[InjectionMethod]
public void InjectMethod()
{
this.InjectionMethodCalled = true;
}
}
}
}
| mit | C# |
186faafdfd1c33ef4bf131476da8870e887cb00a | Add test of scheduler usage | peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework.Tests/Visual/Drawables/TestSceneSynchronizationContext.cs | osu.Framework.Tests/Visual/Drawables/TestSceneSynchronizationContext.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.Threading;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneSynchronizationContext : FrameworkTestScene
{
private AsyncPerformingBox box;
[Test]
public void TestAsyncPerformingBox()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox());
AddAssert("not spun", () => box.Rotation == 0);
AddStep("trigger", () => box.Trigger());
AddUntilStep("has spun", () => box.Rotation == 180);
}
[Test]
public void TestUsingLocalScheduler()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox());
AddAssert("scheduler null", () => box.Scheduler == null);
AddStep("trigger", () => box.Trigger());
AddUntilStep("scheduler non-null", () => box.Scheduler != null);
}
public class AsyncPerformingBox : Box
{
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public AsyncPerformingBox()
{
Size = new Vector2(100);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override async void LoadComplete()
{
base.LoadComplete();
await waiter.WaitAsync().ConfigureAwait(true);
this.RotateTo(180, 500);
}
public void Trigger()
{
waiter.Release();
}
}
}
}
| // 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.Threading;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneSynchronizationContext : FrameworkTestScene
{
private AsyncPerformingBox box;
[Test]
public void TestAsyncPerformingBox()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox());
AddAssert("not spun", () => box.Rotation == 0);
AddStep("trigger", () => box.Trigger());
AddUntilStep("has spun", () => box.Rotation == 180);
}
public class AsyncPerformingBox : Box
{
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public AsyncPerformingBox()
{
Size = new Vector2(100);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override async void LoadComplete()
{
base.LoadComplete();
await waiter.WaitAsync().ConfigureAwait(true);
this.RotateTo(180, 500);
}
public void Trigger()
{
waiter.Release();
}
}
}
}
| mit | C# |
f97fe72d4883d8ea99aede95066ae17f428256c5 | add label names | DasAllFolks/SharpGraphs | Graph/Graph.cs | Graph/Graph.cs | using System;
using System.Collections.Generic;
namespace Graph
{
public class Vertex
{
private bool hasLabel;
private string label;
public Vertex ()
{
this.hasLabel = false;
}
public Vertex (string label)
{
this.Label = label;
}
// XXXX: Remind self how to link to private field?
public bool HasLabel
{
get;
set;
}
public string Label
{
get
{
if (!this.hasLabel)
{
throw NoLabelFoundException("This vertex is unlabeled.");
}
return this.label;
}
set
{
this.label = value;
this.hasLabel = true;
}
}
public void ClearLabel ()
{
this.hasLabel = false;
}
public class NoLabelFoundException : Exception
{
}
}
public class Edge
{
// All Edge objects correspond to a directed (unidirectional) graph edge.
//
// An undirected edge should be represented using a pair of such (directed)
// Edges.
//
// Under this system, loops and multigraphs are also automatically supported.
//
// Edges are Immutable after creation.
private Vertex tail;
private Vertex head;
public Edge (Vertex tail, Vertex head)
{
this.tail = tail;
this.head = head;
}
public Vertex Tail
{
get;
}
public Vertex Head
{
get;
}
}
public class Graph
{
private HashSet<Graph.Vertex> vertices;
private HashSet<Graph.Edge> edges;
public Graph ()
{
}
// Use 0-based labeling by default for vertices added without an explicit label.
//
// If the auto-generated label is already in use, keep searching upward until we find the first integer
// not taken for this purpose.
public void AddVertex ()
{
}
public void AddVertex (int label)
{
this.vertices.Add (new Graph.Vertex((string) label));
}
public void AddVertex (string label)
{
}
// Add an edge using labels of existing vertices.
public void AddDirectedEdge(string tailLabel, string headLabel)
{
}
// Add an edge using two Vertex objects.
public void AddUndirectedEdge(string label1, string label2)
{
this.AddDirectedEdge (label1, label2);
this.AddDirectedEdge (label2, label1);
}
}
| using System;
using System.Collections.Generic;
namespace Graph
{
public class Vertex
{
private bool hasLabel;
private string label;
public Vertex ()
{
this.hasLabel = false;
}
public Vertex (string label)
{
this.Label = label;
}
// XXXX: Remind self how to link to private field?
public bool HasLabel
{
get;
set;
}
public string Label
{
get
{
if (!this.hasLabel)
{
throw NoLabelFoundException("This vertex is unlabeled.");
}
return this.label;
}
set
{
this.label = value;
this.hasLabel = true;
}
}
public void ClearLabel ()
{
this.hasLabel = false;
}
public class NoLabelFoundException : Exception
{
}
}
public class Edge
{
// All Edge objects correspond to a directed (unidirectional) graph edge.
//
// An undirected edge should be represented using a pair of such (directed)
// Edges.
//
// Under this system, loops and multigraphs are also automatically supported.
//
// Edges are Immutable after creation.
private Vertex tail;
private Vertex head;
public Edge (Vertex tail, Vertex head)
{
this.tail = tail;
this.head = head;
}
public Vertex Tail
{
get;
}
public Vertex Head
{
get;
}
}
public class Graph
{
private HashSet<Graph.Vertex> vertices;
private HashSet<Graph.Edge> edges;
public Graph ()
{
}
// Use 0-based labeling by default for vertices added without an explicit label.
//
// If the auto-generated label is already in use, keep searching upward until we find the first integer
// not taken for this purpose.
public void AddVertex ()
{
}
public void AddVertex (int label)
{
this.vertices.Add (new Graph.Vertex((string) label));
}
public void AddVertex (string label)
{
}
// Add an edge using labels of existing vertices.
public void AddDirectedEdge(string TailLabel, string HeadLabel)
{
}
// Add an edge using two Vertex objects.
public void AddUndirectedEdge(string label1, string label2)
{
this.AddDirectedEdge (label1, label2);
this.AddDirectedEdge (label2, label1);
}
}
| apache-2.0 | C# |
62f9e30d32fb78d5a7b7126c56d36a2cbc67fc81 | add few methods to compleate equation | pashchuk/Numerical-methods,pashchuk/Numerical-methods | CSharp/lab1/SquaresMethod.cs | CSharp/lab1/SquaresMethod.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using System.IO;
namespace lab1
{
public class SquaresMethod
{
#region Fields
private Matrix<double> _matrix;
private double[] _vector;
#endregion
#region Properties
#endregion
#region Costructors
public SquaresMethod(Matrix<double> matrix, double[] vector)
{
_matrix = matrix;
_vector = vector;
}
#endregion
#region private Methods
public Matrix<double> factorise()
{
var temp = new Matrix<double>(_matrix.Rows);
temp[0, 0] = Math.Sqrt(_matrix[0, 0]);
for (int i = 1; i < _matrix.Columns; i++)
temp[0, i] = temp[i,0] = _matrix[0, i]/temp[0, 0];
for (int i = 1; i < _matrix.Rows; i++)
{
double sum = 0;
for (int k = 0; k < i; k++)
sum += _matrix[k, i] * _matrix[k, i];
temp[i, i] = Math.Sqrt(_matrix[i, i] - sum);
}
for(int i = 1; i < _matrix.Rows; i++)
for (int j = i + 1; j < _matrix.Columns; j++)
{
double sum = 0;
for (int k = 0; k < i; k++)
sum += temp[k, i]*temp[k, j];
temp[i, j] = temp[j,i] = (_matrix[i, j] - sum)/temp[i, i];
}
return temp;
}
public Matrix<double> factorise2()
{
var temp = new Matrix<double>(_matrix.Rows);
for (int i = 0; i < _matrix.Rows; i++)
for (int j = 0; j <= i; j++)
{
double sum = 0;
for (int k = 0; k < j; k++)
sum += _matrix[i, k] * _matrix[j, k];
temp[i, j] = temp[j, i] = j == i ? Math.Sqrt(_matrix[i, j] - sum) : (_matrix[i, j] - sum) / temp[j, j];
}
return temp;
}
public double[] Check(Matrix<double> matrix, double[] vector)
{
var y = new double[vector.Length];
var x = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
{
double sum = 0;
for (int k = 0; k < i; k++)
sum += matrix[k, i]*y[k];
y[i] = (vector[i] - sum)/matrix[i, i];
}
for (int i = vector.Length-1; i > 0; i--)
{
double sum = 0;
for (int k = i; k < vector.Length; k++)
sum += matrix[i, k] * x[k];
y[i] = (y[i] - sum) / matrix[i, i];
}
return y;
}
#endregion
#region public Methods
public void Solve()
{
_matrix.Print(Console.Out);
Console.WriteLine();
var f1 = factorise2();
var f2 = factorise();
f1.Print(Console.Out);
Console.WriteLine();
f2.Print(Console.Out);
Console.WriteLine();
foreach (var a in Check(f1, _vector))
Console.WriteLine(a);
Console.WriteLine();
foreach (var a in Check(f2, _vector))
Console.WriteLine(a);
}
#endregion
#region Events
#endregion
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab1
{
public class SquaresMethod
{
#region Fields
private Matrix<double> _matrix;
#endregion
#region Properties
#endregion
#region Costructors
public SquaresMethod(Matrix<double> matrix)
{
_matrix = matrix;
}
#endregion
#region private Methods
#endregion
#region public Methods
public void Solve()
{
}
#endregion
#region Events
#endregion
}
}
| mit | C# |
00e50946e29fc21f99585c144f9864e6ad5af4ef | Add EnumerateArray() extension for tables | OpenRA/Eluant,cdhowie/Eluant,WFoundation/Eluant | Eluant/LuaValueExtensions.cs | Eluant/LuaValueExtensions.cs | using System;
using System.Collections.Generic;
namespace Eluant
{
public static class LuaValueExtensions
{
public static bool IsNil(this LuaValue self)
{
return self == null || self == LuaNil.Instance;
}
public static IEnumerable<LuaValue> EnumerateArray(this LuaTable self)
{
if (self == null) { throw new ArgumentNullException("self"); }
return CreateEnumerateArrayEnumerable(self);
}
private static IEnumerable<LuaValue> CreateEnumerateArrayEnumerable(LuaTable self)
{
// By convention, the 'n' field refers to the array length, if present.
using (var n = self["n"]) {
var num = n as LuaNumber;
if (num != null) {
var length = (int)num.Value;
for (int i = 1; i <= length; ++i) {
yield return self[i];
}
yield break;
}
}
// If no 'n' then stop at the first nil element.
for (int i = 1; ; ++i) {
var value = self[i];
if (value.IsNil()) {
yield break;
}
yield return value;
}
}
}
}
| using System;
namespace Eluant
{
public static class LuaValueExtensions
{
public static bool IsNil(this LuaValue self)
{
return self == null || self == LuaNil.Instance;
}
}
}
| mit | C# |
77db73b882443a5fa1d2fa7ab38e5e43796be297 | Add MathF.Tanh function. | eylvisaker/AgateLib | AgateLib/Mathematics/MathF.cs | AgateLib/Mathematics/MathF.cs | //
// Copyright (c) 2006-2018 Erik Ylvisaker
//
// 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 System.Text;
using System.Threading.Tasks;
namespace AgateLib.Mathematics
{
/// <summary>
/// Provides single precision math operations.
/// </summary>
public static class MathF
{
public const float PI = 3.14159265359f;
public const float TwoPI = 6.28318530718f;
/// <summary>
/// Single precision sine.
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static float Sin(float angle)
{
return (float)Math.Sin(angle);
}
/// <summary>
/// Hyperbolic Tangent function.
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static float Tanh(float x)
{
return (float)Math.Tanh((float)x);
}
/// <summary>
/// Single precision cosine.
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static float Cos(float angle)
{
return (float)Math.Cos(angle);
}
/// <summary>
/// Single precision square root.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static float Sqrt(float value)
{
return (float)Math.Sqrt(value);
}
/// <summary>
/// Floating precision exponential function.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static float Pow(float x, float y)
{
return (float)Math.Pow(x, y);
}
}
}
| //
// Copyright (c) 2006-2018 Erik Ylvisaker
//
// 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 System.Text;
using System.Threading.Tasks;
namespace AgateLib.Mathematics
{
/// <summary>
/// Provides single precision math operations.
/// </summary>
public static class MathF
{
public const float PI = 3.14159265359f;
public const float TwoPI = 6.28318530718f;
/// <summary>
/// Single precision sine.
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static float Sin(float angle)
{
return (float)Math.Sin(angle);
}
/// <summary>
/// Single precision cosine.
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static float Cos(float angle)
{
return (float)Math.Cos(angle);
}
/// <summary>
/// Single precision square root.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static float Sqrt(float value)
{
return (float)Math.Sqrt(value);
}
/// <summary>
/// Floating precision exponential function.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static float Pow(float x, float y)
{
return (float)Math.Pow(x, y);
}
}
}
| mit | C# |
a1cbff60ccd27ab3027179586bbee59d9e173f1d | Fix UWP VirtualAlloc import (dotnet/corert#6882) | BrennanConroy/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,ptoonen/corefx,shimingsg/corefx,ptoonen/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ericstj/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx | src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs | src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.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.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int MEM_RELEASE = 0x8000;
internal const int MEM_FREE = 0x10000;
internal const int PAGE_READWRITE = 0x04;
#if ENABLE_WINRT
[DllImport("api-ms-win-core-memory-l1-1-3.dll", EntryPoint = "VirtualAllocFromApp")]
internal static extern unsafe void* VirtualAlloc(void* BaseAddress, UIntPtr Size, int AllocationType, int Protection);
#else
[DllImport(Libraries.Kernel32)]
internal static extern unsafe void* VirtualAlloc(void* lpAddress, UIntPtr dwSize, int flAllocationType, int flProtect);
#endif
}
}
| // 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.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int MEM_RELEASE = 0x8000;
internal const int MEM_FREE = 0x10000;
internal const int PAGE_READWRITE = 0x04;
#if ENABLE_WINRT
[DllImport(Libraries.Kernel32, EntryPoint = "VirtualAllocFromApp")]
internal static extern unsafe void* VirtualAlloc(void* BaseAddress, UIntPtr Size, int AllocationType, int Protection);
#else
[DllImport(Libraries.Kernel32)]
internal static extern unsafe void* VirtualAlloc(void* lpAddress, UIntPtr dwSize, int flAllocationType, int flProtect);
#endif
}
}
| mit | C# |
a353eee1276641827781aa95be76f5e3149d96fb | Fix spin function to use local rotation | plrusek/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare | Assets/Resources/Microgames/_Bosses/PaperThief/Scripts/PaperThiefSpin.cs | Assets/Resources/Microgames/_Bosses/PaperThief/Scripts/PaperThiefSpin.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PaperThiefSpin : MonoBehaviour
{
[SerializeField]
private int rotateSpeed;
[SerializeField]
private bool _facingRight;
public bool facingRight
{
get {return _facingRight;}
set {_facingRight = value;}
}
void Start()
{
_facingRight = MathHelper.Approximately(getSpinRotation(), -180f, 1f);
}
void Update()
{
updateRotation();
}
void updateRotation()
{
float rotation = getSpinRotation();
//Spin between 0 and -180 degrees
float goalRotation = _facingRight ? -180f : 0f;
if (!MathHelper.Approximately(rotation, goalRotation, .0001f))
{
float diff = rotateSpeed * Time.deltaTime;
if (Mathf.Abs(goalRotation - rotation) <= diff)
setSpinRotation(goalRotation);
else
setSpinRotation(rotation + (diff * Mathf.Sign(goalRotation - rotation)));
}
}
float getSpinRotation()
{
Vector3 eulers = transform.localRotation.eulerAngles;
return eulers.y <= 0f ? eulers.y : eulers.y - 360f;
}
void setSpinRotation(float rotation)
{
Vector3 eulers = transform.localRotation.eulerAngles;
transform.localRotation = Quaternion.Euler(eulers.x, rotation, eulers.z);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PaperThiefSpin : MonoBehaviour
{
[SerializeField]
private int rotateSpeed;
[SerializeField]
private bool _facingRight;
public bool facingRight
{
get {return _facingRight;}
set {_facingRight = value;}
}
void Start()
{
_facingRight = MathHelper.Approximately(getSpinRotation(), -180f, 1f);
}
void Update()
{
updateRotation();
}
void updateRotation()
{
float rotation = getSpinRotation();
//Spin between 0 and -180 degrees
float goalRotation = _facingRight ? -180f : 0f;
if (!MathHelper.Approximately(rotation, goalRotation, .0001f))
{
float diff = rotateSpeed * Time.deltaTime;
if (Mathf.Abs(goalRotation - rotation) <= diff)
setSpinRotation(goalRotation);
else
setSpinRotation(rotation + (diff * Mathf.Sign(goalRotation - rotation)));
}
}
float getSpinRotation()
{
Vector3 eulers = transform.rotation.eulerAngles;
return eulers.y <= 0f ? eulers.y : eulers.y - 360f;
}
void setSpinRotation(float rotation)
{
Vector3 eulers = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(eulers.x, rotation, eulers.z);
}
}
| mit | C# |
81d7ca37a0952d0b334e15a503f7c518d7c0cdd2 | Fix formatting | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Shared/DisplayTemplates/VehicleStatus.cshtml | Battery-Commander.Web/Views/Shared/DisplayTemplates/VehicleStatus.cshtml | @model Vehicle
@switch (Model.Status)
{
case Vehicle.VehicleStatus.FMC:
<span class="label label-success">FMC</span>
return;
case Vehicle.VehicleStatus.NMC:
<span class="label label-danger">NMC</span>
return;
case Vehicle.VehicleStatus.Unknown:
<span class="label label-warning">Unknown</span>
return;
} | @model Vehicle
@switch(Model.Status)
{
case Vehicle.VehicleStatus.FMC:
<span class="label label-success">FMC</span>
return;
case Vehicle.VehicleStatus.NMC:
<span class="label label-danger">NMC</span>
return;
case Vehicle.VehicleStatus.Unknown:
<span class="label label-warning">Unknown</span>
return;
} | mit | C# |
1d799ff1f86396eb59154a17f3fe2353aa09d791 | Fix NullException ocurring in GetFeaturesInView() when BoundingBox is null | charlenni/Mapsui,charlenni/Mapsui,tebben/Mapsui,pauldendulk/Mapsui | Mapsui/Layers/MemoryLayer.cs | Mapsui/Layers/MemoryLayer.cs | using Mapsui.Fetcher;
using Mapsui.Geometries;
using Mapsui.Providers;
using System.Collections.Generic;
using System.Threading.Tasks;
using Mapsui.Styles;
namespace Mapsui.Layers
{
public class MemoryLayer : BaseLayer
{
public IProvider DataSource { get; set; }
public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution)
{
// Safeguard in case BoundingBox is null, most likely due to no features in layer
if (box == null) { return new List<IFeature>(); }
var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution);
return DataSource.GetFeaturesInView(biggerBox, resolution);
}
public override BoundingBox Envelope => DataSource?.GetExtents();
public override void AbortFetch()
{
// do nothing. This is not an async layer
}
public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution)
{
//The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it.
Task.Run(() => OnDataChanged(new DataChangedEventArgs()));
}
public override void ClearCache()
{
// do nothing. This is not an async layer
}
}
}
| using Mapsui.Fetcher;
using Mapsui.Geometries;
using Mapsui.Providers;
using System.Collections.Generic;
using System.Threading.Tasks;
using Mapsui.Styles;
namespace Mapsui.Layers
{
public class MemoryLayer : BaseLayer
{
public IProvider DataSource { get; set; }
public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution)
{
var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution);
return DataSource.GetFeaturesInView(biggerBox, resolution);
}
public override BoundingBox Envelope => DataSource?.GetExtents();
public override void AbortFetch()
{
// do nothing. This is not an async layer
}
public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution)
{
//The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it.
Task.Run(() => OnDataChanged(new DataChangedEventArgs()));
}
public override void ClearCache()
{
// do nothing. This is not an async layer
}
}
}
| mit | C# |
59df9468c0c3ac4cc333b2f1e9f5aa33b2548da9 | Allow cactbot to be restarted | quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot | ACTPlugin.cs | ACTPlugin.cs | using Advanced_Combat_Tracker;
using CefSharp;
using CefSharp.Wpf;
using System;
using System.Windows.Forms;
namespace Cactbot
{
public class ACTPlugin : IActPluginV1
{
SettingsTab settingsTab = new SettingsTab();
BrowserWindow browserWindow;
#region IActPluginV1 Members
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
{
settingsTab.Initialize(pluginStatusText);
browserWindow = new BrowserWindow();
browserWindow.ShowInTaskbar = false;
browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated;
browserWindow.Show();
pluginScreenSpace.Controls.Add(settingsTab);
Application.ApplicationExit += OnACTShutdown;
}
public void DeInitPlugin()
{
browserWindow.Hide();
settingsTab.Shutdown();
}
#endregion
private void OnBrowserCreated(object sender, IWpfWebBrowser browser)
{
browser.RegisterJsObject("act", new BrowserBindings());
// FIXME: Make it possible to create more than one window.
// Tie loading html to the browser window creation and bindings to the
// browser creation.
browser.Load(settingsTab.HTMLFile());
browser.ShowDevTools();
}
private void OnACTShutdown(object sender, EventArgs args)
{
// Cef has to be manually shutdown on this thread, but can only be
// shutdown once.
Cef.Shutdown();
}
}
}
| using Advanced_Combat_Tracker;
using CefSharp;
using CefSharp.Wpf;
using System;
using System.Windows.Forms;
namespace Cactbot
{
public class ACTPlugin : IActPluginV1
{
SettingsTab settingsTab = new SettingsTab();
BrowserWindow browserWindow;
#region IActPluginV1 Members
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
{
settingsTab.Initialize(pluginStatusText);
browserWindow = new BrowserWindow();
browserWindow.ShowInTaskbar = false;
browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated;
browserWindow.Show();
pluginScreenSpace.Controls.Add(settingsTab);
}
public void DeInitPlugin()
{
browserWindow.Hide();
settingsTab.Shutdown();
// FIXME: This needs to be called from the right thread, so it can't happen automatically.
// However, calling it here means the plugin can never be reinitialized, oops.
Cef.Shutdown();
}
#endregion
private void OnBrowserCreated(object sender, IWpfWebBrowser browser)
{
browser.RegisterJsObject("act", new BrowserBindings());
// FIXME: Make it possible to create more than one window.
// Tie loading html to the browser window creation and bindings to the
// browser creation.
browser.Load(settingsTab.HTMLFile());
browser.ShowDevTools();
}
}
}
| apache-2.0 | C# |
e2bcc4e035aaa2e0c9495d3deed5704bc4e0e72f | Update Box.cs | dimmpixeye/Unity3dTools | Runtime/LibProcessors/Box.cs | Runtime/LibProcessors/Box.cs | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Pixeye.Framework
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public class Box : IKernel, IDisposable
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public static Box Default = new Box();
public static readonly string path = "/{0}";
internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default);
Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default);
public static int StringToHash(string val)
{
var hash = val.GetHashCode();
Default.itemsPaths.Add(hash, val);
return hash;
}
public static T Load<T>(string id) where T : Object
{
return Resources.Load<T>(id);
}
public static T[] LoadAll<T>(string id) where T : Object
{
return Resources.LoadAll<T>(id);
}
public static T[] LoadAll<T>(string id, int amount) where T : UnityEngine.Object
{
var storage = new T[amount];
for (int i = 0; i < amount; i++)
{
storage[i] = Resources.Load<T>($"{id} {i}");
}
return storage;
}
public static T Get<T>(string id) where T : Object
{
Object obj;
var key = id.GetHashCode();
var hasValue = Default.items.TryGetValue(key, out obj);
if (hasValue == false)
{
obj = Resources.Load<T>(id);
Default.items.Add(key, obj);
}
return obj as T;
}
public static T Get<T>(int id) where T : Object
{
Object obj;
if (Default.items.TryGetValue(id, out obj))
return obj as T;
obj = Resources.Load(Default.itemsPaths[id]);
Default.items.Add(id, obj);
return obj as T;
}
public void Dispose()
{
items.Clear();
itemsPaths.Clear();
}
}
} | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Pixeye.Framework
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public class Box : IKernel, IDisposable
{
/// <summary>
/// <para>Caches / return assets that Developer takes from the Resources folder.
/// Box cleans cache when scene reloads.</para>
/// </summary>
public static Box Default = new Box();
public static readonly string path = "/{0}";
internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default);
Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default);
public static int StringToHash(string val)
{
var hash = val.GetHashCode();
Default.itemsPaths.Add(hash, val);
return hash;
}
public static T Load<T>(string id) where T : Object
{
return Resources.Load<T>(id);
}
public static T[] LoadAll<T>(string id) where T : Object
{
return Resources.LoadAll<T>(id);
}
public static T[] LoadAll<T>(string id, int amount) where T : UnityEngine.Object
{
var storage = new T[amount];
for (int i = 0; i < amount; i++)
storage[i] = Resources.Load<T>($"{id} {amount}");
return storage;
}
public static T Get<T>(string id) where T : Object
{
Object obj;
var key = id.GetHashCode();
var hasValue = Default.items.TryGetValue(key, out obj);
if (hasValue == false)
{
obj = Resources.Load<T>(id);
Default.items.Add(key, obj);
}
return obj as T;
}
public static T Get<T>(int id) where T : Object
{
Object obj;
if (Default.items.TryGetValue(id, out obj))
return obj as T;
obj = Resources.Load(Default.itemsPaths[id]);
Default.items.Add(id, obj);
return obj as T;
}
public void Dispose()
{
items.Clear();
itemsPaths.Clear();
}
}
} | mit | C# |
c6dd75f67794b631e7f1cee9ef5c2824223c33cb | Move currentPipeline to be a local variable | WimObiwan/Pash,sburnicki/Pash,sillvan/Pash,JayBazuzi/Pash,sillvan/Pash,sburnicki/Pash,sburnicki/Pash,Jaykul/Pash,JayBazuzi/Pash,ForNeVeR/Pash,ForNeVeR/Pash,Jaykul/Pash,JayBazuzi/Pash,Jaykul/Pash,mrward/Pash,mrward/Pash,JayBazuzi/Pash,mrward/Pash,ForNeVeR/Pash,sburnicki/Pash,WimObiwan/Pash,sillvan/Pash,WimObiwan/Pash,sillvan/Pash,Jaykul/Pash,mrward/Pash,ForNeVeR/Pash,WimObiwan/Pash | Source/PashGui/MainWindow.cs | Source/PashGui/MainWindow.cs | using System;
using Gtk;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Host;
using PashGui;
public partial class MainWindow: Gtk.Window
{
readonly private Runspace runspace;
readonly private Host host;
public MainWindow(): base (Gtk.WindowType.Toplevel)
{
Build();
this.consoleview1.ConsoleInput += this.OnConsoleview1ConsoleInput;
this.host = new Host(this.consoleview1);
this.runspace = RunspaceFactory.CreateRunspace(this.host);
this.runspace.Open();
ExecutePrompt();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
void ExecuteCommand(string command)
{
Pipeline currentPipeline;
using (currentPipeline = this.runspace.CreatePipeline())
{
currentPipeline.Commands.Add(command);
// Now add the default outputter to the end of the pipe and indicate
// that it should handle both output and errors from the previous
// commands. This will result in the output being written using the PSHost
// and PSHostUserInterface classes instead of returning objects to the hosting
// application.
currentPipeline.Commands.Add("out-default");
currentPipeline.Commands [0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
currentPipeline.Invoke();
}
}
void ExecutePrompt()
{
this.consoleview1.PromptString = "PASH> ";
this.consoleview1.Prompt(false);
}
protected void OnConsoleview1ConsoleInput(object sender, MonoDevelop.Components.ConsoleInputEventArgs e)
{
string command = e.Text;
ExecuteCommand(command);
ExecutePrompt();
}
}
| using System;
using Gtk;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Host;
using PashGui;
public partial class MainWindow: Gtk.Window
{
readonly private Runspace runspace;
readonly private Host host;
private Pipeline currentPipeline;
public MainWindow(): base (Gtk.WindowType.Toplevel)
{
Build();
this.consoleview1.ConsoleInput += this.OnConsoleview1ConsoleInput;
this.host = new Host(this.consoleview1);
this.runspace = RunspaceFactory.CreateRunspace(this.host);
this.runspace.Open();
ExecutePrompt();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
void ExecuteCommand(string command)
{
using (currentPipeline = this.runspace.CreatePipeline())
{
currentPipeline.Commands.Add(command);
// Now add the default outputter to the end of the pipe and indicate
// that it should handle both output and errors from the previous
// commands. This will result in the output being written using the PSHost
// and PSHostUserInterface classes instead of returning objects to the hosting
// application.
currentPipeline.Commands.Add("out-default");
currentPipeline.Commands [0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
currentPipeline.Invoke();
}
}
void ExecutePrompt()
{
this.consoleview1.PromptString = "PASH> ";
this.consoleview1.Prompt(false);
}
protected void OnConsoleview1ConsoleInput(object sender, MonoDevelop.Components.ConsoleInputEventArgs e)
{
string command = e.Text;
ExecuteCommand(command);
ExecutePrompt();
}
}
| bsd-3-clause | C# |
77c530fa93fc3ce3865d2b9ee782f4eb81efda2b | fix connections string | jona8690/Project-Getting-Real | Code/Core/Database.cs | Code/Core/Database.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Core
{
public class Database
{
private const string ConnInfo = "Server=ealdb1.eal.local; Database=ejl86_db; User Id=ejl86_usr; Password=Baz1nga86";
private SqlConnection Conn;
//Database()
//{
// Conn = new SqlConnection(ConnInfo);
//}
public void RunSP(string name, Dictionary<string,string> param)
{
using (Conn = new SqlConnection(ConnInfo))
{
SqlCommand cmd = new SqlCommand(name, this.Conn);
cmd.CommandType = CommandType.StoredProcedure;
foreach(KeyValuePair<string,string> entry in param)
{
cmd.Parameters.Add(new SqlParameter(entry.Key, entry.Value));
}
try
{
Conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
Conn.Close();
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Core
{
public class Database
{
private const string ConnInfo = "Server=ealdb1.eal.local; Database=ejl86_usr; Password=Baz1nga86";
private SqlConnection Conn;
//Database()
//{
// Conn = new SqlConnection(ConnInfo);
//}
public void RunSP(string name, Dictionary<string,string> param)
{
using (Conn = new SqlConnection(ConnInfo))
{
SqlCommand cmd = new SqlCommand(name, this.Conn);
cmd.CommandType = CommandType.StoredProcedure;
foreach(KeyValuePair<string,string> entry in param)
{
cmd.Parameters.Add(new SqlParameter(entry.Key, entry.Value));
}
try
{
Conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
Conn.Close();
}
}
}
}
}
| mit | C# |
6b5aa7787bf44ca77b82cf353e8c6cdd0171bc29 | change how MainWindow sets screens | svmnotn/cuddly-octo-adventure | Game/UI/MainWindow.cs | Game/UI/MainWindow.cs | namespace COA.Game.UI {
using System;
using System.Windows.Forms;
using Controls;
using Data;
internal partial class MainWindow : Form {
UserControl current;
internal UserControl Current {
get { return current; }
set {
if(current != null) {
current.Visible = false;
}
if(!Controls.Contains(value)) {
Controls.Add(value);
}
current = value;
current.Dock = DockStyle.Fill;
current.Visible = true;
}
}
internal readonly Archive archive;
internal GameMode gm;
internal int currTeam;
internal Action timerFire;
internal int timerCount;
internal MainWindow() : this(Archive.Default) { }
internal MainWindow(Archive a) {
InitializeComponent();
archive = a;
Text = a.name;
BackColor = archive.settings.backgroundColor;
if(!string.IsNullOrWhiteSpace(archive.settings.backgroundLoc)) {
BackgroundImage = archive.settings.background ?? Extensions.LoadImage(Program.ArchivePath(archive), archive.settings.backgroundLoc);
}
Current = new ModeSelect();
}
private void OnTick(object sender, EventArgs e) {
if(timerFire != null) {
timerFire();
}
}
private void OnClose(object sender, FormClosedEventArgs e) {
Application.Exit();
}
}
} | namespace COA.Game.UI {
using System;
using System.Windows.Forms;
using Controls;
using Data;
internal partial class MainWindow : Form {
UserControl current;
internal UserControl Current {
get { return current; }
set {
if(!Controls.Contains(value)) {
Controls.Add(value);
}
if(current != null) {
current.Visible = false;
}
current = value;
if(!string.IsNullOrWhiteSpace(archive.settings.backgroundLoc)) {
current.BackgroundImage = archive.settings.background ?? Extensions.LoadImage(Program.ArchivePath(archive), archive.settings.backgroundLoc);
}
current.BackColor = archive.settings.backgroundColor;
current.Visible = true;
}
}
internal readonly Archive archive;
internal GameMode gm;
internal readonly Team[] teams;
internal int currTeam;
internal Action timerFire;
internal int timerCount;
internal MainWindow() : this(Archive.Default) { }
internal MainWindow(Archive a) {
InitializeComponent();
archive = a;
teams = archive.settings.teams.ToArray();
Text = a.name;
var mode = new ModeSelect();
mode.Dock = DockStyle.Fill;
Current = mode;
}
private void OnTick(object sender, EventArgs e) {
if(timerFire != null) {
timerFire();
}
}
private void OnClose(object sender, FormClosedEventArgs e) {
Application.Exit();
}
}
} | mit | C# |
6e821a426d4bcc234788a7703110ed9fc7ad5185 | Fix restoration of enabled mods when cancelling song select | johnneijzen/osu,peppy/osu,johnneijzen/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,naoey/osu,ppy/osu,DrabWeb/osu,ppy/osu,peppy/osu,smoogipoo/osu,ZLima12/osu,smoogipooo/osu,naoey/osu,2yangk23/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu | osu.Game/Screens/Select/MatchSongSelect.cs | osu.Game/Screens/Select/MatchSongSelect.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 System.Collections.Generic;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerSubScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
public override string Title => ShortTitle.Humanize();
[Resolved(typeof(Room))]
protected Bindable<PlaylistItem> CurrentItem { get; private set; }
[Resolved]
protected Bindable<IEnumerable<Mod>> CurrentMods { get; private set; }
[Resolved]
private BeatmapManager beatmaps { get; set; }
public MatchSongSelect()
{
Padding = new MarginPadding { Horizontal = HORIZONTAL_OVERFLOW_PADDING };
}
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
RulesetID = Ruleset.Value.ID ?? 0
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (this.IsCurrentScreen())
this.Exit();
return true;
}
public override bool OnExiting(IScreen next)
{
if (base.OnExiting(next))
return true;
Beatmap.Value = beatmaps.GetWorkingBeatmap(CurrentItem.Value?.Beatmap);
Beatmap.Value.Mods.Value = CurrentMods.Value = CurrentItem.Value?.RequiredMods;
Ruleset.Value = CurrentItem.Value?.Ruleset;
Beatmap.Disabled = true;
Ruleset.Disabled = true;
return false;
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
Beatmap.Disabled = false;
Ruleset.Disabled = false;
}
}
}
| // 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 Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi;
namespace osu.Game.Screens.Select
{
public class MatchSongSelect : SongSelect, IMultiplayerSubScreen
{
public Action<PlaylistItem> Selected;
public string ShortTitle => "song selection";
public override string Title => ShortTitle.Humanize();
[Resolved(typeof(Room))]
protected Bindable<PlaylistItem> CurrentItem { get; private set; }
[Resolved]
private BeatmapManager beatmaps { get; set; }
public MatchSongSelect()
{
Padding = new MarginPadding { Horizontal = HORIZONTAL_OVERFLOW_PADDING };
}
protected override bool OnStart()
{
var item = new PlaylistItem
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = Ruleset.Value,
RulesetID = Ruleset.Value.ID ?? 0
};
item.RequiredMods.AddRange(SelectedMods.Value);
Selected?.Invoke(item);
if (this.IsCurrentScreen())
this.Exit();
return true;
}
public override bool OnExiting(IScreen next)
{
if (base.OnExiting(next))
return true;
Beatmap.Value = beatmaps.GetWorkingBeatmap(CurrentItem.Value?.Beatmap);
Ruleset.Value = CurrentItem.Value?.Ruleset;
CurrentItem.Value?.RequiredMods.Clear();
CurrentItem.Value?.RequiredMods.AddRange(SelectedMods.Value);
Beatmap.Disabled = true;
Ruleset.Disabled = true;
return false;
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
Beatmap.Disabled = false;
Ruleset.Disabled = false;
}
}
}
| mit | C# |
c020bed936eb6286e05f5de5f2e7021e7a9c9c55 | 修正 Ivony.Web 项目版本号。 | yonglehou/Jumony,zpzgone/Jumony,wukaixian/Jumony,yonglehou/Jumony,wukaixian/Jumony,zpzgone/Jumony | Ivony.Web/Properties/AssemblyInfo.cs | Ivony.Web/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Ivony.Web")]
[assembly: AssemblyDescription( "a web utils" )]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct("Ivony.Web")]
[assembly: AssemblyCopyright( "Copyright © 2013 by Ivony" )]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("69f0dea2-f48b-4ffe-b3cd-8b826c5f8aec")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.1.*" )]
[assembly: AssemblyFileVersion( "1.1" )]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Ivony.Web")]
[assembly: AssemblyDescription( "a web utils" )]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct("Ivony.Web")]
[assembly: AssemblyCopyright( "Copyright © 2013 by Ivony" )]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("69f0dea2-f48b-4ffe-b3cd-8b826c5f8aec")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
95f0ce95ea705859127eb1e78fc72e8d8212e006 | Update 1.0.0.1 | NoShurim/Buddys | Kayn/Kayn/Properties/AssemblyInfo.cs | Kayn/Kayn/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kayn")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Kayn")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e88aec8e-30ef-4857-a35c-452730185351")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
| using System.Reflection;
using System.Runtime.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("Kayn")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Kayn")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e88aec8e-30ef-4857-a35c-452730185351")]
// 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")]
| epl-1.0 | C# |
3bef48352c076e6871b159a9208765154d5dcbf9 | Update NClock.cs | demigor/nreact | NReact.Demo.Wpf/Components/NClock.cs | NReact.Demo.Wpf/Components/NClock.cs | using System;
using System.Threading;
namespace NReact
{
public partial class NClock : NComponent
{
Timer _timer;
public override object GetDefaultProps()
{
return new { FS = 36.0 };
}
protected override object GetInitialState()
{
return new { Time = DateTime.Now, Tick = 0 };
}
public override void ComponentDidMount()
{
_timer = new Timer(UpdateTime, null, 0, NDemo.RefreshDelay);
}
public override void ComponentWillUnmount()
{
_timer.Dispose();
}
void UpdateTime(object sender = null)
{
SetState(new { Time = DateTime.Now, Tick = State.Tick + 1 });
}
}
}
| using System;
using System.Threading;
namespace NReact
{
public partial class NClock : NComponent
{
Timer _timer;
public override object GetDefaultProps()
{
return new { FS = 36D }.AsDynamic();
}
protected override object GetInitialState()
{
return new { Time = DateTime.Now, Tick = 0 }.AsDynamic();
}
public override void ComponentDidMount()
{
_timer = new Timer(UpdateTime, null, 0, NDemo.RefreshDelay);
}
public override void ComponentWillUnmount()
{
_timer.Dispose();
}
void UpdateTime(object sender = null)
{
SetState(new { Time = DateTime.Now, Tick = State.Tick + 1 });
}
}
}
| mit | C# |
45d57920447db49d2f7d0e8838046d656434ce9e | Update version to 4.3.0 | TheOtherTimDuncan/TOTD | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
// 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("4.3.0.0")]
[assembly: AssemblyFileVersion("4.3.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
// 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("4.2.0.0")]
[assembly: AssemblyFileVersion("4.2.0.0")]
| mit | C# |
047c4452fd9d03837ba86830eda1ad17d426a5d2 | Update ProductMap.cs | henkmollema/Dapper-FluentMap,henkmollema/Dapper-FluentMap,thomasbargetz/Dapper-FluentMap,bondarenkod/Dapper-FluentMap,arumata/Dapper-FluentMap | examples/ProductMap.cs | examples/ProductMap.cs | using Dapper.FluentMap.Mapping;
namespace App.Data.Mapping
{
/// <summary>
/// Represents a manual mapping for the Product entity.
/// </summary>
public class ProductMap : EntityMap<Product>
{
public ProductMap()
{
// Map property 'Name' to column 'strName'.
Map(p => p.Name)
.ToColumn("strName");
// Map property 'Description' to 'strdescription', ignoring casing.
Map(p => p.Description)
.ToColumn("strdescription", caseSensitive: false);
// Ignore the 'LastModified' property when mapping.
Map(p => p.LastModified)
.Ignore();
}
}
}
| using Dapper.FluentMap.Mapping;
namespace App.Data.Mapping
{
/// <summary>
/// Represents a manual mapping for the Product entity.
/// </summary>
public class ProductMap : EntityMap<Product>
{
public ProductMap()
{
// Map property 'Name' to column 'strName'.
Map(p => p.Name)
.ToColumn("strName");
// Map property 'Description' to 'strdescription', ignoring casing.
Map(p => p.Description)
.ToColumn("strdescription", caseSensitive: false);
// Ignore the 'LastModified' property when mapping.
Map(p => p.LastModified)
.Ignore();
}
}
}
| mit | C# |
52fd325daaf6c44abbe17ca887be477d259a7700 | Update Coin.cs | erdenbatuhan/Venture | Assets/Scripts/Coin.cs | Assets/Scripts/Coin.cs | //
// Coin.cs
// Venture
//
// Created by Batuhan Erden.
// Copyright © 2016 Batuhan Erden. All rights reserved.
//
using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour {
public GameObject coinEffect;
private void OnTriggerEnter() {
GetComponent<MeshRenderer>().enabled = false;
GetComponent<BoxCollider>().enabled = false;
GameMaster.addCoin();
animate();
}
private void animate() {
GameObject effect = Instantiate(coinEffect);
effect.transform.position = transform.position;
GetComponent<AudioSource>().Play();
destroyChildren();
Destroy(effect, 3);
Destroy(gameObject, 3);
}
private void destroyChildren() {
foreach (Transform child in transform)
Destroy(child.gameObject);
}
}
| //
// Coin.cs
// A Vaila Ball - Computer
//
// Created by Batuhan Erden.
// Copyright © 2016 Batuhan Erden. All rights reserved.
//
using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour {
public GameObject coinEffect;
private void OnTriggerEnter() {
GetComponent<MeshRenderer>().enabled = false;
GetComponent<BoxCollider>().enabled = false;
GameMaster.addCoin();
animate();
}
private void animate() {
GameObject effect = Instantiate(coinEffect);
effect.transform.position = transform.position;
GetComponent<AudioSource>().Play();
destroyChildren();
Destroy(effect, 3);
Destroy(gameObject, 3);
}
private void destroyChildren() {
foreach (Transform child in transform)
Destroy(child.gameObject);
}
} | mit | C# |
0dee6ceab74a3826c2705d55e50921f58d38dc52 | Remove unnecessary using | EVAST9919/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.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 System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.DifficultyReduction;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.AutoSpin = true;
}
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.DifficultyReduction;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.AutoSpin = true;
}
}
}
}
}
| mit | C# |
da794063fb4003d7f7f365dd4165ef82bc7ed079 | Remove IUpload constructor from UploadPartRequest | carbon/Amazon | src/Amazon.S3/Actions/UploadPartRequest.cs | src/Amazon.S3/Actions/UploadPartRequest.cs | using System;
namespace Amazon.S3
{
// PUT /ObjectName?partNumber=PartNumber&uploadId=UploadId
public sealed class UploadPartRequest : PutObjectRequest
{
public UploadPartRequest(string host, string bucketName, string key, string uploadId, int partNumber)
: base(host, bucketName, key + $"?partNumber={partNumber}&uploadId={uploadId}")
{
if (partNumber < 1 || partNumber > 10_000)
throw new ArgumentOutOfRangeException(nameof(partNumber), partNumber, "Must be between 1 and 10,000");
UploadId = uploadId ?? throw new ArgumentNullException(nameof(uploadId));
PartNumber = partNumber;
}
public string UploadId { get; }
public int PartNumber { get; }
}
}
/*
Part numbers: 1 to 10,000 (inclusive)
Part size: 5 MB to 5 GB, last part can be < 5 MB
*/
| using System;
using Carbon.Storage;
namespace Amazon.S3
{
// PUT /ObjectName?partNumber=PartNumber&uploadId=UploadId
public sealed class UploadPartRequest : PutObjectRequest
{
public UploadPartRequest(string host, IUpload upload, int partNumber)
: this(host, upload.BucketName, upload.ObjectName, upload.UploadId, partNumber) { }
public UploadPartRequest(string host, string bucketName, string key, string uploadId, int partNumber)
: base(host, bucketName, key + $"?partNumber={partNumber}&uploadId={uploadId}")
{
if (partNumber < 1 || partNumber > 10_000)
throw new ArgumentOutOfRangeException(nameof(partNumber), partNumber, "Must be between 1 and 10,000");
UploadId = uploadId ?? throw new ArgumentNullException(nameof(uploadId));
PartNumber = partNumber;
}
public string UploadId { get; }
public int PartNumber { get; }
}
}
/*
Part numbers: 1 to 10,000 (inclusive)
Part size: 5 MB to 5 GB, last part can be < 5 MB
*/
| mit | C# |
d25849c3859765d7caf99dc48cfdcdcd7758f5e6 | Use new API to build durable Exchange | lsfera/Carrot,naighes/Carrot | src/Carrot/Messages/ConsumedMessageBase.cs | src/Carrot/Messages/ConsumedMessageBase.cs | using System;
using System.Threading.Tasks;
using Carrot.Configuration;
using Carrot.Extensions;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace Carrot.Messages
{
public abstract class ConsumedMessageBase
{
protected readonly BasicDeliverEventArgs Args;
protected ConsumedMessageBase(BasicDeliverEventArgs args)
{
Args = args;
}
internal abstract Object Content { get; }
internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration);
internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class
{
var content = Content as TMessage;
if (content == null)
throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'",
Content.GetType(),
typeof(TMessage)));
return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args));
}
internal abstract Boolean Match(Type type);
internal void Acknowledge(IModel model)
{
model.BasicAck(Args.DeliveryTag, false);
}
internal void Requeue(IModel model)
{
model.BasicNack(Args.DeliveryTag, false, true);
}
internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder)
{
var exchange = Exchange.Direct(exchangeNameBuilder(Args.Exchange)).Durable();
exchange.Declare(model);
var properties = Args.BasicProperties.Copy();
properties.Persistent = true;
model.BasicPublish(exchange.Name,
String.Empty,
properties,
Args.Body);
}
}
} | using System;
using System.Threading.Tasks;
using Carrot.Configuration;
using Carrot.Extensions;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace Carrot.Messages
{
public abstract class ConsumedMessageBase
{
protected readonly BasicDeliverEventArgs Args;
protected ConsumedMessageBase(BasicDeliverEventArgs args)
{
Args = args;
}
internal abstract Object Content { get; }
internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration);
internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class
{
var content = Content as TMessage;
if (content == null)
throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'",
Content.GetType(),
typeof(TMessage)));
return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args));
}
internal abstract Boolean Match(Type type);
internal void Acknowledge(IModel model)
{
model.BasicAck(Args.DeliveryTag, false);
}
internal void Requeue(IModel model)
{
model.BasicNack(Args.DeliveryTag, false, true);
}
internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder)
{
var exchange = Exchange.DurableDirect(exchangeNameBuilder(Args.Exchange));
exchange.Declare(model);
var properties = Args.BasicProperties.Copy();
properties.Persistent = true;
model.BasicPublish(exchange.Name,
String.Empty,
properties,
Args.Body);
}
}
} | mit | C# |
9e4b4338dbad4e14d994247259386833a52263c4 | add http error codes to error actions | codeimpossible/proggr,codeimpossible/proggr | src/Proggr/Controllers/ErrorsController.cs | src/Proggr/Controllers/ErrorsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Proggr.Controllers
{
public class ErrorsController : ControllerBase
{
public ActionResult Index()
{
Response.StatusCode = 412;
return View();
}
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
public ActionResult MustBeLoggedIn()
{
Response.StatusCode = 401;
return View();
}
public ActionResult AuthError()
{
Response.StatusCode = 401;
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Proggr.Controllers
{
public class ErrorsController : ControllerBase
{
public ActionResult Index()
{
return View();
}
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
public ActionResult MustBeLoggedIn()
{
return View();
}
public ActionResult AuthError()
{
return View();
}
}
}
| bsd-3-clause | C# |
e8588ea1a6088fb9e53d03ce8382d7aa62e6100d | Test break fix | ErikEJ/EntityFramework7.SqlServerCompact,ErikEJ/EntityFramework.SqlServerCompact | src/SqlCeDataStoreSource.cs | src/SqlCeDataStoreSource.cs | using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Storage;
namespace ErikEJ.Data.Entity.SqlServerCe
{
public class SqlCeDataStoreSource : DataStoreSource<SqlCeDataStoreServices, SqlCeOptionsExtension>
{
public override void AutoConfigure(DbContextOptionsBuilder optionsBuilder)
{
}
public override string Name => "SqlCeDataStore";
}
} | using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Storage;
namespace ErikEJ.Data.Entity.SqlServerCe
{
public class SqlCeDataStoreSource : DataStoreSource<SqlCeDataStoreServices, SqlCeOptionsExtension>
{
public override void AutoConfigure(DbContextOptionsBuilder optionsBuilder)
{
}
public override string Name => "SqlServerCeDataStore";
}
} | apache-2.0 | C# |
068996678bda9c7b2611f3379808091d519f96a5 | Add mLogger to Unity Window menu | bartlomiejwolk/FileLogger | Editor/LoggerWindow.cs | Editor/LoggerWindow.cs | using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
namespace mLogger {
public class LoggerWindow : EditorWindow {
private Logger loggerInstance;
public Logger LoggerInstance {
get {
if (loggerInstance == null) {
loggerInstance = FindObjectOfType<Logger>();
if (loggerInstance == null) {
GameObject loggerGO = new GameObject();
loggerGO.AddComponent<Logger>();
loggerInstance = loggerGO.GetComponent<Logger>();
}
}
return loggerInstance;
}
}
[MenuItem("Window/mLogger")]
public static void Init() {
LoggerWindow window =
(LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow));
window.title = "Logger";
window.minSize = new Vector2(100f, 60f);
}
private void OnGUI() {
EditorGUILayout.BeginHorizontal();
// Draw Start/Stop button.
LoggerInstance.LoggingEnabled =
InspectorControls.DrawStartStopButton(
LoggerInstance.LoggingEnabled,
LoggerInstance.EnableOnPlay,
null,
() => LoggerInstance.LogWriter.Add("[PAUSE]", true),
() => LoggerInstance.LogWriter.WriteAll(
LoggerInstance.FilePath,
false));
// Draw -> button.
if (GUILayout.Button("->", GUILayout.Width(30))) {
EditorGUIUtility.PingObject(LoggerInstance);
Selection.activeGameObject = LoggerInstance.gameObject;
}
EditorGUILayout.EndHorizontal();
Repaint();
}
}
}
| using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
namespace mLogger {
public class LoggerWindow : EditorWindow {
private Logger loggerInstance;
public Logger LoggerInstance {
get {
if (loggerInstance == null) {
loggerInstance = FindObjectOfType<Logger>();
if (loggerInstance == null) {
GameObject loggerGO = new GameObject();
loggerGO.AddComponent<Logger>();
loggerInstance = loggerGO.GetComponent<Logger>();
}
}
return loggerInstance;
}
}
[MenuItem("Debug/Logger")]
public static void Init() {
LoggerWindow window =
(LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow));
window.title = "Logger";
window.minSize = new Vector2(100f, 60f);
}
private void OnGUI() {
EditorGUILayout.BeginHorizontal();
// Draw Start/Stop button.
LoggerInstance.LoggingEnabled =
InspectorControls.DrawStartStopButton(
LoggerInstance.LoggingEnabled,
LoggerInstance.EnableOnPlay,
null,
() => LoggerInstance.LogWriter.Add("[PAUSE]", true),
() => LoggerInstance.LogWriter.WriteAll(
LoggerInstance.FilePath,
false));
// Draw -> button.
if (GUILayout.Button("->", GUILayout.Width(30))) {
EditorGUIUtility.PingObject(LoggerInstance);
Selection.activeGameObject = LoggerInstance.gameObject;
}
EditorGUILayout.EndHorizontal();
Repaint();
}
}
}
| mit | C# |
ad509142ea6a61a6589404d5fffe04fef184dcdf | change stateProvider to an Action so it cannot be replaced externally | Pondidum/Finite,Pondidum/Finite | Finite/StateMachine.cs | Finite/StateMachine.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Finite.Configurations;
namespace Finite
{
public class StateMachine<TSwitches>
{
private readonly MachineConfiguration<TSwitches> _configuration;
private readonly States<TSwitches> _states;
private readonly TSwitches _switches;
public StateMachine(Action<States<TSwitches>> stateProvider, TSwitches switches)
: this(null, stateProvider, switches)
{
}
public StateMachine(Action<MachineConfiguration<TSwitches>> customiseConfiguration, Action<States<TSwitches>> buildStates, TSwitches switches)
{
_switches = switches;
_configuration = new MachineConfiguration<TSwitches>();
_states = new States<TSwitches>();
if (customiseConfiguration != null)
customiseConfiguration(_configuration);
buildStates(_states);
_states.InitialiseStates(_configuration.InstanceCreator);
}
public State<TSwitches> CurrentState { get; private set; }
public IEnumerable<State<TSwitches>> AllTargetStates
{
get { return CurrentState.Links.Select(l => l.Target); }
}
public IEnumerable<State<TSwitches>> ActiveTargetStates
{
get { return CurrentState.Links.Where(l => l.IsActive(_switches)).Select(l => l.Target); }
}
public IEnumerable<State<TSwitches>> InactiveTargetStates
{
get { return CurrentState.Links.Where(l => l.IsActive(_switches) == false).Select(l => l.Target); }
}
public void ResetTo<TTarget>() where TTarget : State<TSwitches>
{
CurrentState = _states.GetStateFor<TTarget>();
}
public void TransitionTo<TTarget>() where TTarget : State<TSwitches>
{
var type = typeof(TTarget);
var targetState = _states.GetStateFor<TTarget>();
if (CurrentState == null)
{
throw new StateMachineException();
}
if (CurrentState.CanTransitionTo(_switches, targetState) == false)
{
throw new InvalidTransitionException(CurrentState.GetType(), type);
}
var stateChangeArgs = new StateChangeEventArgs<TSwitches>(_switches, CurrentState, targetState);
OnLeaveState(stateChangeArgs);
CurrentState = targetState;
OnEnterState(stateChangeArgs);
}
private void OnEnterState(StateChangeEventArgs<TSwitches> stateChangeArgs)
{
CurrentState.OnEnter(this, stateChangeArgs);
_configuration.StateChangedHandler.OnEnterState(this, stateChangeArgs);
}
private void OnLeaveState(StateChangeEventArgs<TSwitches> stateChangeArgs)
{
_configuration.StateChangedHandler.OnLeaveState(this, stateChangeArgs);
if (stateChangeArgs.Previous != null)
{
stateChangeArgs.Previous.OnLeave(this, stateChangeArgs);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Finite.Configurations;
namespace Finite
{
public class StateMachine<TSwitches>
{
private readonly MachineConfiguration<TSwitches> _configuration;
private readonly States<TSwitches> _states;
private readonly TSwitches _switches;
public StateMachine(Func<States<TSwitches>, States<TSwitches>> stateProvider, TSwitches switches)
: this(null, stateProvider, switches)
{
}
public StateMachine(Action<MachineConfiguration<TSwitches>> customiseConfiguration, Func<States<TSwitches>, States<TSwitches>> stateProvider, TSwitches switches)
{
_switches = switches;
_configuration = new MachineConfiguration<TSwitches>();
if (customiseConfiguration != null)
customiseConfiguration(_configuration);
var states = stateProvider.Invoke(new States<TSwitches>());
states.InitialiseStates(_configuration.InstanceCreator);
_states = states;
}
public State<TSwitches> CurrentState { get; private set; }
public IEnumerable<State<TSwitches>> AllTargetStates
{
get { return CurrentState.Links.Select(l => l.Target); }
}
public IEnumerable<State<TSwitches>> ActiveTargetStates
{
get { return CurrentState.Links.Where(l => l.IsActive(_switches)).Select(l => l.Target); }
}
public IEnumerable<State<TSwitches>> InactiveTargetStates
{
get { return CurrentState.Links.Where(l => l.IsActive(_switches) == false).Select(l => l.Target); }
}
public void ResetTo<TTarget>() where TTarget : State<TSwitches>
{
CurrentState = _states.GetStateFor<TTarget>();
}
public void TransitionTo<TTarget>() where TTarget : State<TSwitches>
{
var type = typeof(TTarget);
var targetState = _states.GetStateFor<TTarget>();
if (CurrentState == null)
{
throw new StateMachineException();
}
if (CurrentState.CanTransitionTo(_switches, targetState) == false)
{
throw new InvalidTransitionException(CurrentState.GetType(), type);
}
var stateChangeArgs = new StateChangeEventArgs<TSwitches>(_switches, CurrentState, targetState);
OnLeaveState(stateChangeArgs);
CurrentState = targetState;
OnEnterState(stateChangeArgs);
}
private void OnEnterState(StateChangeEventArgs<TSwitches> stateChangeArgs)
{
CurrentState.OnEnter(this, stateChangeArgs);
_configuration.StateChangedHandler.OnEnterState(this, stateChangeArgs);
}
private void OnLeaveState(StateChangeEventArgs<TSwitches> stateChangeArgs)
{
_configuration.StateChangedHandler.OnLeaveState(this, stateChangeArgs);
if (stateChangeArgs.Previous != null)
{
stateChangeArgs.Previous.OnLeave(this, stateChangeArgs);
}
}
}
}
| lgpl-2.1 | C# |
2c279ebbdbb2f1b8c75b480e11e72e1670eeb037 | add some stubs | ravjotsingh9/StockTradingApplication | ClientServer/Server/Stock.cs | ClientServer/Server/Stock.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Server.Yahoo_Finance;
//
namespace Server
{
public class Stock
{
public string stockname;
public float stockprice;
// Stock list and price in memory
private Dictionary<string, string> StocksDictionary = new Dictionary<string, string>();
// file's name for stock's information stores in the Disk
private string fileStock;
// file's name for users' information stores in the Disk
private string users;
// querys to update all the stock's price
private List<stockQuote> updatequerys { get; set; }
// constructor
public Stock()
{
}
///You can use this function to test the stock value
///stockIdentifier : stock's name
///For example, Apple should input as AAPL
///You can see the right stock name from here:
///https://finance.yahoo.com/q?s=AAPL
// string val = getPriceFromYahoo("AAPL");
public String getPriceFromYahoo(String stockIdentifier)
{
string price = "";
List<stockQuote> queryPrice = new List<stockQuote>();
queryPrice.Add(new stockQuote(stockIdentifier));
getStockData.getData(queryPrice);
stockQuote value = queryPrice.ElementAt(0);
price = value.LastTradePrice.ToString();
return price;
}
// update the price for all the stocks
public bool updateAllPrice(List<stockQuote> updateList)
{
bool success = false;
return success;
}
public void addToTheStockList(string stockName, string price)
{
this.StocksDictionary.Add(stockname,price);
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Server.Yahoo_Finance;
//
namespace Server
{
public class Stock
{
public string stockname;
public float stockprice;
private List<stockQuote> querys { get; set; }
public Stock()
{
}
///You can use this function to test the stock value
///stockIdentifier : stock's name
///For example, Apple should input as AAPL
///You can see the right stock name from here:
///https://finance.yahoo.com/q?s=AAPL
// string val = getPriceFromYahoo("AAPL");
public String getPriceFromYahoo(String stockIdentifier)
{
string price = "";
List<stockQuote> queryPrice = new List<stockQuote>();
queryPrice.Add(new stockQuote(stockIdentifier));
getStockData.getData(queryPrice);
stockQuote value = queryPrice.ElementAt(0);
price = value.LastTradePrice.ToString();
return price;
}
// update the price for all the stocks
public void updateAllPrice(List<stockQuote> updateList)
{
}
}
}
| apache-2.0 | C# |
d1c3dffc6e25254b2a47d10f05e473b6e84b00a6 | Update console test output | refactorsaurusrex/FluentConsole | TestConsole/Program.cs | TestConsole/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentConsole.Library;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
FluentConsoleSettings.LineWrapOption = LineWrapOption.Manual;
FluentConsoleSettings.LineWrapWidth = 25;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
FluentConsoleSettings.LineWrapOption = LineWrapOption.Auto;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
"This is a much shorter string, with zero line breaks.".WriteLine();
"This is a green string with one line break.".WriteLine(ConsoleColor.Green, 1);
"A red string, with zero breaks, and waits after printing".WriteLineWait(ConsoleColor.Red);
"This is a much shorter string, with zero line breaks.".WriteLineWait();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentConsole.Library;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
FluentConsoleSettings.LineWrapOption = LineWrapOption.Auto;
FluentConsoleSettings.LineWrapWidth = 50;
"This is a really long string, longer than the default width of the Console window buffer. With any luck, this will be displayed as expected!".WriteLineWait();
}
}
}
| mit | C# |
b6a5cd8cfc8da2251cd1284d5f4578f68fe54781 | Fix missing return | maxthecatstudios/UnityTC | UnityTC.CLI/Program.cs | UnityTC.CLI/Program.cs | //
// © 2016 Max the Cat Studios Ltd.
//
// https://maxthecatstudios.com
// @maxthecatstudio
//
// Created By Desmond Fernando 2016 06 30 12:22 PM
//
//
//
using System.Linq;
namespace UnityTC.CLI
{
class Program
{
private static int Main( string[] args )
{
return Unity.StartUnity( args[ 0 ], string.Join( " ", args, 1, args.Length - 1 ) );
}
}
} | //
// © 2016 Max the Cat Studios Ltd.
//
// https://maxthecatstudios.com
// @maxthecatstudio
//
// Created By Desmond Fernando 2016 06 30 12:22 PM
//
//
//
using System.Linq;
namespace UnityTC.CLI
{
class Program
{
static void Main( string[] args )
{
Unity.StartUnity( args[ 0 ], string.Join( " ", args, 1, args.Length - 1 ) );
}
}
} | mit | C# |
8cd957784e820f039ca13ccb13019a3a24c2847b | Remove Main()'s unused args parameter | OlsonDev/YeamulNet | Yeamul.Test/Program.cs | Yeamul.Test/Program.cs | using System;
namespace Yeamul.Test {
class Program {
static void Main() {
Node nn = Node.Null;
Console.WriteLine(nn);
Node nbt = true;
Console.WriteLine(nbt);
Node nbf = false;
Console.WriteLine(nbf);
Node n16 = short.MinValue;
Console.WriteLine(n16);
Node n32 = int.MinValue;
Console.WriteLine(n32);
Node n64 = long.MinValue;
Console.WriteLine(n64);
Node nu16 = ushort.MaxValue;
Console.WriteLine(nu16);
Node nu32 = uint.MaxValue;
Console.WriteLine(nu32);
Node nu64 = ulong.MaxValue;
Console.WriteLine(nu64);
Node nf = 1.2f;
Console.WriteLine(nf);
Node nd = Math.PI;
Console.WriteLine(nd);
Node nm = 1.2345678901234567890m;
Console.WriteLine(nm);
Node ng = Guid.NewGuid();
Console.WriteLine(ng);
Node ns = "derp";
Console.WriteLine(ns);
Console.ReadKey();
}
}
} | using System;
namespace Yeamul.Test {
class Program {
static void Main(string[] args) {
Node nn = Node.Null;
Console.WriteLine(nn);
Node nbt = true;
Console.WriteLine(nbt);
Node nbf = false;
Console.WriteLine(nbf);
Node n16 = short.MinValue;
Console.WriteLine(n16);
Node n32 = int.MinValue;
Console.WriteLine(n32);
Node n64 = long.MinValue;
Console.WriteLine(n64);
Node nu16 = ushort.MaxValue;
Console.WriteLine(nu16);
Node nu32 = uint.MaxValue;
Console.WriteLine(nu32);
Node nu64 = ulong.MaxValue;
Console.WriteLine(nu64);
Node nf = 1.2f;
Console.WriteLine(nf);
Node nd = Math.PI;
Console.WriteLine(nd);
Node nm = 1.2345678901234567890m;
Console.WriteLine(nm);
Node ng = Guid.NewGuid();
Console.WriteLine(ng);
Node ns = "derp";
Console.WriteLine(ns);
Console.ReadKey();
}
}
} | mit | C# |
be971cb6f72824b0a130b0e36dde126a43bb38a2 | Allow forced encoding to override default encoding | adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress | src/SharpCompress/Common/ArchiveEncoding.cs | src/SharpCompress/Common/ArchiveEncoding.cs | using System;
using System.Text;
namespace SharpCompress.Common
{
public class ArchiveEncoding
{
/// <summary>
/// Default encoding to use when archive format doesn't specify one.
/// </summary>
public Encoding Default { get; set; }
/// <summary>
/// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898.
/// </summary>
public Encoding Password { get; set; }
/// <summary>
/// Set this encoding when you want to force it for all encoding operations.
/// </summary>
public Encoding Forced { get; set; }
/// <summary>
/// Set this when you want to use a custom method for all decoding operations.
/// </summary>
/// <returns>string Func(bytes, index, length)</returns>
public Func<byte[], int, int, string> CustomDecoder { get; set; }
public ArchiveEncoding()
{
Default = Encoding.UTF8;
Password = Encoding.UTF8;
}
#if NETSTANDARD1_3 || NETSTANDARD2_0
static ArchiveEncoding()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
#endif
public string Decode(byte[] bytes)
{
return Decode(bytes, 0, bytes.Length);
}
public string Decode437(byte[] bytes)
{
#if NETSTANDARD1_0
return Decode(bytes, 0, bytes.Length);
#else
//allow forced to override this.
if (Forced != null)
{
return Decode(bytes, 0, bytes.Length);
}
var extendedAsciiEncoding = Encoding.GetEncoding(437);
return extendedAsciiEncoding.GetString(bytes, 0, bytes.Length);
#endif
}
public string Decode(byte[] bytes, int start, int length)
{
return GetDecoder().Invoke(bytes, start, length);
}
public byte[] Encode(string str)
{
return GetEncoding().GetBytes(str);
}
public Encoding GetEncoding()
{
return Forced ?? Default ?? Encoding.UTF8;
}
public Func<byte[], int, int, string> GetDecoder()
{
return CustomDecoder ?? ((bytes, index, count) => (Default ?? Encoding.UTF8).GetString(bytes, index, count));
}
}
} | using System;
using System.Text;
namespace SharpCompress.Common
{
public class ArchiveEncoding
{
/// <summary>
/// Default encoding to use when archive format doesn't specify one.
/// </summary>
public Encoding Default { get; set; }
/// <summary>
/// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898.
/// </summary>
public Encoding Password { get; set; }
/// <summary>
/// Set this encoding when you want to force it for all encoding operations.
/// </summary>
public Encoding Forced { get; set; }
/// <summary>
/// Set this when you want to use a custom method for all decoding operations.
/// </summary>
/// <returns>string Func(bytes, index, length)</returns>
public Func<byte[], int, int, string> CustomDecoder { get; set; }
public ArchiveEncoding()
{
Default = Encoding.UTF8;
Password = Encoding.UTF8;
}
#if NETSTANDARD1_3 || NETSTANDARD2_0
static ArchiveEncoding()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
#endif
public string Decode(byte[] bytes)
{
return Decode(bytes, 0, bytes.Length);
}
public string Decode437(byte[] bytes)
{
#if NETSTANDARD1_0
return Decode(bytes, 0, bytes.Length);
#else
var extendedAsciiEncoding = Encoding.GetEncoding(437);
return extendedAsciiEncoding.GetString(bytes, 0, bytes.Length);
#endif
}
public string Decode(byte[] bytes, int start, int length)
{
return GetDecoder().Invoke(bytes, start, length);
}
public byte[] Encode(string str)
{
return GetEncoding().GetBytes(str);
}
public Encoding GetEncoding()
{
return Forced ?? Default ?? Encoding.UTF8;
}
public Func<byte[], int, int, string> GetDecoder()
{
return CustomDecoder ?? ((bytes, index, count) => (Default ?? Encoding.UTF8).GetString(bytes, index, count));
}
}
} | mit | C# |
d2882729fdf1231bfccc43f4a683834e0366a441 | change the android apk path filename to be correct (#27) | xamarinhq/app-evolve,xamarinhq/app-evolve | src/XamarinEvolve.UITests/AppInitializer.cs | src/XamarinEvolve.UITests/AppInitializer.cs | using System;
using System.IO;
using System.Linq;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace XamarinEvolve.UITests
{
public class AppInitializer
{
const string apkfile = "../../../XamarinEvolve.Android/bin/UITest/com.xamarin.xamarinevolve-Signed.apk";
// const string appfile = "../../../XamarinEvolve.iOS/bin/iPhoneSimulator/Debug/XamarinEvolveiOS.app";
private static IApp app;
public static IApp App
{
get
{
if (app == null)
throw new NullReferenceException("'AppInitializer.App' not set. Call 'AppInitializer.StartApp(platform)' before trying to access it.");
return app;
}
}
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
app = ConfigureApp.Android.ApkFile(apkfile)
.StartApp(Xamarin.UITest.Configuration.AppDataMode.Clear);
}
else
{
app = ConfigureApp.iOS.InstalledApp("com.sample.evolve")
.StartApp(Xamarin.UITest.Configuration.AppDataMode.Clear);
}
return app;
}
}
}
| using System;
using System.IO;
using System.Linq;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace XamarinEvolve.UITests
{
public class AppInitializer
{
const string apkfile = "../../../XamarinEvolve.Android/bin/UITest/com.sample.evolve-Signed.apk";
// const string appfile = "../../../XamarinEvolve.iOS/bin/iPhoneSimulator/Debug/XamarinEvolveiOS.app";
private static IApp app;
public static IApp App
{
get
{
if (app == null)
throw new NullReferenceException("'AppInitializer.App' not set. Call 'AppInitializer.StartApp(platform)' before trying to access it.");
return app;
}
}
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
app = ConfigureApp.Android.ApkFile(apkfile)
.StartApp(Xamarin.UITest.Configuration.AppDataMode.Clear);
}
else
{
app = ConfigureApp.iOS.InstalledApp("com.sample.evolve")
.StartApp(Xamarin.UITest.Configuration.AppDataMode.Clear);
}
return app;
}
}
}
| mit | C# |
314f16af39cd7974aceb35e81a4d6bec1dedeb83 | Fix some documentation incorrectness. | nohros/must,nohros/must,nohros/must | src/base/common/data/readers/DataReaders.cs | src/base/common/data/readers/DataReaders.cs | using System;
using System.Data;
using Nohros.Resources;
namespace Nohros.Data
{
/// <summary>
/// Utility methods for <see cref="IDataReader"/>.
/// </summary>
public sealed class DataReaders
{
/// <summary>
/// Return the indexes of the named fields.
/// </summary>
/// <param name="data_reader">
/// A <see cref="IDataReader"/> containing the fileds to get the ordinals.
/// </param>
/// <param name="column_names">
/// A string array containing the names of the fields to find.
/// </param>
/// <returns>
/// An array containing the indexes of the specified column
/// names within the <paramref name="data_reader"/>. The indexes is
/// returned in the same order they appear on column names array.
/// </returns>
/// <remarks>
/// Ordinal-based lookups are more efficient than name lookups, it
/// is inefficient to call <see cref="IDataReader.GetOrdinal"/> within a
/// loop. This method provides a convenient way to call the
/// <see cref="IDataReader.GetOrdinal"/> method for a set of columns
/// defined within a <paramref name="data_reader"/> and reduce the
/// code len used for that purpose.
/// </remarks>
/// <exception cref="ArgumentException">
/// The number of specified fields is less than the number of columns.
/// </exception>
public static int[] GetOrdinals(IDataReader data_reader,
params string[] column_names) {
int[] ordinals = new int[column_names.Length];
int j = column_names.Length;
if (data_reader.FieldCount < j) {
throw new ArgumentException(
StringResources.Argument_ArrayLengthMismatch);
}
for (int i = 0; i < j; i++) {
ordinals[i] = data_reader.GetOrdinal(column_names[i]);
}
return ordinals;
}
}
}
| using System;
using System.Data;
using Nohros.Resources;
namespace Nohros.Data
{
/// <summary>
/// Utility methods for <see cref="IDataReader"/>.
/// </summary>
public sealed class DataReaders
{
/// <summary>
/// Return the indexes of the named fields.
/// </summary>
/// <param name="data_reader">
/// A <see cref="IDataReader"/> containing the fileds to get the ordinals.
/// </param>
/// <param name="column_names">
/// A string array containing the names of the fields to find.
/// </param>
/// <returns>
/// An array containing the indexes of the specified column
/// names within the <paramref name="data_reader"/>. The indexes is
/// returned in the same order they appear on column names array.
/// </returns>
/// <remarks>
/// Ordinal-based lookups are more efficient than name lookups, it
/// is inefficient to call <see cref="IDataReader.GetOrdinal"/> within a
/// loop. This method provides a convenient way to call the
/// <see cref="IDataReader.GetOrdinal"/> method for a set of columns
/// defined within a <paramref name="data_reader"/> and reduce the
/// code len used for that purpose.
/// </remarks>
/// <exception cref="ArgumentException">
/// The number of specified fields is less than the number of columns.
/// </exception>
public static int[] GetOrdinals(IDataReader data_reader,
params string[] column_names) {
int[] ordinals = new int[column_names.Length];
int j = column_names.Length;
if (data_reader.FieldCount < j) {
throw new ArgumentException(
StringResources.Argument_ArrayLengthMismatch);
}
for (int i = 0; i < j; i++) {
ordinals[i] = data_reader.GetOrdinal(column_names[i]);
}
return ordinals;
}
public static IDataField<T>
}
}
| mit | C# |
4b9d1496acbe29a0d64609db07923dd99f746bc7 | Move SharpDX to next minor verison 2.5.1 | tomba/Toolkit,sharpdx/Toolkit,sharpdx/Toolkit | Source/SharedAssemblyInfo.cs | Source/SharedAssemblyInfo.cs | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.5.1")]
[assembly:AssemblyFileVersion("2.5.1")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
| // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.5.0")]
[assembly:AssemblyFileVersion("2.5.0")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
| mit | C# |
a178c44b60e578cf654d57d2a98361d94d147737 | Remove snap line dependencies | ppy/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,naoey/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu | osu.Game.Rulesets.Mania/Edit/ManiaEditPlayfield.cs | osu.Game.Rulesets.Mania/Edit/ManiaEditPlayfield.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.UI;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Mania.Edit
{
public class ManiaEditPlayfield : ManiaPlayfield
{
protected override bool DisplayJudgements => false;
public ManiaEditPlayfield(List<StageDefinition> stages)
: base(stages)
{
}
protected override ManiaStage CreateStage(int firstColumnIndex, StageDefinition definition, ref ManiaAction normalColumnStartAction, ref ManiaAction specialColumnStartAction)
=> new ManiaEditStage(firstColumnIndex, definition, ref normalColumnStartAction, ref specialColumnStartAction);
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.UI;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Rulesets.Mania.Edit
{
public class ManiaEditPlayfield : ManiaPlayfield
{
protected override bool DisplayJudgements => false;
public ManiaEditPlayfield(List<StageDefinition> stages)
: base(stages)
{
}
public void Add(EditSnapLine editSnapLine) => Stages.Cast<ManiaEditStage>().ForEach(s => s.Add(editSnapLine));
public void Remove(DrawableManiaEditSnapLine editSnapLine) => Stages.Cast<ManiaEditStage>().ForEach(s => s.Remove(editSnapLine));
public void ClearEditSnapLines() => Stages.Cast<ManiaEditStage>().ForEach(s => s.ClearEditSnapLines());
protected override ManiaStage CreateStage(int firstColumnIndex, StageDefinition definition, ref ManiaAction normalColumnStartAction, ref ManiaAction specialColumnStartAction)
=> new ManiaEditStage(firstColumnIndex, definition, ref normalColumnStartAction, ref specialColumnStartAction);
}
}
| mit | C# |
1038034172c0c12938bc66fe7c399cd8c0d4733f | Update example | JokkeeZ/Twitchie | Twitchie2.Example/Program.cs | Twitchie2.Example/Program.cs | using System;
using System.Threading.Tasks;
using Twitchie2.Events;
namespace Twitchie2.Example
{
class Program
{
static async Task Main()
{
using var twitchie = new Twitchie();
await twitchie.ConnectAsync();
twitchie.Login("jokkeez", "oauth:password");
twitchie.SetDefaultChannels(new[] { "#jokkeez" });
twitchie.OnMessage += OnMessage;
await twitchie.ListenAsync();
}
static void OnMessage(object sender, MessageEventArgs e)
{
Console.WriteLine($"User: {e.DisplayName} on channel: {e.Channel}: {e.Message}");
}
}
}
| using System;
using System.Threading.Tasks;
using Twitchie2.Events;
namespace Twitchie2.Example
{
class Program
{
static async Task Main(string[] args)
{
using var twitchie = new Twitchie();
await twitchie.ConnectAsync();
twitchie.Login("jokkeez", "oauth:password");
twitchie.SetDefaultChannels(new[] { "#jokkeez" });
twitchie.OnRawMessage += OnRawMessage;
await twitchie.ListenAsync();
}
static void OnRawMessage(object sender, RawMessageEventArgs e)
{
Console.WriteLine(e.Message);
}
}
}
| mit | C# |
d48e62a00cc4235fd5ac1f6d0373d51e73b18fe5 | Add a ParentScene property Add properties for WindowWidth and WindowHeight which help the syntax a bit | opcon/Substructio,opcon/Substructio | GUI/Scene.cs | GUI/Scene.cs | using System;
using Substructio.Core;
namespace Substructio.GUI
{
public abstract class Scene : IDisposable
{
#region Member Variables
#endregion
#region Properties
public bool Exclusive;
public bool Loaded;
public SceneManager SceneManager;
public Scene ParentScene;
public bool Visible;
public bool Removed;
public int WindowWidth {get { return SceneManager.Width; }}
public int WindowHeight {get { return SceneManager.Height; }}
#endregion
#region Constructors
/// <summary>
/// The default Constructor.
/// </summary>
public Scene()
{
Visible = true;
Exclusive = false;
Removed = false;
}
#endregion
#region Public Methods
/// <summary>
/// Load resources here
/// Make sure to set Loaded to true after it, or you'll fuck things up
/// </summary>
public abstract void Load();
/// <summary>
/// The regular callback that shall be used to process events from awesomium
/// </summary>
/// <param name="e">The callback arguments</param>
public abstract void CallBack(GUICallbackEventArgs e);
/// <summary>
/// Called when your window is resized. Set your viewport here. It is also
/// a good place to set up your projection matrix (which probably changes
/// along when the aspect ratio of your window).
/// </summary>
/// <param name="e">Not used.</param>
public abstract void Resize(EventArgs e);
/// <summary>
/// Called when it is time to setup the next frame. Add you game logic here.
/// </summary>
/// <param name="time">Contains timing information for framerate independent logic.</param>
/// <param name="b"></param>
public abstract void Update(double time, bool focused = false);
/// <summary>
/// Called when it is time to render the next frame. Add your rendering code here.
/// </summary>
/// <param name="time">Contains timing information.</param>
public abstract void Draw(double time);
/// <summary>
/// Unload and shutdown screen here
/// </summary>
public abstract void Dispose();
#endregion
#region Private Methods
#endregion
}
} | using System;
using Substructio.Core;
namespace Substructio.GUI
{
public abstract class Scene : IDisposable
{
#region Member Variables
#endregion
#region Properties
public bool Exclusive;
public bool Loaded;
public SceneManager SceneManager;
public bool Visible;
public bool Removed;
#endregion
#region Constructors
/// <summary>
/// The default Constructor.
/// </summary>
public Scene()
{
Visible = true;
Exclusive = false;
Removed = false;
}
#endregion
#region Public Methods
/// <summary>
/// Load resources here
/// Make sure to set Loaded to true after it, or you'll fuck things up
/// </summary>
public abstract void Load();
/// <summary>
/// The regular callback that shall be used to process events from awesomium
/// </summary>
/// <param name="e">The callback arguments</param>
public abstract void CallBack(GUICallbackEventArgs e);
/// <summary>
/// Called when your window is resized. Set your viewport here. It is also
/// a good place to set up your projection matrix (which probably changes
/// along when the aspect ratio of your window).
/// </summary>
/// <param name="e">Not used.</param>
public abstract void Resize(EventArgs e);
/// <summary>
/// Called when it is time to setup the next frame. Add you game logic here.
/// </summary>
/// <param name="time">Contains timing information for framerate independent logic.</param>
/// <param name="b"></param>
public abstract void Update(double time, bool focused = false);
/// <summary>
/// Called when it is time to render the next frame. Add your rendering code here.
/// </summary>
/// <param name="time">Contains timing information.</param>
public abstract void Draw(double time);
/// <summary>
/// Unload and shutdown screen here
/// </summary>
public abstract void Dispose();
#endregion
#region Private Methods
#endregion
}
} | mit | C# |
fa2754cb07cb110910378f76cd9aaac7539d4eff | Add test for autor properties | paulodiovani/feevale-cs-livraria-2015 | LivrariaTest/AutorTest.cs | LivrariaTest/AutorTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Livraria;
namespace LivrariaTest
{
[TestClass]
public class AutorTest
{
[TestMethod]
public void TestProperties()
{
Autor autor = new Autor();
autor.CodAutor = 999;
autor.Nome = "George R. R. Martin";
autor.Cpf = "012.345.678.90";
autor.DtNascimento = new DateTime(1948, 9, 20);
Assert.AreEqual(autor.CodAutor, 999);
Assert.AreEqual(autor.Nome, "George R. R. Martin");
Assert.AreEqual(autor.Cpf, "012.345.678.90");
Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LivrariaTest
{
[TestClass]
public class AutorTest
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(true, true);
}
}
}
| mit | C# |
59f33a7dc00f5678abeb5c257a4f0391dcd662f8 | Update Dewey Create View's number input to be of type number. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Views/Deweys/Create.cshtml | src/Open-School-Library/Views/Deweys/Create.cshtml | @model Open_School_Library.Models.DeweyViewModels.DeweyCreateViewModel
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Dewey</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Number" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Number" type="number" class="form-control" />
<span asp-validation-for="Number" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
| @model Open_School_Library.Models.DeweyViewModels.DeweyCreateViewModel
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Dewey</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Number" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Number" class="form-control" />
<span asp-validation-for="Number" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
| mit | C# |
8f93ed610d9e8ddd06791a0bbe6dc15247de934f | Update AlembicStreamPlayerEditor.cs | unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter | AlembicImporter/Assets/UTJ/AlembicImporter/Editor/AlembicStreamPlayerEditor.cs | AlembicImporter/Assets/UTJ/AlembicImporter/Editor/AlembicStreamPlayerEditor.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace UTJ.Alembic
{
[ExecuteInEditMode]
[CustomEditor(typeof(AlembicStreamPlayer))]
public class AlembicStreamPlayerEditor : Editor
{
public override void OnInspectorGUI()
{
SerializedProperty iterator = this.serializedObject.GetIterator();
for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
{
using (new EditorGUI.DisabledScope(false))
EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]);
}
this.serializedObject.ApplyModifiedProperties();
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace UTJ.Alembic
{
[ExecuteInEditMode]
[CustomEditor(typeof(AlembicStreamPlayer))]
public class AlembicStreamPlayerEditor : Editor
{
public override void OnInspectorGUI()
{
SerializedProperty iterator = this.serializedObject.GetIterator();
for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
{
using (new EditorGUI.DisabledScope(false))
{
EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]);
}
}
this.serializedObject.ApplyModifiedProperties();
}
}
}
| mit | C# |
b8f1b0e5a61724e47597fdd753ce0e0cf4d9a1e0 | Remove unneeded usings | TheEadie/PlayerRank,TheEadie/PlayerRank | UnitTests/HistoryTests.cs | UnitTests/HistoryTests.cs | using System.Linq;
using PlayerRank.Scoring.Simple;
using Xunit;
namespace PlayerRank.UnitTests
{
public class HistoryTests
{
[Fact]
public void CanGetHistoryOfLeague()
{
var league = new League();
for (var i = 0; i < 10; i++)
{
var game = new Game();
game.AddResult("Foo", new Points(5));
game.AddResult("Bar", new Points(1));
league.RecordGame(game);
}
var history = league.GetLeaderBoardHistory(new SimpleScoringStrategy()).ToList();
var fooAfterFiveGames = history[4].Leaderboard.Single(x => x.Name == "Foo");
var fooMostRecentGame = history.Last().Leaderboard.Single(x => x.Name == "Foo");
Assert.Equal(new Points(25), fooAfterFiveGames.Points);
Assert.Equal(new Points(50), fooMostRecentGame.Points);
}
}
} | using System.Collections.Generic;
using System.Linq;
using PlayerRank.Scoring;
using PlayerRank.Scoring.Simple;
using Xunit;
namespace PlayerRank.UnitTests
{
public class HistoryTests
{
[Fact]
public void CanGetHistoryOfLeague()
{
var league = new League();
for (var i = 0; i < 10; i++)
{
var game = new Game();
game.AddResult("Foo", new Points(5));
game.AddResult("Bar", new Points(1));
league.RecordGame(game);
}
var history = league.GetLeaderBoardHistory(new SimpleScoringStrategy()).ToList();
var fooAfterFiveGames = history[4].Leaderboard.Single(x => x.Name == "Foo");
var fooMostRecentGame = history.Last().Leaderboard.Single(x => x.Name == "Foo");
Assert.Equal(new Points(25), fooAfterFiveGames.Points);
Assert.Equal(new Points(50), fooMostRecentGame.Points);
}
}
} | mit | C# |
8e828053183c7529433523bf1b9e26b0cbd8e5e0 | Fix off-by-one error in DisplayModeCollection. | alesliehughes/monoDX,alesliehughes/monoDX | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayModeCollection.cs | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayModeCollection.cs | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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;
using System.Runtime.InteropServices;
namespace Microsoft.DirectX.Direct3D
{
public sealed class DisplayModeCollection : IEnumerable, IEnumerator
{
private int _adapter;
private int _count;
private int _index;
private Format _format;
public DisplayModeCollection this [Format f] {
get => new DisplayModeCollection(_adapter, f);
}
public int Count {
get => _count;
}
public object Current {
get => Manager.GetAdapterDisplayMode(_adapter, _index, _format);
}
public void Reset ()
{
throw new NotImplementedException ();
}
public bool MoveNext ()
{
if (_index >= (_count - 1)) return false;
_index++;
return true;
}
public IEnumerator GetEnumerator ()
{
return this;
}
public override bool Equals (object compare)
{
throw new NotImplementedException ();
}
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
internal DisplayModeCollection (int adapter, Format format)
{
_adapter = adapter;
_count = Manager.GetAdapterDisplayModeCount(adapter, format);
_index = -1;
_format = format;
}
}
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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;
using System.Runtime.InteropServices;
namespace Microsoft.DirectX.Direct3D
{
public sealed class DisplayModeCollection : IEnumerable, IEnumerator
{
private int _adapter;
private int _count;
private int _index;
private Format _format;
public DisplayModeCollection this [Format f] {
get => new DisplayModeCollection(_adapter, f);
}
public int Count {
get => _count;
}
public object Current {
get => Manager.GetAdapterDisplayMode(_adapter, _index, _format);
}
public void Reset ()
{
throw new NotImplementedException ();
}
public bool MoveNext ()
{
if (_index >= _count) return false;
_index++;
return true;
}
public IEnumerator GetEnumerator ()
{
return this;
}
public override bool Equals (object compare)
{
throw new NotImplementedException ();
}
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
internal DisplayModeCollection (int adapter, Format format)
{
_adapter = adapter;
_count = Manager.GetAdapterDisplayModeCount(adapter, format);
_index = -1;
_format = format;
}
}
}
| mit | C# |
2cfa0b292d8b2ef86e9f6a4be875dd7cbbd355b5 | Fix exception message | arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp | src/Transport.cs | src/Transport.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
namespace NDesk.DBus.Transports
{
public abstract class Transport
{
public static Transport Create (AddressEntry entry)
{
switch (entry.Method) {
case "tcp":
{
Transport transport = new SocketTransport ();
transport.Open (entry);
return transport;
}
case "unix":
{
//Transport transport = new UnixMonoTransport ();
Transport transport = new UnixNativeTransport ();
transport.Open (entry);
return transport;
}
default:
throw new NotSupportedException ("Transport method \"" + entry.Method + "\" not supported");
}
}
protected Connection connection;
public Connection Connection
{
get {
return connection;
} set {
connection = value;
}
}
//TODO: design this properly
//this is just a temporary solution
public Stream Stream;
public long SocketHandle;
public abstract void Open (AddressEntry entry);
public abstract string AuthString ();
public abstract void WriteCred ();
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
namespace NDesk.DBus.Transports
{
public abstract class Transport
{
public static Transport Create (AddressEntry entry)
{
switch (entry.Method) {
case "tcp":
{
Transport transport = new SocketTransport ();
transport.Open (entry);
return transport;
}
case "unix":
{
//Transport transport = new UnixMonoTransport ();
Transport transport = new UnixNativeTransport ();
transport.Open (entry);
return transport;
}
default:
throw new NotSupportedException ("Transport method \"{0}\" not supported");
}
}
protected Connection connection;
public Connection Connection
{
get {
return connection;
} set {
connection = value;
}
}
//TODO: design this properly
//this is just a temporary solution
public Stream Stream;
public long SocketHandle;
public abstract void Open (AddressEntry entry);
public abstract string AuthString ();
public abstract void WriteCred ();
}
}
| mit | C# |
e3470c7ac30366a3a3fa4120c69d8b11615d79c1 | Remove unused enum | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices/Services/PowerShell/Execution/ExecutionOptions.cs | src/PowerShellEditorServices/Services/PowerShell/Execution/ExecutionOptions.cs | using System;
namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution
{
public enum ExecutionPriority
{
Normal,
Next,
}
public record ExecutionOptions
{
public static ExecutionOptions Default = new()
{
Priority = ExecutionPriority.Normal,
MustRunInForeground = false,
InterruptCurrentForeground = false,
};
public ExecutionPriority Priority { get; init; }
public bool MustRunInForeground { get; init; }
public bool InterruptCurrentForeground { get; init; }
}
public record PowerShellExecutionOptions : ExecutionOptions
{
public static new PowerShellExecutionOptions Default = new()
{
Priority = ExecutionPriority.Normal,
MustRunInForeground = false,
InterruptCurrentForeground = false,
WriteOutputToHost = false,
WriteInputToHost = false,
ThrowOnError = true,
AddToHistory = false,
};
public bool WriteOutputToHost { get; init; }
public bool WriteInputToHost { get; init; }
public bool ThrowOnError { get; init; }
public bool AddToHistory { get; init; }
}
}
| using System;
namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution
{
public enum TaskKind
{
Foreground,
Background,
}
public enum ExecutionPriority
{
Normal,
Next,
}
public record ExecutionOptions
{
public static ExecutionOptions Default = new()
{
Priority = ExecutionPriority.Normal,
MustRunInForeground = false,
InterruptCurrentForeground = false,
};
public ExecutionPriority Priority { get; init; }
public bool MustRunInForeground { get; init; }
public bool InterruptCurrentForeground { get; init; }
}
public record PowerShellExecutionOptions : ExecutionOptions
{
public static new PowerShellExecutionOptions Default = new()
{
Priority = ExecutionPriority.Normal,
MustRunInForeground = false,
InterruptCurrentForeground = false,
WriteOutputToHost = false,
WriteInputToHost = false,
ThrowOnError = true,
AddToHistory = false,
};
public bool WriteOutputToHost { get; init; }
public bool WriteInputToHost { get; init; }
public bool ThrowOnError { get; init; }
public bool AddToHistory { get; init; }
}
}
| mit | C# |
9cbceaa4b6f74c50b646aacdd740aab7486961ef | Update foodservices.cs | RobinsonMann/UWaterlooApi | foodservices/foodservices.cs | foodservices/foodservices.cs | /*....By : Robinson Mann
*..Date : 2/3/2015
*.About : Contians all the classes need for any of the foodserivces
* API calls, aswell as associated factory methods.
**********************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Net;
using System.IO;
namespace UWaterlooAPI.FoodServices
{
public class Date
{
public int? week { get; set; }
public int? year { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Outlet {
public string outlet_name { get; set; }
public int? outlet_id { get; set; }
public IEnumerable<OutletMenu> menu { get; set; }
}
public class OutletMenu
{
string date { get; set; }
string day { get; set; }
public IEnumerable<Meals> meals { get; set; }
}
public class Meals
{
public IEnumerable<Meal> lunch { get; set; }
public IEnumerable<Meal> dinner { get; set; }
}
public class Meal
{
public string product_name { get; set; }
public string diet_type { get; set; }
public int product_id { get; set; }
}
public class WeeklyFoodMenu
{
public Date date { get; set; }
public IEnumerable<Outlet> outlets;
}
public class Note
{
public Date date { get; set; }
public string outlet_name { get; set; }
public int outlet_id { get; set; }
public string note { get; set; }
}
public class Notes
{
public IEnumerable<Note> notes;
}
public class Diet
{
public int diet_id {get;set;}
public string diet_type {get;set;}
}
public class FoodServicesApiFactory
{
/* TODO: Have the functions actually call the API. Research Json.Net (?) -- Should be helpful in mapping fields. */
public UWaterlooAPI.ApiCall<WeeklyFoodMenu> menu()
{
UWaterlooAPI.ApiCall<WeeklyFoodMenu> WeeklyFoodMenu = new UWaterlooAPI.ApiCall<WeeklyFoodMenu>();
return WeeklyFoodMenu;
}
public UWaterlooAPI.ApiCall<Notes> notes()
{
UWaterlooAPI.ApiCall<Notes> notes = new UWaterlooAPI.ApiCall<Notes>();
return notes;
}
}
}
| /*....By : Robinson Mann
*..Date : 2/3/2015
*.About : Contians all the classes need for any of the foodserivces
* API calls, aswell as associated factory methods.
**********************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Net;
using System.IO;
namespace UWaterlooAPI.FoodServices
{
public class Date
{
public int? week { get; set; }
public int? year { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Outlet {
public string outlet_name { get; set; }
public int? outlet_id { get; set; }
public IEnumerable<OutletMenu> menu { get; set; }
}
public class OutletMenu
{
string date { get; set; }
string day { get; set; }
public IEnumerable<Meals> meals { get; set; }
}
public class Meals
{
public IEnumerable<Meal> lunch { get; set; }
public IEnumerable<Meal> dinner { get; set; }
}
public class Meal
{
public string product_name { get; set; }
public string diet_type { get; set; }
public int product_id { get; set; }
}
public class WeeklyFoodMenu
{
public Date date { get; set; }
public IEnumerable<Outlet> outlets;
}
/* */
public class Note
{
public Date date { get; set; }
public string outlet_name { get; set; }
public int outlet_id { get; set; }
//TODO: 'note' *might* not be a string -- Specs aren't clear
public string note { get; set; }
}
public class Notes
{
public IEnumerable<Note> notes;
}
public class Diet
{
public int diet_id {get;set;}
public string diet_type {get;set;}
}
public class FoodServicesApiFactory
{
public UWaterlooAPI.ApiCall<WeeklyFoodMenu> menu()
{
UWaterlooAPI.ApiCall<WeeklyFoodMenu> WeeklyFoodMenu = new UWaterlooAPI.ApiCall<WeeklyFoodMenu>();
return WeeklyFoodMenu;
}
public Notes notes()
{
return null;
}
}
}
| mit | C# |
a0255504a30f3eccd91dd706d01bf00e335daf3e | Update version | gahcep/App.Refoveo | App.Refoveo/Properties/GlobalAssemblyInfo.cs | App.Refoveo/Properties/GlobalAssemblyInfo.cs | using System.Reflection;
/* General Product Information */
[assembly: AssemblyProduct("App.Refoveo")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
/* Configuration Type */
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
/* Assembly Versioning: mixture of MSDN and SemVer approaches
* MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx
* SemVer: http://semver.org/spec/v2.0.0.html
*
* Format: Major.Minor.Patch-ReleaseType.BuildNum
* - Major - for incompatible API changes (big changes)
* - Minor - for adding functionality in a backwards-compatible manner (small changes)
* - Patch - for bugfixes (increments only for "bugfix/" branch)
* - ReleaseType - additional information: either
* -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch)
* -- "alpha" - active development and adding new features ("dev" branch)
* -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch)
* -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch)
* -- "release" - release in production ("release" branch)
* -- "release.hotfix" - rapid bugfix for release ("hotfix" branch)
*
* AssemblyVersion - defines a version for the product itself
* -- format: Major.Minor.0
* AssemblyFileVersion - defines a version for particular assembly
* -- format: Major.Minor.Patch
* AssemblyInformationalVersion - defines detailed version for the product and assemblies
* -- format: Major.Minor.Patch-ReleaseType.BuildNumber
*
* {develop} branch contains ONLY alpha version
*/
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
[assembly: AssemblyInformationalVersion("0.5.0-alpha.6")]
| using System.Reflection;
/* General Product Information */
[assembly: AssemblyProduct("App.Refoveo")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
/* Configuration Type */
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
/* Assembly Versioning: mixture of MSDN and SemVer approaches
* MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx
* SemVer: http://semver.org/spec/v2.0.0.html
*
* Format: Major.Minor.Patch-ReleaseType.BuildNum
* - Major - for incompatible API changes (big changes)
* - Minor - for adding functionality in a backwards-compatible manner (small changes)
* - Patch - for bugfixes (increments only for "bugfix/" branch)
* - ReleaseType - additional information: either
* -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch)
* -- "alpha" - active development and adding new features ("dev" branch)
* -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch)
* -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch)
* -- "release" - release in production ("release" branch)
* -- "release.hotfix" - rapid bugfix for release ("hotfix" branch)
*
* AssemblyVersion - defines a version for the product itself
* -- format: Major.Minor.0
* AssemblyFileVersion - defines a version for particular assembly
* -- format: Major.Minor.Patch
* AssemblyInformationalVersion - defines detailed version for the product and assemblies
* -- format: Major.Minor.Patch-ReleaseType.BuildNumber
*
* {develop} branch contains ONLY alpha version
*/
[assembly: AssemblyVersion("0.4.0")]
[assembly: AssemblyFileVersion("0.4.0")]
[assembly: AssemblyInformationalVersion("0.4.0-alpha.5")]
| mit | C# |
0103cf8e2d82317972e45cf861b5ca9ad5b1a532 | fix bug for losing permessageorexecution lifetime manager case in MSDbContext constructrue | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework.Plugins/iFramework.Infrastructure.EntityFramework/MSDbContext.cs | Src/iFramework.Plugins/iFramework.Infrastructure.EntityFramework/MSDbContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Reflection;
using IFramework.Domain;
using IFramework.Infrastructure;
using IFramework.UnitOfWork;
using IFramework.Infrastructure.Unity.LifetimeManagers;
using System.Web;
using System.ServiceModel;
namespace IFramework.EntityFramework
{
public static class QueryableCollectionInitializer
{
public static void InitializeQueryableCollections(this MSDbContext context, object entity)
{
var dbEntity = entity as Entity;
if (dbEntity != null)
{
((dynamic)dbEntity).DomainContext = context;
}
}
}
public class MSDbContext : DbContext
{
public MSDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
InitObjectContext();
if ((BaseUnitOfWork.UnitOfWorkLifetimeManagerType == typeof(PerMessageContextLifetimeManager)
&& PerMessageContextLifetimeManager.CurrentMessageContext != null)
|| (BaseUnitOfWork.UnitOfWorkLifetimeManagerType == typeof(PerExecutionContextLifetimeManager)
&& (HttpContext.Current != null || OperationContext.Current != null))
|| (BaseUnitOfWork.UnitOfWorkLifetimeManagerType == typeof(PerMessageOrExecutionContextLifetimeManager)
&& (PerMessageContextLifetimeManager.CurrentMessageContext != null
|| HttpContext.Current != null
|| OperationContext.Current != null)))
{
var unitOfWork = (IoCFactory.Resolve<IUnitOfWork>() as UnitOfWork);
unitOfWork.RegisterDbContext(this);
}
}
protected void InitObjectContext()
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
if (objectContext != null)
{
objectContext.ObjectMaterialized +=
(s, e) => this.InitializeQueryableCollections(e.Entity);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Reflection;
using IFramework.Domain;
using IFramework.Infrastructure;
using IFramework.UnitOfWork;
using IFramework.Infrastructure.Unity.LifetimeManagers;
using System.Web;
using System.ServiceModel;
namespace IFramework.EntityFramework
{
public static class QueryableCollectionInitializer
{
public static void InitializeQueryableCollections(this MSDbContext context, object entity)
{
var dbEntity = entity as Entity;
if (dbEntity != null)
{
((dynamic)dbEntity).DomainContext = context;
}
}
}
public class MSDbContext : DbContext
{
public MSDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
InitObjectContext();
if ((BaseUnitOfWork.UnitOfWorkLifetimeManagerType == typeof(PerMessageContextLifetimeManager)
&& PerMessageContextLifetimeManager.CurrentMessageContext != null)
|| (BaseUnitOfWork.UnitOfWorkLifetimeManagerType == typeof(PerExecutionContextLifetimeManager)
&& (HttpContext.Current != null || OperationContext.Current != null)))
{
var unitOfWork = (IoCFactory.Resolve<IUnitOfWork>() as UnitOfWork);
unitOfWork.RegisterDbContext(this);
}
}
protected void InitObjectContext()
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
if (objectContext != null)
{
objectContext.ObjectMaterialized +=
(s, e) => this.InitializeQueryableCollections(e.Entity);
}
}
}
}
| mit | C# |
1cc337974d1bf8e49455f2d79dbf93164d2ad85d | Fix compile failure. | GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | bigquery/data-transfer/api/QuickStart/QuickStart.cs | bigquery/data-transfer/api/QuickStart/QuickStart.cs | /*
* Copyright (c) 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
*
* 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.
*/
// [START bigquerydatatransfer_quickstart]
using System;
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.BigQuery.DataTransfer.V1;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
DataTransferServiceClient client = DataTransferServiceClient.Create();
// Your Google Cloud Platform project ID
string projectId = "YOUR-PROJECT-ID";
ProjectName project = new ProjectName(projectId);
var sources = client.ListDataSources(ParentNameOneof.From(project));
Console.WriteLine("Supported Data Sources:");
foreach (DataSource source in sources)
{
Console.WriteLine(
$"{source.DataSourceId}: " +
$"{source.DisplayName} ({source.Description})");
}
}
}
}
// [END bigquerydatatransfer_quickstart]
| /*
* Copyright (c) 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
*
* 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.
*/
// [START bigquerydatatransfer_quickstart]
using System;
using Google.Api.Gax;
using Google.Cloud.BigQuery.DataTransfer.V1;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
DataTransferServiceClient client = DataTransferServiceClient.Create();
// Your Google Cloud Platform project ID
string projectId = "YOUR-PROJECT-ID";
ProjectName project = new ProjectName(projectId);
var sources = client.ListDataSources(ParentNameOneof.From(project));
Console.WriteLine("Supported Data Sources:");
foreach (DataSource source in sources)
{
Console.WriteLine(
$"{source.DataSourceId}: " +
$"{source.DisplayName} ({source.Description})");
}
}
}
}
// [END bigquerydatatransfer_quickstart]
| apache-2.0 | C# |
da6a75233628f66779705a7d5b083f5ad3f8f939 | fix problem with looking at ps files in root | jsacapdev/dockerfiles,jsacapdev/dockerfiles,Capgemini/dockerfiles,Capgemini/dockerfiles | helpers.cake | helpers.cake | #addin nuget:?package=Cake.Git
#addin nuget:?package=Cake.Powershell
public List<string> GetLastCommitChanges(string checkFile)
{
List<string> cc = new List<string>();
var lastCommit = GitLogTip(".");
Debug("Last commit sha "+ lastCommit.Sha);
var gitDiffFiles = GitDiff(".", lastCommit.Sha);
foreach(var gitDiffFile in gitDiffFiles)
{
Debug("Following file has changed -> {0}", gitDiffFile);
bool isDirectory = !string.IsNullOrWhiteSpace(System.IO.Path.GetDirectoryName(gitDiffFile.Path));
if (gitDiffFile.Path.EndsWith(checkFile) && isDirectory)
{
cc.Add(gitDiffFile.Path);
}
}
return cc;
}
public void ExecuteScript(string scripto)
{
Information("Starting to execute file -> {0}", scripto);
var resultCollection = StartPowershellFile(scripto);
var returnCode = int.Parse(resultCollection[0].BaseObject.ToString());
Information("Result -> {0}", returnCode);
} | #addin nuget:?package=Cake.Git
#addin nuget:?package=Cake.Powershell
public List<string> GetLastCommitChanges(string checkFile)
{
List<string> cc = new List<string>();
var lastCommit = GitLogTip(".");
Debug("Last commit sha "+ lastCommit.Sha);
var gitDiffFiles = GitDiff(".", lastCommit.Sha);
foreach(var gitDiffFile in gitDiffFiles)
{
Debug("Following file has changed:" + gitDiffFile);
if (gitDiffFile.Path.EndsWith(checkFile))
{
cc.Add(gitDiffFile.Path);
}
}
return cc;
}
public void ExecuteScript(string scripto)
{
Information("Starting to execute file -> {0}", scripto);
var resultCollection = StartPowershellFile(scripto);
var returnCode = int.Parse(resultCollection[0].BaseObject.ToString());
Information("Result -> {0}", returnCode);
} | mit | C# |
c25c9d8e868ce73b22ff34a4b5097bba995d92fe | Make sure dotnet exit if crashing during Run (see https://github.com/aspnet/Hosting/issues/1194) | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer/Program.cs | NBXplorer/Program.cs | using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using NBXplorer.Configuration;
using NBXplorer.Logging;
using NBitcoin.Protocol;
using System.Collections;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore;
using NBitcoin;
using System.Text;
using System.Net;
using CommandLine;
namespace NBXplorer
{
public class Program
{
public static void Main(string[] args)
{
var processor = new ConsoleLoggerProcessor();
Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false, processor)));
IWebHost host = null;
try
{
var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args);
if(conf == null)
return;
ConfigurationBuilder builder = new ConfigurationBuilder();
host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseConfiguration(conf)
.UseApplicationInsights()
.ConfigureLogging(l =>
{
l.AddFilter("Microsoft", LogLevel.Error);
if(conf.GetOrDefault<bool>("verbose", false))
{
l.SetMinimumLevel(LogLevel.Debug);
}
l.AddProvider(new CustomConsoleLogProvider(processor));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Configuration.LogError(ex.Message);
}
catch(CommandParsingException parsing)
{
Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message);
}
finally
{
processor.Dispose();
if(host != null)
host.Dispose();
}
}
}
}
| using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using NBXplorer.Configuration;
using NBXplorer.Logging;
using NBitcoin.Protocol;
using System.Collections;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore;
using NBitcoin;
using System.Text;
using System.Net;
using CommandLine;
namespace NBXplorer
{
public class Program
{
public static void Main(string[] args)
{
var processor = new ConsoleLoggerProcessor();
Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false, processor)));
IWebHost host = null;
try
{
var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args);
if(conf == null)
return;
ConfigurationBuilder builder = new ConfigurationBuilder();
host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseConfiguration(conf)
.UseApplicationInsights()
.ConfigureLogging(l =>
{
l.AddFilter("Microsoft", LogLevel.Error);
if(conf.GetOrDefault<bool>("verbose", false))
{
l.SetMinimumLevel(LogLevel.Debug);
}
l.AddProvider(new CustomConsoleLogProvider(processor));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Configuration.LogError(ex.Message);
}
catch(CommandParsingException parsing)
{
Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message);
}
catch(Exception exception)
{
Logs.Explorer.LogError("Exception thrown while running the server");
Logs.Explorer.LogError(exception.ToString());
}
finally
{
processor.Dispose();
if(host != null)
host.Dispose();
}
}
}
}
| mit | C# |
032b7cc9b3cc0c1e01ee60235ca1878ec9d039d8 | Fix recursion with Random.Range float function Thanks @zakharovg | Nogrod/Oxide-2,bawNg/Oxide,LaserHydra/Oxide,Visagalis/Oxide,MSylvia/Oxide,Nogrod/Oxide-2,LaserHydra/Oxide,bawNg/Oxide,MSylvia/Oxide,Visagalis/Oxide | Oxide.Core/Random.cs | Oxide.Core/Random.cs | namespace Oxide.Core
{
public static class Random
{
private static System.Random random;
static Random()
{
random = new System.Random();
}
/// <summary>
/// Returns a random integer which is bigger than or equal to min and smaller than max. If max equals min, min will be returned.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static int Range(int min, int max)
{
return random.Next(min, max);
}
/// <summary>
/// Returns a random integer which is bigger than or equal to 0 and smaller than max.
/// </summary>
/// <param name="max"></param>
public static int Range(int max)
{
float one = Range(0f, 1f);
return random.Next(max);
}
/// <summary>
/// Returns a random double between min and max.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static double Range(double min, double max)
{
return min + (random.NextDouble() * (max - min));
}
/// <summary>
/// Returns a random float between min and max.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static float Range(float min, float max)
{
return (float)Range((double)min, (double)max);
}
}
}
| namespace Oxide.Core
{
public static class Random
{
private static System.Random random;
static Random()
{
random = new System.Random();
}
/// <summary>
/// Returns a random integer which is bigger than or equal to min and smaller than max. If max equals min, min will be returned.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static int Range(int min, int max)
{
return random.Next(min, max);
}
/// <summary>
/// Returns a random integer which is bigger than or equal to 0 and smaller than max.
/// </summary>
/// <param name="max"></param>
public static int Range(int max)
{
float one = Range(0f, 1f);
return random.Next(max);
}
/// <summary>
/// Returns a random double between min and max.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static double Range(double min, double max)
{
return min + (random.NextDouble() * (max - min));
}
/// <summary>
/// Returns a random float between min and max.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public static float Range(float min, float max)
{
return (float)Range(min, max);
}
}
}
| mit | C# |
81a09886420741c37f28a173ef10e6af813ddeba | Remove duplicate Percent unit. | BrandonLWhite/UnitsNet,Tirael/UnitsNet,neutmute/UnitsNet,BrandonLWhite/UnitsNet,maherkassim/UnitsNet,anjdreas/UnitsNet,BoGrevyDynatest/UnitsNet,anjdreas/UnitsNet,maherkassim/UnitsNet | Src/UnitsNet/Unit.cs | Src/UnitsNet/Unit.cs | // Copyright © 2007 by Initial Force AS. All rights reserved.
// https://github.com/InitialForce/SIUnits
//
// 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 UnitsNet.Attributes;
namespace UnitsNet
{
public enum OtherUnit
{
[I18n("en-US", "(undefined)")]
[I18n("ru-RU", "(нет ед.изм.)")]
[I18n("nb-NO", "(ingen)")]
Undefined = 0,
// Generic / Other
[I18n("en-US", "piece", "pieces", "pcs", "pcs.", "pc", "pc.", "pce", "pce.")]
[I18n("ru-RU", "штук")]
[I18n("nb-NO", "stk", "stk.", "x")]
Piece,
// Cooking units
// TODO Move to volume?
[I18n("en-US", "Tbsp", "Tbs", "T", "tb", "tbs", "tbsp", "tblsp", "tblspn", "Tbsp.", "Tbs.", "T.", "tb.", "tbs.", "tbsp.", "tblsp.", "tblspn.", "tablespoon", "Tablespoon")]
[I18n("ru-RU", "столовая ложка")]
[I18n("nb-NO", "ss", "ss.", "SS", "SS.")]
Tablespoon,
[I18n("en-US", "tsp","t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon")]
[I18n("ru-RU", "чайная ложка")]
[I18n("nb-NO", "ts", "ts.")]
Teaspoon,
}
} | // Copyright © 2007 by Initial Force AS. All rights reserved.
// https://github.com/InitialForce/SIUnits
//
// 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 UnitsNet.Attributes;
namespace UnitsNet
{
public enum OtherUnit
{
[I18n("en-US", "(undefined)")]
[I18n("ru-RU", "(нет ед.изм.)")]
[I18n("nb-NO", "(ingen)")]
Undefined = 0,
// Generic / Other
[I18n("en-US", "piece", "pieces", "pcs", "pcs.", "pc", "pc.", "pce", "pce.")]
[I18n("ru-RU", "штук")]
[I18n("nb-NO", "stk", "stk.", "x")]
Piece,
[I18n("en-US", "%")]
Percent,
// Cooking units
// TODO Move to volume?
[I18n("en-US", "Tbsp", "Tbs", "T", "tb", "tbs", "tbsp", "tblsp", "tblspn", "Tbsp.", "Tbs.", "T.", "tb.", "tbs.", "tbsp.", "tblsp.", "tblspn.", "tablespoon", "Tablespoon")]
[I18n("ru-RU", "столовая ложка")]
[I18n("nb-NO", "ss", "ss.", "SS", "SS.")]
Tablespoon,
[I18n("en-US", "tsp","t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon")]
[I18n("ru-RU", "чайная ложка")]
[I18n("nb-NO", "ts", "ts.")]
Teaspoon,
}
} | mit | C# |
85ad641c6ff0c1de14130088283d632ea7e19929 | Range and GetEnumValue methods; | KonH/UDBase | Utils/RandomUtils.cs | Utils/RandomUtils.cs | using System;
using System.Collections.Generic;
namespace UDBase.Utils {
public static class RandomUtils {
public static int Range(int min, int max) {
return UnityEngine.Random.Range(min, max);
}
public static T GetItem<T>(List<T> items) {
if( (items != null) && (items.Count > 0) ) {
return items[Range(0, items.Count)];
}
return default(T);
}
public static T GetItem<T>(IEnumerable<T> items) {
if( items != null ) {
var list = new List<T>(items);
return GetItem(list);
}
return default(T);
}
public static T GetEnumValue<T>() {
var values = Enum.GetValues(typeof(T));
var index = Range(0, values.Length);
return (T)values.GetValue(index);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UDBase.Utils {
public static class RandomUtils {
public static T GetItem<T>(List<T> items) {
if( (items != null) && (items.Count > 0) ) {
return items[Random.Range(0, items.Count)];
}
return default(T);
}
public static T GetItem<T>(IEnumerable<T> items) {
if( items != null ) {
var list = new List<T>(items);
return GetItem(list);
}
return default(T);
}
}
}
| mit | C# |
1b5ab459c1f55d9e4d8e7a16f929beefa8b5752a | make the Stop-button work again. | mcneel/RhinoCycles | RenderPipeline.cs | RenderPipeline.cs | /**
Copyright 2014-2016 Robert McNeel and Associates
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.Drawing;
using RhinoCyclesCore;
using Rhino;
using Rhino.Render;
using System.Threading;
namespace RhinoCycles
{
/// <summary>
/// For asynchronous renderer this is just the entry point.
///
/// Inherits Rhino.Render.RenderPipeline
/// <seealso cref="Rhino.Render.RenderPipeline"/>
/// </summary>
public class RenderPipeline : Rhino.Render.RenderPipeline
{
private bool m_bStopFlag;
/// <summary>
/// Context that contains the actual renderer instance
/// </summary>
readonly private RenderEngine cyclesEngine;
public RenderPipeline(RhinoDoc doc, Rhino.Commands.RunMode mode, Rhino.PlugIns.RenderPlugIn plugin, ref AsyncRenderContext aRC)
: base(doc, mode, plugin, RenderSize(doc),
"RhinoCycles", Rhino.Render.RenderWindow.StandardChannels.RGBA, false, false) //, ref aRC)
{
cyclesEngine = (RenderEngine)aRC;
}
public bool Cancel()
{
return m_bStopFlag;
}
protected override bool OnRenderBegin()
{
m_bStopFlag = false;
cyclesEngine.RenderThread = new Thread(ModalRenderEngine.Renderer)
{
Name = "A cool Cycles rendering thread"
};
cyclesEngine.RenderThread.Start(cyclesEngine);
return true;
}
protected override bool OnRenderBeginQuiet(Size imageSize)
{
return OnRenderBegin();
}
protected override void OnRenderEnd(RenderEndEventArgs e)
{
cyclesEngine.StopRendering();
}
protected override bool ContinueModal()
{
return !cyclesEngine.CancelRender;
}
protected override bool OnRenderWindowBegin(Rhino.Display.RhinoView view, System.Drawing.Rectangle rect) { return false; }
}
}
| /**
Copyright 2014-2016 Robert McNeel and Associates
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.Drawing;
using RhinoCyclesCore;
using Rhino;
using Rhino.Render;
using System.Threading;
namespace RhinoCycles
{
/// <summary>
/// For asynchronous renderer this is just the entry point.
///
/// Inherits Rhino.Render.RenderPipeline
/// <seealso cref="Rhino.Render.RenderPipeline"/>
/// </summary>
public class RenderPipeline : Rhino.Render.RenderPipeline
{
private bool m_bStopFlag;
/// <summary>
/// Context that contains the actual renderer instance
/// </summary>
readonly private RenderEngine cyclesEngine;
public RenderPipeline(RhinoDoc doc, Rhino.Commands.RunMode mode, Rhino.PlugIns.RenderPlugIn plugin, ref AsyncRenderContext aRC)
: base(doc, mode, plugin, RenderSize(doc),
"RhinoCycles", Rhino.Render.RenderWindow.StandardChannels.RGBA, false, false) //, ref aRC)
{
cyclesEngine = (RenderEngine)aRC;
}
public bool Cancel()
{
return m_bStopFlag;
}
protected override bool OnRenderBegin()
{
m_bStopFlag = false;
cyclesEngine.RenderThread = new Thread(ModalRenderEngine.Renderer)
{
Name = "A cool Cycles rendering thread"
};
cyclesEngine.RenderThread.Start(cyclesEngine);
return true;
}
protected override bool OnRenderBeginQuiet(Size imageSize)
{
return OnRenderBegin();
}
protected override void OnRenderEnd(RenderEndEventArgs e)
{
// unused
}
protected override bool ContinueModal()
{
return !cyclesEngine.CancelRender;
}
protected override bool OnRenderWindowBegin(Rhino.Display.RhinoView view, System.Drawing.Rectangle rect) { return false; }
}
}
| apache-2.0 | C# |
4b0904c1ccefe5b9a079dd48a722909c1ee6a9b2 | Apply image rescaling to generated deck | ChangSpivey/SubtitleMemorize | WorkerSnapshot.cs | WorkerSnapshot.cs | // Copyright (C) 2016 Chang Spivey
//
// 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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
using System;
using System.Collections.Generic;
using System.IO;
namespace subtitleMemorize
{
public static class WorkerSnapshot
{
public static List<String> ExtractSnaphots(Settings settings, String path, List<CardInfo> allEntries) {
List<String> snapshotFieldValues = new List<string>(allEntries.Count);
for(int i = 0; i < allEntries.Count; i++) {
CardInfo CardInfo = allEntries[i];
// create file at given path
String outputSnapshotFilename = CardInfo.GetKey () + ".jpg";
String outputSnapshotFilepath = path + Path.DirectorySeparatorChar + outputSnapshotFilename;
// value that will be imported into Anki/SRS-Programs-Field
// TODO: make this flexible
snapshotFieldValues.Add("<img src=\"" + outputSnapshotFilename + "\"/>");
// get file with snapshot information -> video
UtilsInputFiles.FileDesc videoFileDesc = CardInfo.episodeInfo.VideoFileDesc;
// extract image
double scaling = UtilsVideo.GetMaxScalingByStreamInfo(CardInfo.episodeInfo.VideoStreamInfo, settings.RescaleWidth, settings.RescaleHeight, settings.RescaleMode);
double timeStamp = UtilsCommon.GetMiddleTime (CardInfo);
UtilsImage.GetImage (videoFileDesc.filename, timeStamp, outputSnapshotFilepath, scaling);
}
return snapshotFieldValues;
}
}
}
| // Copyright (C) 2016 Chang Spivey
//
// 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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
using System;
using System.Collections.Generic;
using System.IO;
namespace subtitleMemorize
{
public static class WorkerSnapshot
{
public static List<String> ExtractSnaphots(Settings settings, String path, List<CardInfo> allEntries) {
List<String> snapshotFieldValues = new List<string>(allEntries.Count);
for(int i = 0; i < allEntries.Count; i++) {
CardInfo CardInfo = allEntries[i];
// create file at given path
String outputSnapshotFilename = CardInfo.GetKey () + ".jpg";
String outputSnapshotFilepath = path + Path.DirectorySeparatorChar + outputSnapshotFilename;
// value that will be imported into Anki/SRS-Programs-Field
// TODO: make this flexible
snapshotFieldValues.Add("<img src=\"" + outputSnapshotFilename + "\"/>");
// get file with snapshot information -> video
UtilsInputFiles.FileDesc videoFileDesc = CardInfo.episodeInfo.VideoFileDesc;
// extract image
double timeStamp = UtilsCommon.GetMiddleTime (CardInfo);
UtilsImage.GetImage (videoFileDesc.filename, timeStamp, outputSnapshotFilepath, 1);
}
return snapshotFieldValues;
}
}
}
| agpl-3.0 | C# |
3b688c702c5cfd82b4c1e0a5b968d0aac844113e | Use graying rather than alpha | NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,naoey/osu,DrabWeb/osu,naoey/osu,peppy/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu-new,ZLima12/osu,2yangk23/osu,DrabWeb/osu,ppy/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,naoey/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu | osu.Game/Screens/Multi/Components/DisableableTabControl.cs | osu.Game/Screens/Multi/Components/DisableableTabControl.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osuTK.Graphics;
namespace osu.Game.Screens.Multi.Components
{
public abstract class DisableableTabControl<T> : TabControl<T>
{
public readonly BindableBool ReadOnly = new BindableBool();
protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true)
{
if (tab is DisableableTabItem<T> disableable)
disableable.ReadOnly.BindTo(ReadOnly);
base.AddTabItem(tab, addToDropdown);
}
protected abstract class DisableableTabItem<T> : TabItem<T>
{
public readonly BindableBool ReadOnly = new BindableBool();
protected DisableableTabItem(T value)
: base(value)
{
ReadOnly.BindValueChanged(updateReadOnly);
}
private void updateReadOnly(bool readOnly)
{
Colour = readOnly ? Color4.Gray : Color4.White;
}
protected override bool OnClick(ClickEvent e)
{
if (ReadOnly)
return true;
return base.OnClick(e);
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
namespace osu.Game.Screens.Multi.Components
{
public abstract class DisableableTabControl<T> : TabControl<T>
{
public readonly BindableBool ReadOnly = new BindableBool();
protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true)
{
if (tab is DisableableTabItem<T> disableable)
disableable.ReadOnly.BindTo(ReadOnly);
base.AddTabItem(tab, addToDropdown);
}
protected abstract class DisableableTabItem<T> : TabItem<T>
{
public readonly BindableBool ReadOnly = new BindableBool();
protected DisableableTabItem(T value)
: base(value)
{
ReadOnly.BindValueChanged(updateReadOnly);
}
private void updateReadOnly(bool readOnly)
{
Alpha = readOnly ? 0.2f : 1;
}
protected override bool OnClick(ClickEvent e)
{
if (ReadOnly)
return true;
return base.OnClick(e);
}
}
}
}
| mit | C# |
7c54e0f807837c77456cdb368feb737554bb9b0a | Fix crashing on Xamarin Designer | molinch/FFImageLoading,AndreiMisiukevich/FFImageLoading,daniel-luberda/FFImageLoading,luberda-molinet/FFImageLoading | source/FFImageLoading.Droid/Helpers/PlatformPerformance.cs | source/FFImageLoading.Droid/Helpers/PlatformPerformance.cs | using System;
using System.Threading;
using Android.App;
using Java.Lang;
namespace FFImageLoading
{
public class PlatformPerformance : IPlatformPerformance
{
Runtime _runtime;
ActivityManager _activityManager;
ActivityManager.MemoryInfo _memoryInfo;
public static IPlatformPerformance Create()
{
if (Application.Context == null)
return new EmptyPlatformPerformance();
return new PlatformPerformance();
}
private PlatformPerformance()
{
_runtime = Runtime.GetRuntime();
_activityManager = (ActivityManager)Application.Context.GetSystemService("activity");
_memoryInfo = new ActivityManager.MemoryInfo();
}
public int GetCurrentManagedThreadId()
{
return System.Threading.Thread.CurrentThread.ManagedThreadId;
}
public int GetCurrentSystemThreadId()
{
return Android.OS.Process.MyTid();
}
public string GetMemoryInfo()
{
_activityManager.GetMemoryInfo(_memoryInfo);
double availableMegs = (double)_memoryInfo.AvailMem / 1048576d;
double totalMegs = (double)_memoryInfo.TotalMem / 1048576d;
double percentAvail = (double)_memoryInfo.AvailMem / _memoryInfo.TotalMem * 100d;
double availableMegsHeap = ((double)(_runtime.TotalMemory() - _runtime.FreeMemory())) / 1048576d;
double totalMegsHeap = (double)_runtime.MaxMemory() / 1048576d;
double percentAvailHeap = (double)(_runtime.TotalMemory() - _runtime.FreeMemory()) / _runtime.MaxMemory() * 100d;
return string.Format("[PERFORMANCE] Memory - Free: {0:0}MB ({1:0}%), Total: {2:0}MB, Heap - Free: {3:0}MB ({4:0}%), Total: {5:0}MB",
availableMegs, percentAvail, totalMegs, availableMegsHeap, percentAvailHeap, totalMegsHeap);
}
class EmptyPlatformPerformance : IPlatformPerformance
{
public int GetCurrentManagedThreadId()
{
return 0;
}
public int GetCurrentSystemThreadId()
{
return 0;
}
public string GetMemoryInfo()
{
return "";
}
}
}
}
| using System;
using System.Threading;
using Android.App;
using Java.Lang;
namespace FFImageLoading
{
public class PlatformPerformance : IPlatformPerformance
{
Runtime _runtime;
ActivityManager _activityManager;
ActivityManager.MemoryInfo _memoryInfo;
public PlatformPerformance()
{
_runtime = Runtime.GetRuntime();
_activityManager = (ActivityManager)Application.Context.GetSystemService("activity");
_memoryInfo = new ActivityManager.MemoryInfo();
}
public int GetCurrentManagedThreadId()
{
return System.Threading.Thread.CurrentThread.ManagedThreadId;
}
public int GetCurrentSystemThreadId()
{
return Android.OS.Process.MyTid();
}
public string GetMemoryInfo()
{
_activityManager.GetMemoryInfo(_memoryInfo);
double availableMegs = (double)_memoryInfo.AvailMem / 1048576d;
double totalMegs = (double)_memoryInfo.TotalMem / 1048576d;
double percentAvail = (double)_memoryInfo.AvailMem / _memoryInfo.TotalMem * 100d;
double availableMegsHeap = ((double)(_runtime.TotalMemory() - _runtime.FreeMemory())) / 1048576d;
double totalMegsHeap = (double)_runtime.MaxMemory() / 1048576d;
double percentAvailHeap = (double)(_runtime.TotalMemory() - _runtime.FreeMemory()) / _runtime.MaxMemory() * 100d;
return string.Format("[PERFORMANCE] Memory - Free: {0:0}MB ({1:0}%), Total: {2:0}MB, Heap - Free: {3:0}MB ({4:0}%), Total: {5:0}MB",
availableMegs, percentAvail, totalMegs, availableMegsHeap, percentAvailHeap, totalMegsHeap);
}
}
}
| mit | C# |
574ac538ca8bcade36a10b093230eba08f8376e8 | change ctor param name in RequireRoleAttribute | timba/NServiceKit,NServiceKit/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,NServiceKit/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,ZocDoc/ServiceStack,meebey/ServiceStack,MindTouch/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,meebey/ServiceStack,MindTouch/NServiceKit | src/ServiceStack.ServiceInterface/RequiredRoleAttribute.cs | src/ServiceStack.ServiceInterface/RequiredRoleAttribute.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Indicates that the request dto, which is associated with this attribute,
/// can only execute, if the user has specific roles.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class RequiredRoleAttribute : RequestFilterAttribute
{
public List<string> RequiredRoles { get; set; }
public RequiredRoleAttribute(params string[] roles)
{
this.RequiredRoles = roles.ToList();
this.ApplyTo = ApplyTo.All;
}
public RequiredRoleAttribute(ApplyTo applyTo, params string[] roles)
{
this.RequiredRoles = roles.ToList();
this.ApplyTo = applyTo;
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var session = req.GetSession();
if (HasAllRoles(session)) return;
var userAuthRepo = req.TryResolve<IUserAuthRepository>();
var userAuth = userAuthRepo.GetUserAuth(session, null);
session.UpdateSession(userAuth);
if (HasAllRoles(session))
{
req.SaveSession(session);
return;
}
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.StatusDescription = "Invalid Role";
res.Close();
}
private bool HasAllRoles(IAuthSession session)
{
return this.RequiredRoles
.All(requiredRole => session != null
&& session.HasRole(requiredRole));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Indicates that the request dto, which is associated with this attribute,
/// can only execute, if the user has specific roles.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class RequiredRoleAttribute : RequestFilterAttribute
{
public List<string> RequiredRoles { get; set; }
public RequiredRoleAttribute(params string[] roles)
{
this.RequiredRoles = roles.ToList();
this.ApplyTo = ApplyTo.All;
}
public RequiredRoleAttribute(ApplyTo applyTo, params string[] permissions)
{
this.RequiredRoles = permissions.ToList();
this.ApplyTo = applyTo;
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var session = req.GetSession();
if (HasAllRoles(session)) return;
var userAuthRepo = req.TryResolve<IUserAuthRepository>();
var userAuth = userAuthRepo.GetUserAuth(session, null);
session.UpdateSession(userAuth);
if (HasAllRoles(session))
{
req.SaveSession(session);
return;
}
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.StatusDescription = "Invalid Role";
res.Close();
}
private bool HasAllRoles(IAuthSession session)
{
return this.RequiredRoles
.All(requiredRole => session != null
&& session.HasRole(requiredRole));
}
}
}
| bsd-3-clause | C# |
c996c4ff9a270663932767afd6293248a323f629 | Reformat code for consistency | mysticfall/Alensia | Assets/Alensia/Core/Game/Game.cs | Assets/Alensia/Core/Game/Game.cs | using System;
using Alensia.Core.Common;
using UniRx;
using UnityEngine;
using Zenject;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Alensia.Core.Game
{
public class Game : BaseObject, IGame
{
public float TimeScale
{
get { return _timeScale.Value; }
set { _timeScale.Value = value; }
}
public bool Paused => _paused.Value;
public UniRx.IObservable<float> OnTimeScaleChange => _timeScale;
public UniRx.IObservable<bool> OnPauseStateChange => _paused;
public UniRx.IObservable<Unit> OnPause =>
OnPauseStateChange.Where(s => s).AsSingleUnitObservable();
public UniRx.IObservable<Unit> OnResume =>
OnPauseStateChange.Where(s => !s).AsSingleUnitObservable();
private readonly IReactiveProperty<float> _timeScale;
private readonly IReactiveProperty<bool> _paused;
public Game([InjectOptional] Settings settings)
{
settings = settings ?? new Settings();
Time.timeScale = settings.TimeScale;
_timeScale = new ReactiveProperty<float>(Time.timeScale);
_paused = new ReactiveProperty<bool>();
_timeScale
.Where(_ => !Paused)
.Subscribe(scale => Time.timeScale = scale)
.AddTo(this);
_paused
.Select(v => v ? 0 : settings.TimeScale)
.Subscribe(scale => Time.timeScale = scale)
.AddTo(this);
}
public void Pause() => _paused.Value = true;
public void Resume() => _paused.Value = false;
public void Quit()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
[Serializable]
public class Settings : IEditorSettings
{
public float TimeScale = 1;
}
} | using System;
using Alensia.Core.Common;
using UniRx;
using UnityEngine;
using Zenject;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Alensia.Core.Game
{
public class Game : BaseObject, IGame
{
public float TimeScale
{
get { return _timeScale.Value; }
set { _timeScale.Value = value; }
}
public bool Paused => _paused.Value;
public UniRx.IObservable<float> OnTimeScaleChange => _timeScale;
public UniRx.IObservable<bool> OnPauseStateChange => _paused;
public UniRx.IObservable<Unit> OnPause =>
OnPauseStateChange.Where(s => s).AsSingleUnitObservable();
public UniRx.IObservable<Unit> OnResume =>
OnPauseStateChange.Where(s => !s).AsSingleUnitObservable();
private readonly IReactiveProperty<float> _timeScale;
private readonly IReactiveProperty<bool> _paused;
public Game([InjectOptional] Settings settings)
{
settings = settings ?? new Settings();
Time.timeScale = settings.TimeScale;
_timeScale = new ReactiveProperty<float>(Time.timeScale);
_paused = new ReactiveProperty<bool>();
_timeScale
.Where(_ => !Paused)
.Subscribe(scale => Time.timeScale = scale).AddTo(this);
_paused
.Select(v => v ? 0 : settings.TimeScale)
.Subscribe(scale => Time.timeScale = scale)
.AddTo(this);
}
public void Pause() => _paused.Value = true;
public void Resume() => _paused.Value = false;
public void Quit()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
[Serializable]
public class Settings : IEditorSettings
{
public float TimeScale = 1;
}
} | apache-2.0 | C# |
e456828f656dd7078550f6d6ece140f397d3ed2d | Use OpenTK triangle sample in OpenTkApp project | PhilboBaggins/ci-experiments-dotnetcore,PhilboBaggins/ci-experiments-dotnetcore | OpenTkApp/Program.cs | OpenTkApp/Program.cs | using System;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace OpenTkApp
{
class Game : GameWindow
{
public Game()
: base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample")
{
VSync = VSyncMode.On;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
GL.Enable(EnableCap.DepthTest);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height);
Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref projection);
}
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
if (Keyboard[Key.Escape])
Exit();
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref modelview);
GL.Begin(BeginMode.Triangles);
GL.Color3(1.0f, 1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 4.0f);
GL.Color3(1.0f, 0.0f, 0.0f); GL.Vertex3(1.0f, -1.0f, 4.0f);
GL.Color3(0.2f, 0.9f, 1.0f); GL.Vertex3(0.0f, 1.0f, 4.0f);
GL.End();
SwapBuffers();
}
}
class Program
{
[STAThread]
static void Main(string[] args)
{
using (Game game = new Game())
{
game.Run(30.0);
}
}
}
}
| using System;
namespace OpenTkApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| unlicense | C# |
5b5d84f6affa30873d282afd196fc334ed050828 | fix crash when reopening a window closed by alt+tab or win+tab | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Windows/TccWindow.cs | TCC.Core/Windows/TccWindow.cs | using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace TCC.Windows
{
public class TccWindow : Window
{
public event Action Hidden;
public event Action Showed;
public TccWindow()
{
Closing += OnClosing;
}
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
HideWindow();
}
public void HideWindow()
{
var a = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(150));
a.Completed += (s, ev) =>
{
Hide();
if (Settings.SettingsHolder.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
Hidden?.Invoke();
};
BeginAnimation(OpacityProperty, a);
}
public void ShowWindow()
{
if (Settings.SettingsHolder.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.Default;
Dispatcher.Invoke(() =>
{
Topmost = false; Topmost = true;
Opacity = 0;
Show();
Showed?.Invoke();
BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)));
});
}
}
} | using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace TCC.Windows
{
public class TccWindow : Window
{
public event Action Hidden;
public event Action Showed;
public void HideWindow()
{
var a = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(150));
a.Completed += (s, ev) =>
{
Hide();
if (Settings.SettingsHolder.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
Hidden?.Invoke();
};
BeginAnimation(OpacityProperty, a);
}
public void ShowWindow()
{
if (Settings.SettingsHolder.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.Default;
Dispatcher.Invoke(() =>
{
Topmost = false; Topmost = true;
Opacity = 0;
Show();
Showed?.Invoke();
BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)));
});
}
}
} | mit | C# |
27d96a08c1ef25a9a27f3571e280d22bdd89d18a | Mark WinApiNet assembly as not CLS-compliant | MpDzik/winapinet,MpDzik/winapinet | src/WinApiNet/Properties/AssemblyInfo.cs | src/WinApiNet/Properties/AssemblyInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
// Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinApiNet")]
[assembly: AssemblyDescription("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]
// Assembly is not CLS-compliant
[assembly: CLSCompliant(false)] | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
// Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinApiNet")]
[assembly: AssemblyDescription("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]
// Assembly is CLS-compliant
[assembly: CLSCompliant(true)] | mit | C# |
3aa97beb96f9bf8eca8839403fc3b680c088fadb | Update ActivatorEx to consider private constructors and look for constructor using appropriate order | atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata | src/Atata/ActivatorEx.cs | src/Atata/ActivatorEx.cs | using System;
using System.Linq;
using System.Reflection;
namespace Atata
{
internal static class ActivatorEx
{
internal static T CreateInstance<T>(string typeName)
{
typeName.CheckNotNullOrEmpty(nameof(typeName));
Type type = Type.GetType(typeName, true);
return CreateInstance<T>(type);
}
internal static T CreateInstance<T>(Type type = null)
{
return (T)CreateInstance(type ?? typeof(T));
}
internal static object CreateInstance(Type type)
{
var constructorData = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).
Select(x => new { Constructor = x, Parameters = x.GetParameters() }).
OrderByDescending(x => x.Constructor.IsPublic).
ThenBy(x => x.Parameters.Length).
FirstOrDefault(x => !x.Parameters.Any() || x.Parameters.All(param => param.IsOptional || param.GetCustomAttributes(true).Any(attr => attr is ParamArrayAttribute)));
if (constructorData == null)
throw new MissingMethodException($"No parameterless constructor or constructor without non-optional parameters defined for the {type.FullName} type.");
object[] parameters = constructorData.Parameters.Select(x => x.IsOptional ? x.DefaultValue : null).ToArray();
return constructorData.Constructor.Invoke(parameters);
}
}
}
| using System;
using System.Linq;
namespace Atata
{
internal static class ActivatorEx
{
internal static T CreateInstance<T>(string typeName)
{
typeName.CheckNotNullOrEmpty(nameof(typeName));
Type type = Type.GetType(typeName, true);
return CreateInstance<T>(type);
}
internal static T CreateInstance<T>(Type type = null)
{
return (T)CreateInstance(type ?? typeof(T));
}
internal static object CreateInstance(Type type)
{
var constructorData = type.GetConstructors().
Select(x => new { Constructor = x, Parameters = x.GetParameters() }).
FirstOrDefault(x =>
{
return !x.Parameters.Any() || x.Parameters.All(param => param.IsOptional || param.GetCustomAttributes(true).Any(attr => attr is ParamArrayAttribute));
});
if (constructorData == null)
throw new MissingMethodException("No parameterless constructor or constructor without non-optional parameters defined for the {0} type.".FormatWith(type.FullName));
object[] parameters = constructorData.Parameters.Select(x => x.IsOptional ? x.DefaultValue : null).ToArray();
return constructorData.Constructor.Invoke(parameters);
}
}
}
| apache-2.0 | C# |
692b923ca61924880a63bff44f7536cf4db4c72e | fix public | NCTUGDC/HearthStone | HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs | HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
public class CardManagerUnitTest
{
[TestMethod]
public void CardManagerInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance);
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards);
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card);
Assert.IsFalse(IDs.Contains(card.CardID));
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects);
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect);
Assert.IsFalse(IDs.Contains(effect.EffectID));
IDs.Add(effect.EffectID);
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
class CardManagerUnitTest
{
[TestMethod]
public void CardManagerInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance);
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards);
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card);
Assert.IsFalse(IDs.Contains(card.CardID));
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects);
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect);
Assert.IsFalse(IDs.Contains(effect.EffectID));
IDs.Add(effect.EffectID);
}
}
}
}
| apache-2.0 | C# |
015a558ab590e78439dc1736c08bf2193a9237e8 | change assembly version | nabehiro/HttpAuthModule,nabehiro/HttpAuthModule | HttpAuthModule/Properties/AssemblyInfo.cs | HttpAuthModule/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("HttpAuthModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HttpAuthModule")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("a229e6bd-81cd-489c-9c4c-0e090e0f8c40")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("HttpAuthModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HttpAuthModule")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("a229e6bd-81cd-489c-9c4c-0e090e0f8c40")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
ff70baff755b1180d25ef09539237265b925f910 | fix null exception in presenter | zoon/nunit-unity3d,zoon/nunit-unity3d | Assets/Plugins/NUnitLite/NUnitLiteUnityRunner.cs | Assets/Plugins/NUnitLite/NUnitLiteUnityRunner.cs | // Copyright (C) 2013 by Andrew Zhilin <andrew_zhilin@yahoo.com>
#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NUnitLite;
using NUnitLite.Runner;
using UnityEngine;
#endregion
/* NOTE:
*
* This is a test runner for NUnitLite, that redirects test results
* to Unity console.
*
* After compilation of C# files Unity gives you two assemblies:
*
* - Assembly-CSharp-firstpass.dll for 'Plugins' and 'Standard Assets'
* - Assembly-CSharp.dll for another scripts
*
* Then, if you want have tests in both places - you should call
* NUnitLiteUnityRunner.RunTests() from both places. One call per assembly
* is enough, but you can call it as many times as you want - all
* calls after first are ignored.
*
* You can use 'MonoBahavior' classes for tests, but Unity give you
* one harmless warning per class. Using special Test classes would be
* better idea.
*/
public static class NUnitLiteUnityRunner
{
private static readonly HashSet<Assembly> Tested =
new HashSet<Assembly>();
public static Action<string, ResultSummary> Presenter { get; set; }
static NUnitLiteUnityRunner()
{
Presenter = UnityConsolePresenter;
}
public static void RunTests()
{
RunTests(Assembly.GetCallingAssembly());
}
private static void RunTests(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (Tested.Contains(assembly))
return;
Tested.Add(assembly);
using (var sw = new StringWriter())
{
var runner = new NUnitStreamUI(sw);
runner.Execute(assembly);
var resultSummary = runner.Summary;
var resultText = sw.GetStringBuilder().ToString();
Presenter(resultText, resultSummary);
}
}
private static void UnityConsolePresenter(string longResult, ResultSummary result)
{
if (result != null && (result.ErrorCount > 0 || result.FailureCount > 0))
Debug.LogWarning(longResult);
else
Debug.Log(longResult);
}
}
| // Copyright (C) 2013 by Andrew Zhilin <andrew_zhilin@yahoo.com>
#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NUnitLite;
using NUnitLite.Runner;
using UnityEngine;
#endregion
/* NOTE:
*
* This is a test runner for NUnitLite, that redirects test results
* to Unity console.
*
* After compilation of C# files Unity gives you two assemblies:
*
* - Assembly-CSharp-firstpass.dll for 'Plugins' and 'Standard Assets'
* - Assembly-CSharp.dll for another scripts
*
* Then, if you want have tests in both places - you should call
* NUnitLiteUnityRunner.RunTests() from both places. One call per assembly
* is enough, but you can call it as many times as you want - all
* calls after first are ignored.
*
* You can use 'MonoBahavior' classes for tests, but Unity give you
* one harmless warning per class. Using special Test classes would be
* better idea.
*/
public static class NUnitLiteUnityRunner
{
private static readonly HashSet<Assembly> Tested =
new HashSet<Assembly>();
public static Action<string, ResultSummary> Presenter { get; set; }
static NUnitLiteUnityRunner()
{
Presenter = UnityConsolePresenter;
}
public static void RunTests()
{
RunTests(Assembly.GetCallingAssembly());
}
private static void RunTests(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (Tested.Contains(assembly))
return;
Tested.Add(assembly);
using (var sw = new StringWriter())
{
var runner = new NUnitStreamUI(sw);
runner.Execute(assembly);
var resultSummary = runner.Summary;
var resultText = sw.GetStringBuilder().ToString();
Presenter(resultText, resultSummary);
}
}
private static void UnityConsolePresenter(string longResult, ResultSummary result)
{
if (result.ErrorCount > 0 || result.FailureCount > 0)
Debug.LogWarning(longResult);
else
Debug.Log(longResult);
}
}
| mit | C# |
2c1ee00feae1c4db4d05f57747cd84031a17bd4b | Add ABCP/APFT Button | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Soldiers/List.cshtml | Battery-Commander.Web/Views/Soldiers/List.cshtml | @model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id })
</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
</tr>
}
</tbody>
</table> | mit | C# |
3fd9810e5bfd1af143f0ff5d13b532695ee5dda4 | Update ErrorCheckingOptions.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/ErrorCheckingOptions.cs | Examples/CSharp/Articles/ErrorCheckingOptions.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class ErrorCheckingOptions
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create a workbook and opening a template spreadsheet
Workbook workbook = new Workbook(dataDir+ "Book1.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Instantiate the error checking options
ErrorCheckOptionCollection opts = sheet.ErrorCheckOptions;
int index = opts.Add();
ErrorCheckOption opt = opts[index];
//Disable the numbers stored as text option
opt.SetErrorCheck(ErrorCheckType.TextNumber, false);
//Set the range
opt.AddRange(CellArea.CreateCellArea(0, 0, 1000, 50));
//Save the Excel file
workbook.Save(dataDir+ "out_test.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class ErrorCheckingOptions
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create a workbook and opening a template spreadsheet
Workbook workbook = new Workbook(dataDir+ "Book1.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Instantiate the error checking options
ErrorCheckOptionCollection opts = sheet.ErrorCheckOptions;
int index = opts.Add();
ErrorCheckOption opt = opts[index];
//Disable the numbers stored as text option
opt.SetErrorCheck(ErrorCheckType.TextNumber, false);
//Set the range
opt.AddRange(CellArea.CreateCellArea(0, 0, 1000, 50));
//Save the Excel file
workbook.Save(dataDir+ "out_test.out.xlsx");
}
}
} | mit | C# |
ccf23ad5c5b2330828faf0ac7e1898235568ae13 | Prepare Assert.cs to have proper FrameworkAssert for different testing frameworks. | telerik/JustMockLite | Telerik.JustMock.Tests/Assert.cs | Telerik.JustMock.Tests/Assert.cs | /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
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;
#if NUNIT
using FrameworkAssert = NUnit.Framework.Assert;
#elif XUNIT
#elif PORTABLE
using FrameworkAssert = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.Assert;
#else
using FrameworkAssert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
#endif
namespace Telerik.JustMock.Tests
{
/// <summary>
/// Assertion wrapper that exposes Xunit alike methods.
/// </summary>
public static class Assert
{
public static Exception Throws<T>(Action action) where T : Exception
{
Exception targetException = null;
try
{
action();
}
catch (T ex)
{
// Test pass
return ex;
}
#if PORTABLE
catch (System.Reflection.TargetInvocationException ex)
{
var inner = ex.InnerException;
if (inner is T)
{
return inner;
}
else
{
FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), inner.GetType()));
}
}
#endif
catch (Exception ex)
{
FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), ex.GetType()));
}
FrameworkAssert.Fail(String.Format("No Expected {0} was thrown", typeof(T).FullName));
throw new Exception();
}
public static void NotNull(object value)
{
FrameworkAssert.IsNotNull(value);
}
public static void Null(object value)
{
FrameworkAssert.IsNull(value);
}
public static void Equal<T>(T expected, T actual)
{
FrameworkAssert.AreEqual(expected, actual);
}
public static void NotEqual<T>(T notExpected, T actual)
{
FrameworkAssert.AreNotEqual(notExpected, actual);
}
public static void True(bool condition)
{
FrameworkAssert.IsTrue(condition);
}
public static void False(bool condition)
{
FrameworkAssert.IsFalse(condition);
}
public static void Same(object expected, object actual)
{
FrameworkAssert.AreSame(expected, actual);
}
public static void NotSame(object expected, object actual)
{
FrameworkAssert.AreNotSame(expected, actual);
}
}
}
| /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
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;
#if !NUNIT
#if !PORTABLE
using FrameworkAssert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
#else
using FrameworkAssert = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.Assert;
#endif
#else
using FrameworkAssert = NUnit.Framework.Assert;
#endif
namespace Telerik.JustMock.Tests
{
/// <summary>
/// Assertion wrapper that exposes Xunit alike methods.
/// </summary>
public static class Assert
{
public static Exception Throws<T>(Action action) where T : Exception
{
Exception targetException = null;
try
{
action();
}
catch (T ex)
{
// Test pass
return ex;
}
#if PORTABLE
catch (System.Reflection.TargetInvocationException ex)
{
var inner = ex.InnerException;
if (inner is T)
{
return inner;
}
else
{
FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), inner.GetType()));
}
}
#endif
catch (Exception ex)
{
FrameworkAssert.Fail(String.Format("Wrong exception type thrown. Expected {0}, got {1}.", typeof(T), ex.GetType()));
}
FrameworkAssert.Fail(String.Format("No Expected {0} was thrown", typeof(T).FullName));
throw new Exception();
}
public static void NotNull(object value)
{
FrameworkAssert.IsNotNull(value);
}
public static void Null(object value)
{
FrameworkAssert.IsNull(value);
}
public static void Equal<T>(T expected, T actual)
{
FrameworkAssert.AreEqual(expected, actual);
}
public static void NotEqual<T>(T notExpected, T actual)
{
FrameworkAssert.AreNotEqual(notExpected, actual);
}
public static void True(bool condition)
{
FrameworkAssert.IsTrue(condition);
}
public static void False(bool condition)
{
FrameworkAssert.IsFalse(condition);
}
public static void Same(object expected, object actual)
{
FrameworkAssert.AreSame(expected, actual);
}
public static void NotSame(object expected, object actual)
{
FrameworkAssert.AreNotSame(expected, actual);
}
}
}
| apache-2.0 | C# |
e5feb7ca3ccfe9022fe136141a16768e979b0028 | Fix AppRelativePath. | jammycakes/dolstagis.web,jammycakes/dolstagis.web,jammycakes/dolstagis.web | src/Dolstagis.Web.Aspnet/HttpRequest.cs | src/Dolstagis.Web.Aspnet/HttpRequest.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Dolstagis.Web.Http;
namespace Dolstagis.Web.Aspnet
{
public class HttpRequest : IRequest
{
public HttpRequest(HttpRequestBase innerRequest)
{
this.Url = innerRequest.Unvalidated.Url;
this.Method = innerRequest.HttpMethod;
this.Path = new VirtualPath(Url.AbsolutePath);
this.AppRelativePath = new VirtualPath(innerRequest.ApplicationPath)
.GetAppRelativePath(this.Path, true);
this.Protocol = innerRequest.ServerVariables["SERVER_PROTOCOL"];
this.IsSecure = innerRequest.IsSecureConnection;
this.Query = innerRequest.Unvalidated.QueryString;
this.Form = innerRequest.Unvalidated.Form;
this.Headers = innerRequest.Unvalidated.Headers;
}
public string Method { get; private set; }
public VirtualPath Path { get; private set; }
public VirtualPath AppRelativePath { get; private set; }
public string Protocol { get; private set; }
public bool IsSecure { get; private set; }
public Uri Url { get; private set; }
public NameValueCollection Query { get; private set; }
public NameValueCollection Form { get; private set; }
public NameValueCollection Headers { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Dolstagis.Web.Http;
namespace Dolstagis.Web.Aspnet
{
public class HttpRequest : IRequest
{
public HttpRequest(HttpRequestBase innerRequest)
{
this.Url = innerRequest.Unvalidated.Url;
this.Method = innerRequest.HttpMethod;
this.Path = new VirtualPath(Url.AbsolutePath);
this.AppRelativePath = this.Path.GetAppRelativePath(new VirtualPath(Url.AbsolutePath), true);
this.Protocol = innerRequest.ServerVariables["SERVER_PROTOCOL"];
this.IsSecure = innerRequest.IsSecureConnection;
this.Query = innerRequest.Unvalidated.QueryString;
this.Form = innerRequest.Unvalidated.Form;
this.Headers = innerRequest.Unvalidated.Headers;
}
public string Method { get; private set; }
public VirtualPath Path { get; private set; }
public VirtualPath AppRelativePath { get; private set; }
public string Protocol { get; private set; }
public bool IsSecure { get; private set; }
public Uri Url { get; private set; }
public NameValueCollection Query { get; private set; }
public NameValueCollection Form { get; private set; }
public NameValueCollection Headers { get; private set; }
}
}
| mit | C# |
f46129ee7c95d5cf532cd1def972c0a7f2a6f5c7 | update team | FabianTerhorst/eSportsRanking | Team.cs | Team.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eSportsRanking
{
public class Team
{
public Team()
{
}
public String name { get; set; }
public int winRatio
{
get {
return winCount / Math.MAX(winCount + lossCount, gameCount);
}
}
public int lossCount { get; set; }
public int winCount { get; set; }
public int gameCount
{ get
{
return lossCount + winCount;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eSportsRanking
{
public class Team
{
public Team()
{
}
public String name { get; set; }
public int points { get; set; }
public int lostGames { get; set; }
public int wonGames { get; set; }
public int gameCount
{ get
{
return lostGames + wonGames;
}
}
}
}
| unlicense | C# |
2b8a00c172bc42b55d7c20814e133109af636793 | Bump version to 1.0.0-beta018 | e-rik/XRoadLib,e-rik/XRoadLib,janno-p/XRoadLib | src/XRoadLib/Properties/AssemblyInfo.cs | src/XRoadLib/Properties/AssemblyInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitleAttribute("XRoadLib")]
[assembly: AssemblyProductAttribute("XRoadLib")]
[assembly: AssemblyDescriptionAttribute("A .NET library for implementing service interfaces of X-Road providers using Code-First Development approach.")]
[assembly: AssemblyVersionAttribute("1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.0.0-beta018")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.0.0";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitleAttribute("XRoadLib")]
[assembly: AssemblyProductAttribute("XRoadLib")]
[assembly: AssemblyDescriptionAttribute("A .NET library for implementing service interfaces of X-Road providers using Code-First Development approach.")]
[assembly: AssemblyVersionAttribute("1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.0.0-beta017")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.0.0";
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.