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 |
|---|---|---|---|---|---|---|---|---|
57725ccce10ae9e8cacb15e19735bbcfeebed945 | Change a modifier of class 'TokenEntries' | lury-lang/lury-lexer | lury-lexer/TokenEntry.cs | lury-lexer/TokenEntry.cs | //
// TokenEnrty.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Lury.Compiling.Lexer
{
/// <summary>
/// 出力されるトークンを区別するためのクラスです。
/// </summary>
public class TokenEntry
{
#region -- Public Properties --
/// <summary>
/// トークン名を表す文字列を取得します。
/// </summary>
public string Name { get; private set; }
#endregion
#region -- Constructors --
/// <summary>
/// トークン名を指定して新しい TokenEntry クラスのインスタンスを初期化します。
/// </summary>
/// <param name="name">トークン名。</param>
public TokenEntry(string name)
{
this.Name = name;
}
#endregion
}
}
| //
// TokenEnrty.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Lury.Compiling.Lexer
{
/// <summary>
/// 出力されるトークンを区別するための抽象クラスです。
/// </summary>
public abstract class TokenEntry
{
#region -- Public Properties --
/// <summary>
/// トークン名を表す文字列を取得します。
/// </summary>
public string Name { get; private set; }
#endregion
#region -- Constructors --
/// <summary>
/// トークン名を指定して新しい TokenEntry クラスのインスタンスを初期化します。
/// </summary>
/// <param name="name">トークン名。</param>
public TokenEntry(string name)
{
this.Name = name;
}
#endregion
}
}
| mit | C# |
85cf1d38729848cedb0311243e7ad01c67eabea3 | Fix UNC path regex | cjmurph/PmsService,cjmurph/PmsService | PlexServiceTray/DriveMapViewModel.cs | PlexServiceTray/DriveMapViewModel.cs | using PlexServiceCommon;
using System.ComponentModel.DataAnnotations;
namespace PlexServiceTray
{
public class DriveMapViewModel : ObservableObject
{
[Required(ErrorMessage = "Please enter a UNC path to map")]
[RegularExpression(@"^\\\\[a-zA-Z0-9\.\-_]{1,}(\\[a-zA-Z0-9\.\x20\-_]{1,}[\$]{0,1}){1,}$", ErrorMessage = "Please enter a UNC path to map")]
public string ShareName
{
get => _driveMap.ShareName;
set {
if (_driveMap.ShareName == value) {
return;
}
_driveMap.ShareName = value;
OnPropertyChanged("ShareName");
}
}
[Required(ErrorMessage = "Please enter a single character A-Z")]
[RegularExpression("[a-zA-Z]", ErrorMessage = "Please enter a single character A-Z")]
public string DriveLetter
{
get => _driveMap.DriveLetter;
set {
if (_driveMap.DriveLetter == value) {
return;
}
_driveMap.DriveLetter = value;
OnPropertyChanged("DriveLetter");
}
}
private readonly DriveMap _driveMap;
public DriveMapViewModel(DriveMap driveMap)
{
_driveMap = driveMap;
ValidationContext = this;
}
public DriveMap GetDriveMap()
{
return _driveMap;
}
}
}
| using PlexServiceCommon;
using System.ComponentModel.DataAnnotations;
namespace PlexServiceTray
{
public class DriveMapViewModel : ObservableObject
{
[Required(ErrorMessage = "Please enter a UNC path to map")]
[RegularExpression(@"", ErrorMessage = "Please enter a UNC path to map")]
public string ShareName
{
get => _driveMap.ShareName;
set {
if (_driveMap.ShareName == value) {
return;
}
_driveMap.ShareName = value;
OnPropertyChanged("ShareName");
}
}
[Required(ErrorMessage = "Please enter a single character A-Z")]
[RegularExpression("[a-zA-Z]", ErrorMessage = "Please enter a single character A-Z")]
public string DriveLetter
{
get => _driveMap.DriveLetter;
set {
if (_driveMap.DriveLetter == value) {
return;
}
_driveMap.DriveLetter = value;
OnPropertyChanged("DriveLetter");
}
}
private readonly DriveMap _driveMap;
public DriveMapViewModel(DriveMap driveMap)
{
_driveMap = driveMap;
ValidationContext = this;
}
public DriveMap GetDriveMap()
{
return _driveMap;
}
}
}
| mit | C# |
c97784e3d711a66c5b38659d9637c45481265154 | make comment more descriptive | Recognos/Metrics.NET,Liwoj/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET | Src/Metrics/MetricData/GaugeValue.cs | Src/Metrics/MetricData/GaugeValue.cs |
namespace Metrics.MetricData
{
/// <summary>
/// Combines the value of a gauge (a double) with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit, MetricTags tags)
: base(name, value, unit, tags)
{ }
}
}
|
namespace Metrics.MetricData
{
/// <summary>
/// Combines the value of a gauge with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit, MetricTags tags)
: base(name, value, unit, tags)
{ }
}
}
| apache-2.0 | C# |
11aaa6bcee2f9f1c23458c93341ac50869daa18e | Add more test coverage | ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework.Tests/Lists/TestEnumerableExtensions.cs | osu.Framework.Tests/Lists/TestEnumerableExtensions.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
namespace osu.Framework.Tests.Lists
{
[TestFixture]
public class TestEnumerableExtensions
{
[Test]
public void TestCommonPrefix()
{
string[] arr = { "abcd", "abdc" };
Assert.AreEqual("ab", arr.GetCommonPrefix());
arr = new[] { "123.456", "123.789" };
Assert.AreEqual("123.", arr.GetCommonPrefix());
arr = new[] { "123.456", "123.789", "435", "123.789" };
Assert.AreEqual(string.Empty, arr.GetCommonPrefix());
}
[Test]
public void TestEmptyEnumerable()
{
Assert.AreEqual(string.Empty, Enumerable.Empty<string>().GetCommonPrefix());
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
namespace osu.Framework.Tests.Lists
{
[TestFixture]
public class TestEnumerableExtensions
{
[Test]
public void TestCommonPrefix()
{
string[] arr = { "abcd", "abdc" };
Assert.AreEqual("ab", arr.GetCommonPrefix());
arr = new[] { "123.456", "123.789" };
Assert.AreEqual("123.", arr.GetCommonPrefix());
}
[Test]
public void TestEmptyEnumerable()
{
Assert.AreEqual(string.Empty, Enumerable.Empty<string>().GetCommonPrefix());
}
}
}
| mit | C# |
23a5792fcf105ab20500dcdba29792322011ef81 | Fix stray character in xmldoc | ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework/Input/Handlers/Tablet/ITabletHandler.cs | osu.Framework/Input/Handlers/Tablet/ITabletHandler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osuTK;
namespace osu.Framework.Input.Handlers.Tablet
{
/// <summary>
/// An interface to access OpenTabletDriverHandler.
/// Can be considered for removal when we no longer require dual targeting against netstandard.
/// </summary>
public interface ITabletHandler
{
/// <summary>
/// The offset of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaOffset { get; }
/// <summary>
/// The size of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaSize { get; }
/// <summary>
/// Information on the currently connected tablet device. May be null if no tablet is detected.
/// </summary>
IBindable<TabletInfo> Tablet { get; }
BindableBool Enabled { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osuTK;
namespace osu.Framework.Input.Handlers.Tablet
{
/// <summary>
/// An interface to access OpenTabletDriverHandler.
/// Can be considered for removal when we no longer require dual targeting against netstandard.
/// </summary>
public interface ITabletHandler
{
/// <summary>
/// The offset of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaOffset { get; }
/// <summary>
/// The size of the area which should be mapped to the game window.
/// </summary>
Bindable<Vector2> AreaSize { get; }
/// <summary>
/// Information on the currently connected tablet device./ May be null if no tablet is detected.
/// </summary>
IBindable<TabletInfo> Tablet { get; }
BindableBool Enabled { get; }
}
}
| mit | C# |
3809f68fbf21fe2bae3f118cb2b2ce81c1ba91ca | Revert "Retry" | Gabyche/CarBase | Assets/CarBaseController.cs | Assets/CarBaseController.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleInfo {
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool brake;
public bool motor;
public bool steering;
}
public class CarBaseController : MonoBehaviour {
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxBrakeTorque;
public float maxSteeringAngle;
public Rigidbody voiture;
private Quaternion cylRotationRight = Quaternion.AngleAxis (270, Vector3.right);
private Quaternion cylRotationUp = Quaternion.AngleAxis (90, Vector3.forward);
// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0) {
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation*cylRotationRight*cylRotationUp;
}
public void FixedUpdate()
{
float brake=0;
float motor=0;
if (Input.GetAxis ("Vertical") < 0 && voiture.velocity.magnitude > 0.001f) {
brake = - maxBrakeTorque * Input.GetAxis ("Vertical");
}
else {
motor = maxMotorTorque * Input.GetAxis ("Vertical");
}
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos) {
if (axleInfo.steering) {
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor) {
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
if (axleInfo.brake){
axleInfo.leftWheel.brakeTorque = brake;
axleInfo.rightWheel.brakeTorque = brake;
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
public bool Forwarding() {
AxleInfo axle = axleInfos [0];
return (axle.leftWheel.rpm >= 0);
}
} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleInfo {
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool brake;
public bool motor;
public bool steering;
}
public class CarBaseController : MonoBehaviour {
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxBrakeTorque;
public float maxSteeringAngle;
public Rigidbody voiture;
private Quaternion cylRotationRight = Quaternion.AngleAxis (270, Vector3.right);
private Quaternion cylRotationUp = Quaternion.AngleAxis (90, Vector3.forward);
// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0) {
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation*cylRotationRight*cylRotationUp;
}
public void FixedUpdate()
{
float brake=0;
float motor=0;
if (Input.GetAxis ("Vertical") < 0 && voiture.velocity.magnitude > 0) {
brake = - maxBrakeTorque * Input.GetAxis ("Vertical");
}
else {
motor = maxMotorTorque * Input.GetAxis ("Vertical");
}
print(motor);
//print (brake);
//print (voiture.velocity);
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos) {
if (axleInfo.steering) {
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor) {
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
if (axleInfo.brake){
axleInfo.leftWheel.brakeTorque = brake;
axleInfo.rightWheel.brakeTorque = brake;
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
} | artistic-2.0 | C# |
6ce8dae2ebd54d97b9cc1f22c8eeda305ac36357 | fix Pause/Resume on iOS | florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho | Bindings/iOS/UrhoSurface.cs | Bindings/iOS/UrhoSurface.cs | using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using CoreGraphics;
using UIKit;
namespace Urho.iOS
{
public class UrhoSurface : UIView
{
[DllImport("@rpath/Urho.framework/Urho", CallingConvention = CallingConvention.Cdecl)]
static extern void SDL_SetExternalViewPlaceholder(IntPtr viewPtr, IntPtr windowPtr);
TaskCompletionSource<bool> initTaskSource = new TaskCompletionSource<bool>();
public Task InitializeTask => initTaskSource.Task;
public UrhoSurface()
{
UrhoPlatformInitializer.DefaultInit();
initTaskSource = new TaskCompletionSource<bool>();
BackgroundColor = UIColor.Black;
}
public UrhoSurface(CGRect frame) : base(frame)
{
UrhoPlatformInitializer.DefaultInit();
BackgroundColor = UIColor.Black;
initTaskSource = new TaskCompletionSource<bool>();
}
public void Pause()
{
if (!Urho.Application.HasCurrent) return;
Urho.Application.Current.Engine.PauseMinimized = true;
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_LOST);
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_MINIMIZED);
}
public void Resume()
{
if (!Urho.Application.HasCurrent) return;
Urho.Application.Current.Engine.PauseMinimized = false;
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_GAINED);
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_RESTORED);
}
public override void MovedToWindow()
{
base.MovedToWindow();
var wndHandle = Window?.Handle;
SDL_SetExternalViewPlaceholder(Handle, wndHandle ?? IntPtr.Zero);
if (wndHandle != null) {
initTaskSource.TrySetResult (true);
} else {
initTaskSource = new TaskCompletionSource<bool> ();
}
}
}
} | using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using CoreGraphics;
using UIKit;
namespace Urho.iOS
{
public class UrhoSurface : UIView
{
[DllImport("@rpath/Urho.framework/Urho", CallingConvention = CallingConvention.Cdecl)]
static extern void SDL_SetExternalViewPlaceholder(IntPtr viewPtr, IntPtr windowPtr);
TaskCompletionSource<bool> initTaskSource = new TaskCompletionSource<bool>();
public Task InitializeTask => initTaskSource.Task;
public UrhoSurface()
{
UrhoPlatformInitializer.DefaultInit();
initTaskSource = new TaskCompletionSource<bool>();
BackgroundColor = UIColor.Black;
}
public UrhoSurface(CGRect frame) : base(frame)
{
UrhoPlatformInitializer.DefaultInit();
BackgroundColor = UIColor.Black;
initTaskSource = new TaskCompletionSource<bool>();
}
public void Pause()
{
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_LOST);
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_MINIMIZED);
}
public void Resume()
{
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_GAINED);
Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_RESTORED);
}
public override void MovedToWindow()
{
base.MovedToWindow();
var wndHandle = Window?.Handle;
SDL_SetExternalViewPlaceholder(Handle, wndHandle ?? IntPtr.Zero);
if (wndHandle != null) {
initTaskSource.TrySetResult (true);
} else {
initTaskSource = new TaskCompletionSource<bool> ();
}
}
}
} | mit | C# |
8e5be3c86dfafd434f3aeb807e366f694f2c8af9 | Refactor how parameters are checked | graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,joemcbride/graphql-dotnet | src/GraphQL/Resolvers/MethodModelBinderResolver.cs | src/GraphQL/Resolvers/MethodModelBinderResolver.cs | using System;
using System.Linq;
using System.Reflection;
using GraphQL.Types;
namespace GraphQL.Resolvers
{
public class MethodModelBinderResolver<T> : IFieldResolver
{
private readonly IDependencyResolver _dependencyResolver;
private readonly MethodInfo _methodInfo;
private readonly ParameterInfo[] _parameters;
private readonly Type _type;
public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver)
{
_dependencyResolver = dependencyResolver;
_type = typeof(T);
_methodInfo = methodInfo;
_parameters = _methodInfo.GetParameters();
}
public object Resolve(ResolveFieldContext context)
{
object[] arguments = null;
if (_parameters.Any())
{
arguments = new object[_parameters.Length];
var index = 0;
if (typeof(ResolveFieldContext) == _parameters[index].ParameterType)
{
arguments[index] = context;
index++;
}
if (context.Source?.GetType() == _parameters[index].ParameterType)
{
arguments[index] = context.Source;
index++;
}
foreach (var parameter in _parameters.Skip(index))
{
arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType);
index++;
}
}
var target = _dependencyResolver.Resolve(_type);
if (target == null)
{
var parentType = context.ParentType != null ? $"{context.ParentType.Name}." : null;
throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {parentType}{context.FieldName}");
}
return _methodInfo.Invoke(target, arguments);
}
}
}
| using System;
using System.Linq;
using System.Reflection;
using GraphQL.Types;
namespace GraphQL.Resolvers
{
public class MethodModelBinderResolver<T> : IFieldResolver
{
private readonly IDependencyResolver _dependencyResolver;
private readonly MethodInfo _methodInfo;
private readonly ParameterInfo[] _parameters;
private readonly Type _type;
public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver)
{
_dependencyResolver = dependencyResolver;
_type = typeof(T);
_methodInfo = methodInfo;
_parameters = _methodInfo.GetParameters();
}
public object Resolve(ResolveFieldContext context)
{
var index = 0;
var arguments = new object[_parameters.Length];
if (_parameters.Any() && typeof(ResolveFieldContext) == _parameters[index].ParameterType)
{
arguments[index] = context;
index++;
}
if (_parameters.Any() && context.Source?.GetType() == _parameters[index].ParameterType)
{
arguments[index] = context.Source;
index++;
}
foreach (var parameter in _parameters.Skip(index))
{
arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType);
index++;
}
var target = _dependencyResolver.Resolve(_type);
if (target == null)
{
throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {context.FieldName}");
}
return _methodInfo.Invoke(target, arguments);
}
}
}
| mit | C# |
bb59d19c1c4662ee4f737f09e894b7bc385d51fa | Implement IsValidDestination for Queen | ProgramFOX/Chess.NET | ChessDotNet/Pieces/Queen.cs | ChessDotNet/Pieces/Queen.cs | using System;
namespace ChessDotNet.Pieces
{
public class Queen : ChessPiece
{
public override Player Owner
{
get;
set;
}
public Queen(Player owner)
{
Owner = owner;
}
public override string GetFenCharacter()
{
return Owner == Player.White ? "Q" : "q";
}
public override bool IsValidDestination(Position origin, Position destination, ChessGame game)
{
return new Bishop(Owner).IsValidDestination(origin, destination, game) || new Rook(Owner).IsValidDestination(origin, destination, game);
}
}
}
| namespace ChessDotNet.Pieces
{
public class Queen : ChessPiece
{
public override Player Owner
{
get;
set;
}
public Queen(Player owner)
{
Owner = owner;
}
public override string GetFenCharacter()
{
return Owner == Player.White ? "Q" : "q";
}
}
}
| mit | C# |
314e44574d0b05c8110b579207dfa1127d18e94d | fix recursion | JohanLarsson/Gu.Wpf.Geometry | Gu.Wpf.Geometry.Demo/Converters/ElementToBoundsRectConverter.cs | Gu.Wpf.Geometry.Demo/Converters/ElementToBoundsRectConverter.cs | namespace Gu.Wpf.Geometry.Demo.Converters
{
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
[ValueConversion(typeof(FrameworkElement), typeof(Rect))]
public sealed class ElementToBoundsRectConverter : MarkupExtension, IValueConverter
{
public Type AncestorType { get; set; }
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var element = (FrameworkElement)value;
var parent = element?.Parent as FrameworkElement;
while (parent != null)
{
if (parent.GetType() == this.AncestorType)
{
return element.TransformToVisual(parent)
.TransformBounds(new Rect(element.DesiredSize));
}
parent = parent.Parent as FrameworkElement;
}
throw new InvalidOperationException("Did not find parent.");
}
object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotSupportedException($"{nameof(ElementToBoundsRectConverter)} can only be used in OneWay bindings");
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
| namespace Gu.Wpf.Geometry.Demo.Converters
{
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
[ValueConversion(typeof(FrameworkElement), typeof(Rect))]
public sealed class ElementToBoundsRectConverter : MarkupExtension, IValueConverter
{
public Type AncestorType { get; set; }
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var element = (FrameworkElement)value;
DependencyObject parent = element.Parent;
while (parent != null)
{
if (parent.GetType() == this.AncestorType)
{
return element.TransformToVisual((Visual)parent).TransformBounds(new Rect(element.DesiredSize));
}
parent = element.Parent;
}
throw new InvalidOperationException("Did not find parent.");
}
object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotSupportedException($"{nameof(ElementToBoundsRectConverter)} can only be used in OneWay bindings");
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
| mit | C# |
cf99aefb45d96eafc146c5c8e687387501c6f89c | Fix ArgumentNullException configuring pools via Remoting | nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Win/Extensions/ApplicationConfigurationExtensions.cs | MultiMiner.Win/Extensions/ApplicationConfigurationExtensions.cs | using MultiMiner.Utility.Serialization;
using System.Linq;
namespace MultiMiner.Win.Extensions
{
public static class ApplicationConfigurationExtensions
{
public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject)
{
Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application();
ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns");
if (modelObject.HiddenColumns != null)
transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray();
return transferObject;
}
public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject)
{
Data.Configuration.Application modelObject = new Data.Configuration.Application();
ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns");
if (transferObject.HiddenColumns != null)
modelObject.HiddenColumns = transferObject.HiddenColumns.ToList();
return modelObject;
}
}
}
| using MultiMiner.Utility.Serialization;
using System.Linq;
namespace MultiMiner.Win.Extensions
{
public static class ApplicationConfigurationExtensions
{
public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject)
{
Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application();
ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns");
transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray();
return transferObject;
}
public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject)
{
Data.Configuration.Application modelObject = new Data.Configuration.Application();
ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns");
modelObject.HiddenColumns = transferObject.HiddenColumns.ToList();
return modelObject;
}
}
}
| mit | C# |
c6b99e34140b5a4afb8bff907c2152e9771f6f2f | Update TMDbClientTrending.cs | LordMike/TMDbLib | TMDbLib/Client/TMDbClientTrending.cs | TMDbLib/Client/TMDbClientTrending.cs | using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.Trending;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/movie/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString().ToLower());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/tv/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/person/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
}
| using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
using TMDbLib.Objects.Trending;
using TMDbLib.Rest;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/movie/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/tv/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false);
return resp;
}
public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default)
{
RestRequest req = _client.Create("trending/person/{time_window}");
req.AddUrlSegment("time_window", timeWindow.ToString());
if (page >= 1)
req.AddQueryString("page", page.ToString());
SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
} | mit | C# |
2e31b09e4fe443cf1f124696480d41c10d7e8284 | Increment version number in assembly info | fox091/TournamentTeamMaker | TeamMaker/Properties/AssemblyInfo.cs | TeamMaker/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("TeamMaker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeamMaker")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("71703720-56ba-4e6a-9004-239a9836693b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2")]
[assembly: AssemblyFileVersion("1.0.2")]
| 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("TeamMaker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeamMaker")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("71703720-56ba-4e6a-9004-239a9836693b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
7d88d6f0fe5a40294e8adba82b0291a7605bc09f | fix fluent builder test | chrismckelt/WebMinder,chrismckelt/WebMinder,chrismckelt/WebMinder | Core.Tests/CreateFixture.cs | Core.Tests/CreateFixture.cs | using WebMinder.Core.Rules.IpBlocker;
using WebMinder.Core.Runners;
using Xunit;
namespace WebMinder.Core.Tests
{
public class CreateFixture
{
[Fact]
public void CreatesRuleSaysWhatItDoes()
{
const string rulesetname = "abcd";
const string rulesetdesc = "xyz";
var rule = Create<IpAddressBlockerRule, IpAddressRequest>
.RuleSet()
.With(y => y.RuleSetName = rulesetname)
.With(x => x.ErrorDescription = rulesetdesc)
.Build();
Assert.Equal(rulesetname, rule.Rule.RuleSetName);
Assert.Equal(rulesetdesc, rule.Rule.ErrorDescription);
}
}
} | using WebMinder.Core.Rules.IpBlocker;
using WebMinder.Core.Runners;
using Xunit;
namespace WebMinder.Core.Tests
{
public class CreateFixture
{
[Fact]
public void CreatesRuleSaysWhatItDoes()
{
const string rulesetname = "abcd";
const string rulesetdesc = "xyz";
var rule = Create<IpAddressBlockerRule, IpAddressRequest>
.RuleSet()
.With(y => y.RuleSetName = rulesetname)
.With(x => x.ErrorDescription = rulesetdesc)
.Build();
Assert.Equal(rulesetname, rule.Rule.RuleSetName);
Assert.Equal(rulesetname, rule.Rule.RuleSetName);
}
}
} | apache-2.0 | C# |
594eaa0d97475e678c676f2c8d6ef2fe20ff74fd | Handle not having a current session | bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity | src/BugsnagUnity/SessionTracker.cs | src/BugsnagUnity/SessionTracker.cs | using BugsnagUnity.Payload;
namespace BugsnagUnity
{
public interface ISessionTracker
{
void StartSession();
Session CurrentSession { get; }
}
class SessionTracker : ISessionTracker
{
private IClient Client { get; }
private Session _currentSession;
public Session CurrentSession
{
get => _currentSession?.Copy();
private set => _currentSession = value;
}
internal SessionTracker(IClient client)
{
Client = client;
}
public void StartSession()
{
var session = new Session();
CurrentSession = session;
var payload = new SessionReport(Client.Configuration, Client.User, session);
Client.Send(payload);
}
}
}
| using BugsnagUnity.Payload;
namespace BugsnagUnity
{
public interface ISessionTracker
{
void StartSession();
Session CurrentSession { get; }
}
class SessionTracker : ISessionTracker
{
private IClient Client { get; }
private Session _currentSession;
public Session CurrentSession
{
get => _currentSession.Copy();
private set => _currentSession = value;
}
internal SessionTracker(IClient client)
{
Client = client;
}
public void StartSession()
{
var session = new Session();
CurrentSession = session;
var payload = new SessionReport(Client.Configuration, Client.User, session);
Client.Send(payload);
}
}
}
| mit | C# |
1fbd7f602eb4036ca0009d7de2438a38368fee3d | Reduce temporary list of titles | Lidefeath/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE | Source/ACE/Network/GameEvent/Events/GameEventCharacterTitles.cs | Source/ACE/Network/GameEvent/Events/GameEventCharacterTitles.cs | namespace ACE.Network.GameEvent
{
public class GameEventCharacterTitle : GameEventPacket
{
public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } }
public GameEventCharacterTitle(Session session) : base(session) { }
protected override void WriteEventBody()
{
fragment.Payload.Write(1u);
fragment.Payload.Write(1u); // TODO: get current title from database
fragment.Payload.Write(10u); // TODO: get player's title list from database
for (uint i = 1; i <= 10; i++)
fragment.Payload.Write(i);
}
}
}
| namespace ACE.Network.GameEvent
{
public class GameEventCharacterTitle : GameEventPacket
{
public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } }
public GameEventCharacterTitle(Session session) : base(session) { }
protected override void WriteEventBody()
{
fragment.Payload.Write(1u);
fragment.Payload.Write(1u); // TODO: get current title from database
fragment.Payload.Write(1000u); // TODO: get player's title list from database
for (uint i = 1; i <= 1000; i++)
fragment.Payload.Write(i);
}
}
}
| agpl-3.0 | C# |
9bb2597c9247fed168ca427a2a6017a27dbe6871 | Add framerate parameter in `AnimatorBase.DisplayUndoable` | Weingartner/SolidworksAddinFramework | SolidworksAddinFramework/OpenGl/Animation/AnimatorBase.cs | SolidworksAddinFramework/OpenGl/Animation/AnimatorBase.cs | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using SolidWorks.Interop.sldworks;
using Weingartner.Exceptional.Reactive;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public abstract class AnimatorBase : IRenderable
{
public abstract TimeSpan Duration { get; }
public abstract IReadOnlyList<IAnimationSection> Sections { get; }
public IDisposable DisplayUndoable(IModelDoc2 modelDoc, double framerate = 30, int layer = 0)
{
OnStart(DateTime.Now);
var d = new CompositeDisposable();
OpenGlRenderer.DisplayUndoable(this, modelDoc, layer).DisposeWith(d);
Redraw(modelDoc, framerate).DisposeWith(d);
return d;
}
public abstract void OnStart(DateTime startTime);
public abstract void Render(DateTime time);
public Tuple<Vector3, float> BoundingSphere
{
get
{
throw new NotImplementedException();
}
}
public void ApplyTransform(Matrix4x4 transform)
{
throw new NotImplementedException();
}
private static IDisposable Redraw(IModelDoc2 doc, double framerate = 30)
{
return Observable.Interval(TimeSpan.FromSeconds(1.0 / framerate))
.ToObservableExceptional()
.ObserveOnSolidworksThread()
.Subscribe(_ => doc.GraphicsRedraw2());
}
}
} | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using SolidWorks.Interop.sldworks;
using Weingartner.Exceptional.Reactive;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public abstract class AnimatorBase : IRenderable
{
public abstract TimeSpan Duration { get; }
public abstract IReadOnlyList<IAnimationSection> Sections { get; }
public IDisposable DisplayUndoable(IModelDoc2 modelDoc, int layer = 0)
{
OnStart(DateTime.Now);
var d = new CompositeDisposable();
OpenGlRenderer.DisplayUndoable(this, modelDoc, layer).DisposeWith(d);
Redraw(modelDoc).DisposeWith(d);
return d;
}
public abstract void OnStart(DateTime startTime);
public abstract void Render(DateTime time);
public Tuple<Vector3, float> BoundingSphere
{
get
{
throw new NotImplementedException();
}
}
public void ApplyTransform(Matrix4x4 transform)
{
throw new NotImplementedException();
}
private static IDisposable Redraw(IModelDoc2 doc, double framerate = 30)
{
return Observable.Interval(TimeSpan.FromSeconds(1.0 / framerate))
.ToObservableExceptional()
.ObserveOnSolidworksThread()
.Subscribe(_ => doc.GraphicsRedraw2());
}
}
} | mit | C# |
a46a4056fc236fd3afb6040496581a10ba41bf56 | Fix Plot return to index | joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net | Joinrpg/Views/Plot/Create.cshtml | Joinrpg/Views/Plot/Create.cshtml | @model JoinRpg.Web.Models.Plot.AddPlotFolderViewModel
@{
ViewBag.Title = "Добавить сюжет";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<p>Начните работу с того, что создайте сюжет. Сюжет — это история, она состоит из вводных, которые вы даете персонажам или локациям.
Все поля на этой странице — только для мастеров, игроки их не увидят.</p>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ProjectId)
<div class="form-group">
@Html.LabelFor(model => model.PlotFolderMasterTitle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PlotFolderMasterTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PlotFolderMasterTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.TodoField, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.TodoField, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.TodoField, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Создать сюжет" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Назад к списку сюжетов", "Index", new {Model.ProjectId}, null)
</div>
| @model JoinRpg.Web.Models.Plot.AddPlotFolderViewModel
@{
ViewBag.Title = "Добавить сюжет";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<p>Начните работу с того, что создайте сюжет. Сюжет — это история, она состоит из вводных, которые вы даете персонажам или локациям.
Все поля на этой странице — только для мастеров, игроки их не увидят.</p>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ProjectId)
<div class="form-group">
@Html.LabelFor(model => model.PlotFolderMasterTitle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PlotFolderMasterTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PlotFolderMasterTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.TodoField, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.TodoField, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.TodoField, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Создать сюжет" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
| mit | C# |
b9458307115d57ee464ef6aa6463c63eb11536a5 | Add Operator Overloads to Vertex Struct | Silvertorch5/RobustEngine | Graphics/Vertex.cs | Graphics/Vertex.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RobustEngine.Graphics
{
public struct Vertex
{
public float X, Y, Z;
public const int Stride = 12;
public static readonly Vertex Zero = new Vertex(0,0);
public static readonly Vertex UnitX = new Vertex(1,0);
public static readonly Vertex UnitY = new Vertex(0,1);
public static readonly Vertex One = new Vertex(1,1);
public Vertex(float x, float y, float z = 0)
{
X = x;
Y = y;
Z = z;
}
#region OPERATORS OH BOY
#region VECTOR MATH
public static Vertex operator *(Vertex A, Vertex B)
{
return new Vertex(A.X * B.X, A.Y * B.Y, A.Z * B.Z);
}
public static Vertex operator +(Vertex A, Vertex B)
{
return new Vertex(A.X + B.X, A.Y + B.Y, A.Z + B.Z);
}
public static Vertex operator -(Vertex A, Vertex B)
{
return new Vertex(A.X - B.X, A.Y - B.Y, A.Z - B.Z);
}
public static Vertex operator /(Vertex A, Vertex B)
{
return new Vertex(A.X / B.X, A.Y / B.Y, A.Z / B.Z);
}
#endregion
#region INT MATH
public static Vertex operator *(Vertex A, int B)
{
return new Vertex(A.X * B, A.Y * B, A.Z * B);
}
public static Vertex operator +(Vertex A, int B)
{
return new Vertex(A.X + B, A.Y + B, A.Z + B);
}
public static Vertex operator -(Vertex A, int B)
{
return new Vertex(A.X - B, A.Y - B, A.Z - B);
}
public static Vertex operator /(Vertex A, int B)
{
return new Vertex(A.X / B, A.Y / B, A.Z / B);
}
#endregion
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RobustEngine.Graphics
{
public struct Vertex
{
public float X, Y, Z;
public const int Stride = 12;
public static readonly Vertex Zero = new Vertex(0,0);
public static readonly Vertex UnitX = new Vertex(1,0);
public static readonly Vertex UnitY = new Vertex(0,1);
public static readonly Vertex One = new Vertex(1,1);
public Vertex(float x, float y, float z = 0)
{
X = x;
Y = y;
Z = z;
}
public static Vertex operator *(Vertex A, Vertex B)
{
return new Vertex(A.X * B.X, A.Y * B.Y, A.Z * B.Z);
}
public static Vertex operator +(Vertex A, Vertex B)
{
return new Vertex(A.X + B.X, A.Y + B.Y, A.Z + B.Z);
}
public static Vertex operator -(Vertex A, Vertex B)
{
return new Vertex(A.X - B.X, A.Y - B.Y, A.Z - B.Z);
}
public static Vertex operator /(Vertex A, Vertex B)
{
return new Vertex(A.X / B.X, A.Y / B.Y, A.Z / B.Z);
}
}
}
| mit | C# |
07f2325cb78d7cc503c30b9b1717b7245f4c2554 | Change button name | Vtek/PowerBI.Api.Client | src/XamarinClient/Page/RootPage.cs | src/XamarinClient/Page/RootPage.cs | using System;
using Xamarin.Forms;
namespace XamarinClient
{
/// <summary>
/// Root page.
/// </summary>
public class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
Bind();
}
void InitializeComponent()
{
var layout = new StackLayout
{
VerticalOptions = LayoutOptions.Center
};
var button = new Button
{
VerticalOptions = LayoutOptions.Center,
Text = "Insert",
IsEnabled = false
};
button.SetBinding<MainViewModel>(Button.CommandProperty, vm => vm.InsertCommand);
layout.Children.Add(button);
Content = layout;
}
void Bind()
{
var viewModel = new MainViewModel();
viewModel.Insert += async (sender, e) => await DisplayAlert("Insertion", "Données bien insérée !", "OK");
BindingContext = viewModel;
}
}
}
| using System;
using Xamarin.Forms;
namespace XamarinClient
{
/// <summary>
/// Root page.
/// </summary>
public class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
Bind();
}
void InitializeComponent()
{
var layout = new StackLayout
{
VerticalOptions = LayoutOptions.Center
};
var button = new Button
{
VerticalOptions = LayoutOptions.Center,
Text = "Connect",
IsEnabled = false
};
button.SetBinding<MainViewModel>(Button.CommandProperty, vm => vm.InsertCommand);
layout.Children.Add(button);
Content = layout;
}
void Bind()
{
var viewModel = new MainViewModel();
viewModel.Insert += async (sender, e) => await DisplayAlert("Insertion", "Données bien insérée !", "OK");
BindingContext = viewModel;
}
}
}
| mit | C# |
cdfe95c15930ac6e0072699d7f7ab2c0725fccaf | Add AcentColour and xmldoc. | smoogipooo/osu,ZLima12/osu,NeoAdonis/osu,Damnae/osu,ppy/osu,johnneijzen/osu,nyaamara/osu,tacchinotacchi/osu,Drezi126/osu,Frontear/osuKyzer,DrabWeb/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,Nabile-Rahmani/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,RedNesto/osu,peppy/osu,naoey/osu,peppy/osu,naoey/osu,NeoAdonis/osu,ZLima12/osu,ppy/osu,naoey/osu,2yangk23/osu,osu-RP/osu-RP,smoogipoo/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo>
{
/// <summary>
/// The colour used for various elements of this DrawableHitObject.
/// </summary>
public virtual Color4 AccentColour { get; }
public DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo();
protected override void UpdateState(ArmedState state)
{
}
/// <summary>
/// Sets the scroll position of the DrawableHitObject relative to the offset between
/// a time value and the HitObject's StartTime.
/// </summary>
/// <param name="time"></param>
protected void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo>
{
public DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo();
protected override void UpdateState(ArmedState state)
{
}
protected void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
}
}
| mit | C# |
0a8bb3f1636984ae38199b78b053573077fd0f27 | clean up | edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk | tests/InMemoryDataStoreTest.cs | tests/InMemoryDataStoreTest.cs | using System.IO;
using FHSDK.Services;
using FHSDK.Services.Data;
using FHSDK.Sync;
using FHSDKPortable;
using Newtonsoft.Json.Linq;
using Xunit;
namespace tests
{
public class InMemoryDataStoreTest
{
private readonly string _dataPersistFile;
private readonly IIOService _ioService;
public InMemoryDataStoreTest()
{
FHClient.Init();
_ioService = ServiceFinder.Resolve<IIOService>();
var dataDir = _ioService.GetDataPersistDir();
var dataPersistDir = Path.Combine(dataDir, "syncTestDir");
_dataPersistFile = Path.Combine(dataPersistDir, ".test_data_file");
}
[Fact]
public void TestInsertIntoDataStore()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("key1", obj);
dataStore.Insert("key2", obj);
//then
var list = dataStore.List();
Assert.Equal(2, list.Count);
Assert.NotNull(list["key1"]);
var result = dataStore.Get("key1");
Assert.Equal(obj, result);
}
[Fact]
public void TestSaveDataStoreToJson()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
dataStore.PersistPath = _dataPersistFile;
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("main-key", obj);
dataStore.Save();
//then
Assert.True(_ioService.Exists(_dataPersistFile));
var content = _ioService.ReadFile(_dataPersistFile);
Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content);
}
}
}
| using System.IO;
using FHSDK.Services;
using FHSDK.Services.Data;
using FHSDK.Sync;
using FHSDKPortable;
using Newtonsoft.Json.Linq;
using Xunit;
namespace tests
{
public class InMemoryDataStoreTest
{
private string _dataPersistDir;
private string _dataPersistFile;
private IIOService _ioService;
public InMemoryDataStoreTest()
{
FHClient.Init();
_ioService = ServiceFinder.Resolve<IIOService>();
var dataDir = _ioService.GetDataPersistDir();
_dataPersistDir = Path.Combine(dataDir, "syncTestDir");
_dataPersistFile = Path.Combine(_dataPersistDir, ".test_data_file");
}
[Fact]
public void TestInsertIntoDataStore()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("key1", obj);
dataStore.Insert("key2", obj);
//then
var list = dataStore.List();
Assert.Equal(2, list.Count);
Assert.NotNull(list["key1"]);
var result = dataStore.Get("key1");
Assert.Equal(obj, result);
}
[Fact]
public void TestSaveDataStoreToJson()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
dataStore.PersistPath = _dataPersistFile;
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("main-key", obj);
dataStore.Save();
//then
Assert.True(_ioService.Exists(_dataPersistFile));
var content = _ioService.ReadFile(_dataPersistFile);
Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content);
}
}
}
| apache-2.0 | C# |
529816fb307ac071e2ca031606144eb8377e523b | Fix generated code spelling mistake. Closes #796 | sschmid/Entitas-CSharp,sschmid/Entitas-CSharp | Addons/Entitas.VisualDebugging.CodeGeneration.Plugins/Entitas.VisualDebugging.CodeGeneration.Plugins/ContextObserverGenerator.cs | Addons/Entitas.VisualDebugging.CodeGeneration.Plugins/Entitas.VisualDebugging.CodeGeneration.Plugins/ContextObserverGenerator.cs | using System.Linq;
using DesperateDevs.CodeGeneration;
using DesperateDevs.Utils;
using Entitas.CodeGeneration.Plugins;
namespace Entitas.VisualDebugging.CodeGeneration.Plugins {
public class ContextObserverGenerator : ICodeGenerator {
public string name { get { return "Context Observer"; } }
public int priority { get { return 0; } }
public bool runInDryMode { get { return true; } }
const string CONTEXTS_TEMPLATE =
@"public partial class Contexts {
#if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR)
[Entitas.CodeGeneration.Attributes.PostConstructor]
public void InitializeContextObservers() {
try {
${contextObservers}
} catch(System.Exception) {
}
}
public void CreateContextObserver(Entitas.IContext context) {
if (UnityEngine.Application.isPlaying) {
var observer = new Entitas.VisualDebugging.Unity.ContextObserver(context);
UnityEngine.Object.DontDestroyOnLoad(observer.gameObject);
}
}
#endif
}
";
const string CONTEXT_OBSERVER_TEMPLATE = @" CreateContextObserver(${contextName});";
public CodeGenFile[] Generate(CodeGeneratorData[] data) {
var contextNames = data
.OfType<ContextData>()
.Select(d => d.GetContextName())
.OrderBy(contextName => contextName)
.ToArray();
return new[] {
new CodeGenFile(
"Contexts.cs",
generateContextsClass(contextNames),
GetType().FullName)
};
}
string generateContextsClass(string[] contextNames) {
var contextObservers = string.Join("\n", contextNames
.Select(contextName => CONTEXT_OBSERVER_TEMPLATE
.Replace("${contextName}", contextName.LowercaseFirst())
).ToArray());
return CONTEXTS_TEMPLATE
.Replace("${contextObservers}", contextObservers);
}
}
}
| using System.Linq;
using DesperateDevs.CodeGeneration;
using DesperateDevs.Utils;
using Entitas.CodeGeneration.Plugins;
namespace Entitas.VisualDebugging.CodeGeneration.Plugins {
public class ContextObserverGenerator : ICodeGenerator {
public string name { get { return "Context Observer"; } }
public int priority { get { return 0; } }
public bool runInDryMode { get { return true; } }
const string CONTEXTS_TEMPLATE =
@"public partial class Contexts {
#if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR)
[Entitas.CodeGeneration.Attributes.PostConstructor]
public void InitializeContexObservers() {
try {
${contextObservers}
} catch(System.Exception) {
}
}
public void CreateContextObserver(Entitas.IContext context) {
if (UnityEngine.Application.isPlaying) {
var observer = new Entitas.VisualDebugging.Unity.ContextObserver(context);
UnityEngine.Object.DontDestroyOnLoad(observer.gameObject);
}
}
#endif
}
";
const string CONTEXT_OBSERVER_TEMPLATE = @" CreateContextObserver(${contextName});";
public CodeGenFile[] Generate(CodeGeneratorData[] data) {
var contextNames = data
.OfType<ContextData>()
.Select(d => d.GetContextName())
.OrderBy(contextName => contextName)
.ToArray();
return new[] {
new CodeGenFile(
"Contexts.cs",
generateContextsClass(contextNames),
GetType().FullName)
};
}
string generateContextsClass(string[] contextNames) {
var contextObservers = string.Join("\n", contextNames
.Select(contextName => CONTEXT_OBSERVER_TEMPLATE
.Replace("${contextName}", contextName.LowercaseFirst())
).ToArray());
return CONTEXTS_TEMPLATE
.Replace("${contextObservers}", contextObservers);
}
}
}
| mit | C# |
3437f02a99423472e784c441ffbc822e55408a4c | Update Index.cshtml | infosecdev/botforge,roxberry/botforge,roxberry/botforge,infosecdev/botforge | botforge/Views/Home/Index.cshtml | botforge/Views/Home/Index.cshtml | @{
ViewBag.Title = "ROBOTS!";
}
<div class="hero-unit">
<img src="~/img/logo2.png" style="width:300px;" alt="The Robot Forge" />
<img src="~/img/banner2.png" />
<p class="lead">The Robot Forge is where robot makers come to learn about robotics, build robots from components and software and interact with other robot makers.</p>
</div>
<div class="row">
<div class="span4">
<h2>
<img src="~/img/robot.png" style="width:32px;margin-right:15px;"/>
<img src="~/img/Learn.png" /></h2>
<p>Robotics is a pathway to learning hardware and software engineering. Follow us for weekly classes and activities.</p>
<p><a class="btn" href="~/Views/Home/Learn.cshtml">Learn more »</a></p>
</div>
<div class="span4">
<h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" />
<img src="~/img/Build.png" /></h2>
<p>Make robots by assemblying actuators, sensors, controllers and writing programs. This is where we show off some of prototypes and production models.</p>
<p><a class="btn" href="~/Views/Home/Build.cshtml">Learn more »</a></p>
</div>
<div class="span4">
<h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" />
<img src="~/img/Interact.png" /></h2>
<p>Robot makers are everywhere. Here you can read about the latest creations and participate in a safe social network of like minded creators.</p>
<p><a class="btn" href="~/Views/Home/Interact.cshtml">Learn more »</a></p>
</div>
</div>
| @{
ViewBag.Title = "The Robot Forge";
}
<div class="hero-unit">
<img src="~/img/logo2.png" style="width:300px;" alt="The Robot Forge" />
<img src="~/img/banner2.png" />
<p class="lead">The Robot Forge is where robot makers come to learn about robotics, build robots from components and software and interact with other robot makers.</p>
</div>
<div class="row">
<div class="span4">
<h2>
<img src="~/img/robot.png" style="width:32px;margin-right:15px;"/>
<img src="~/img/Learn.png" /></h2>
<p>Robotics is a pathway to learning hardware and software engineering. Follow us for weekly classes and activities.</p>
<p><a class="btn" href="~/Views/Home/Learn.cshtml">Learn more »</a></p>
</div>
<div class="span4">
<h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" />
<img src="~/img/Build.png" /></h2>
<p>Make robots by assemblying actuators, sensors, controllers and writing programs. This is where we show off some of prototypes and production models.</p>
<p><a class="btn" href="~/Views/Home/Build.cshtml">Learn more »</a></p>
</div>
<div class="span4">
<h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" />
<img src="~/img/Interact.png" /></h2>
<p>Robot makers are everywhere. Here you can read about the latest creations and participate in a safe social network of like minded creators.</p>
<p><a class="btn" href="~/Views/Home/Interact.cshtml">Learn more »</a></p>
</div>
</div> | mit | C# |
277c613e552daaf4c7f42714421b452c08344cf5 | Fix silly mistake in DI configuration | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.Web/App_Start/ContainerFactoryProviderExtensions.cs | Agiil.Web/App_Start/ContainerFactoryProviderExtensions.cs | using System;
using System.Web.Http;
using Agiil.Bootstrap.DiConfiguration;
using Autofac;
namespace Agiil.Web.App_Start
{
public static class ContainerFactoryProviderExtensions
{
public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config)
{
if(provider == null)
throw new ArgumentNullException(nameof(provider));
if(config == null)
throw new ArgumentNullException(nameof(config));
var diFactory = provider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration;
if(diFactory == null)
throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}.");
diFactory.SetHttpConfiguration(config);
return diFactory.GetContainer();
}
}
}
| using System;
using System.Web.Http;
using Agiil.Bootstrap.DiConfiguration;
using Autofac;
namespace Agiil.Web.App_Start
{
public static class ContainerFactoryProviderExtensions
{
public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config)
{
if(provider == null)
throw new ArgumentNullException(nameof(provider));
if(config == null)
throw new ArgumentNullException(nameof(config));
var factoryProvider = new ContainerFactoryProvider();
var diFactory = factoryProvider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration;
if(diFactory == null)
throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}.");
diFactory.SetHttpConfiguration(config);
return diFactory.GetContainer();
}
}
}
| mit | C# |
c4c9753214bb84c5e423ce422db7acca46227c2b | Return localized resource | gjulianm/AncoraMVVM | AncoraMVVM.Phone/Converters/PhoneEnumToStringConverter.cs | AncoraMVVM.Phone/Converters/PhoneEnumToStringConverter.cs | using System.Windows;
using System.Windows.Data;
using AncoraMVVM.Base.Converters;
namespace AncoraMVVM.Phone.Converters
{
public class PhoneEnumToStringConverter : BaseEnumToStringConverter, IValueConverter
{
protected override string GetLocalizedString(string id)
{
return Application.Current.Resources[id] as string;
}
}
}
| using System.Windows.Data;
using AncoraMVVM.Base.Converters;
namespace AncoraMVVM.Phone.Converters
{
public class PhoneEnumToStringConverter : BaseEnumToStringConverter, IValueConverter
{
protected override string GetLocalizedString(string id)
{
throw new System.NotImplementedException();
}
}
}
| mpl-2.0 | C# |
fd4ca91d6f7c47c9ce97eed2c91b686cac391447 | Fix a bug where toggleready returns an exception when provided with the wrong number of arguments (#9631) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/GameTicking/Commands/ToggleReadyCommand.cs | Content.Server/GameTicking/Commands/ToggleReadyCommand.cs | using Content.Shared.Administration;
using Robust.Server.Player;
using Robust.Shared.Console;
namespace Content.Server.GameTicking.Commands
{
[AnyCommand]
sealed class ToggleReadyCommand : IConsoleCommand
{
public string Command => "toggleready";
public string Description => "";
public string Help => "";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (args.Length != 1)
{
shell.WriteError(Loc.GetString("shell-wrong-arguments-number"));
return;
}
if (player == null)
{
return;
}
var ticker = EntitySystem.Get<GameTicker>();
ticker.ToggleReady(player, bool.Parse(args[0]));
}
}
}
| using Content.Shared.Administration;
using Robust.Server.Player;
using Robust.Shared.Console;
namespace Content.Server.GameTicking.Commands
{
[AnyCommand]
sealed class ToggleReadyCommand : IConsoleCommand
{
public string Command => "toggleready";
public string Description => "";
public string Help => "";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (player == null)
{
return;
}
var ticker = EntitySystem.Get<GameTicker>();
ticker.ToggleReady(player, bool.Parse(args[0]));
}
}
}
| mit | C# |
85ed140631e10d14875a183457066e74b55623b8 | Add simple successfully checking property to AsyncResponseData | insthync/LiteNetLibManager,insthync/LiteNetLibManager | Scripts/AsyncResponseData.cs | Scripts/AsyncResponseData.cs | using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct AsyncResponseData<TResponse>
where TResponse : INetSerializable
{
public ResponseHandlerData RequestHandler { get; private set; }
public AckResponseCode ResponseCode { get; private set; }
public TResponse Response { get; private set; }
public bool IsSuccess { get { return ResponseCode == AckResponseCode.Success; } }
public AsyncResponseData(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response)
{
RequestHandler = requestHandler;
ResponseCode = responseCode;
Response = response;
}
}
} | using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct AsyncResponseData<TResponse>
where TResponse : INetSerializable
{
public ResponseHandlerData RequestHandler { get; private set; }
public AckResponseCode ResponseCode { get; private set; }
public TResponse Response { get; private set; }
public AsyncResponseData(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response)
{
RequestHandler = requestHandler;
ResponseCode = responseCode;
Response = response;
}
}
} | mit | C# |
3ee576240de73918c6455d500c0644b1f2c4c54b | Improve tests | Fody/Stamp | Tests/TaskTests.cs | Tests/TaskTests.cs | using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class TaskTests
{
private Assembly assembly;
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private string beforeAssemblyPath;
private string afterAssemblyPath;
public TaskTests()
{
beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
File.Copy(beforeAssemblyPath, afterAssemblyPath, true);
using (var moduleDefinition = ModuleDefinition.ReadModule(beforeAssemblyPath))
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AddinDirectoryPath = currentDirectory,
SolutionDirectoryPath = currentDirectory,
AssemblyFilePath = afterAssemblyPath,
};
weavingTask.Execute();
moduleDefinition.Write(afterAssemblyPath);
weavingTask.AfterWeaving();
}
assembly = Assembly.LoadFile(afterAssemblyPath);
}
[Test]
public void EnsureAttributeExists()
{
var customAttributes = (AssemblyInformationalVersionAttribute)assembly
.GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false)
.First();
AssertVersionWithSha(customAttributes.InformationalVersion);
}
[Test]
public void Win32Resource()
{
var versionInfo = FileVersionInfo.GetVersionInfo(afterAssemblyPath);
AssertVersionWithSha(versionInfo.ProductVersion);
Assert.IsNotNull(versionInfo.FileVersion);
Assert.IsNotEmpty(versionInfo.FileVersion);
Assert.AreEqual("1.0.0.0",versionInfo.FileVersion);
}
private static void AssertVersionWithSha(string version)
{
Assert.IsNotNull(version);
Assert.IsNotEmpty(version);
StringAssert.Contains("1.0.0.0", version, "Missing number");
StringAssert.Contains("Head:", version, message: "Missing Head");
StringAssert.Contains("Sha:", version, message: "Missing Sha");
Trace.WriteLine(version);
}
#if(DEBUG)
[Test]
public void PeVerify()
{
Verifier.Verify(beforeAssemblyPath, afterAssemblyPath);
}
#endif
} | using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class TaskTests
{
private Assembly assembly;
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private string beforeAssemblyPath;
private string afterAssemblyPath;
public TaskTests()
{
beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif
afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
File.Copy(beforeAssemblyPath, afterAssemblyPath, true);
using (var moduleDefinition = ModuleDefinition.ReadModule(beforeAssemblyPath))
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AddinDirectoryPath = currentDirectory,
SolutionDirectoryPath = currentDirectory,
AssemblyFilePath = afterAssemblyPath,
};
weavingTask.Execute();
moduleDefinition.Write(afterAssemblyPath);
weavingTask.AfterWeaving();
}
assembly = Assembly.LoadFile(afterAssemblyPath);
}
[Test]
public void EnsureAttributeExists()
{
var customAttributes = (AssemblyInformationalVersionAttribute)assembly
.GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false)
.First();
Assert.IsNotNull(customAttributes.InformationalVersion);
Assert.IsNotEmpty(customAttributes.InformationalVersion);
Trace.WriteLine(customAttributes.InformationalVersion);
}
[Test]
public void Win32Resource()
{
var versionInfo = FileVersionInfo.GetVersionInfo(afterAssemblyPath);
Assert.IsNotNull(versionInfo.ProductVersion);
Assert.IsNotEmpty(versionInfo.ProductVersion);
Assert.IsNotNull(versionInfo.FileVersion);
Assert.IsNotEmpty(versionInfo.FileVersion);
Trace.WriteLine(versionInfo.ProductVersion);
Trace.WriteLine(versionInfo.FileVersion);
}
#if(DEBUG)
[Test]
public void PeVerify()
{
Verifier.Verify(beforeAssemblyPath, afterAssemblyPath);
}
#endif
} | mit | C# |
693ca83135753921aee5c08f377f700ce6014fce | Allow trial_period_start to be null | xamarin/XamarinStripe,haithemaraissia/XamarinStripe | XamarinStripe/StripePlan.cs | XamarinStripe/StripePlan.cs | /*
* Copyright 2011 Joe Dluzen
*
* Author(s):
* Joe Dluzen (jdluzen@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Newtonsoft.Json;
namespace Xamarin.Payments.Stripe {
[JsonObject (MemberSerialization.OptIn)]
public class StripePlan : StripeId {
[JsonProperty (PropertyName = "livemode")]
public bool LiveMode { get; set; }
[JsonProperty (PropertyName = "amount")]
public int Amount { get; set; }
[JsonProperty (PropertyName = "currency")]
public string Currency { get; set; }
// deleted was deleted
/*
[JsonProperty(PropertyName = "deleted")]
public bool? Deleted { get; set; }
*/
[JsonProperty(PropertyName = "identifier")]
public string Identifier { get; set; }
[JsonProperty (PropertyName = "interval")]
public StripePlanInterval Interval { get; set; }
[JsonProperty (PropertyName = "name")]
public string Name { get; set; }
[JsonProperty (PropertyName = "trial_period_days")]
public int? TrialPeriod { get; set; }
}
}
| /*
* Copyright 2011 Joe Dluzen
*
* Author(s):
* Joe Dluzen (jdluzen@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Newtonsoft.Json;
namespace Xamarin.Payments.Stripe {
[JsonObject (MemberSerialization.OptIn)]
public class StripePlan : StripeId {
[JsonProperty (PropertyName = "livemode")]
public bool LiveMode { get; set; }
[JsonProperty (PropertyName = "amount")]
public int Amount { get; set; }
[JsonProperty (PropertyName = "currency")]
public string Currency { get; set; }
// deleted was deleted
/*
[JsonProperty(PropertyName = "deleted")]
public bool? Deleted { get; set; }
*/
[JsonProperty(PropertyName = "identifier")]
public string Identifier { get; set; }
[JsonProperty (PropertyName = "interval")]
public StripePlanInterval Interval { get; set; }
[JsonProperty (PropertyName = "name")]
public string Name { get; set; }
[JsonProperty (PropertyName = "trial_period_days")]
public int TrialPeriod { get; set; }
}
}
| apache-2.0 | C# |
ebf5572bc43162d0b28e3f3b9b6255177199d3f0 | Configure Sensor dynamically | jcapellman/jcTM,jcapellman/jcTM | csharp/jcTM.UWP.IoT/MainPage.xaml.cs | csharp/jcTM.UWP.IoT/MainPage.xaml.cs | using Windows.UI.Xaml.Controls;
using GrovePi;
using GrovePi.Sensors;
using jcTM.PCL.Handlers;
namespace jcTM.UWP.IoT {
public sealed partial class MainPage : Page {
private ITemperatureSensor _sensor;
public MainPage() {
this.InitializeComponent();
ConfigureSensor();
ReadTemperature();
}
// Run through the 3 Analog Pins
private void ConfigureSensor() {
var device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin0, TemperatureSensorModel.OnePointTwo);
if (device != null)
{
_sensor = device;
}
device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1, TemperatureSensorModel.OnePointTwo);
if (device != null) {
_sensor = device;
}
device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin2, TemperatureSensorModel.OnePointTwo);
if (device != null) {
_sensor = device;
}
}
private async void ReadTemperature() {
var tempHandler = new TemperatureHandler();
while (true) {
var temperature = _sensor.TemperatureInCelcius();
var convertedTemperature = ((9.0/5.0)*temperature) + 32;
tempHandler.RecordTemperature(convertedTemperature);
await System.Threading.Tasks.Task.Delay(5000);
}
}
}
} | using Windows.UI.Xaml.Controls;
using GrovePi;
using GrovePi.Sensors;
using jcTM.PCL.Handlers;
namespace jcTM.UWP.IoT {
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
ReadTemperature();
}
private async void ReadTemperature() {
var tempHandler = new TemperatureHandler();
while (true) {
var temperature = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin0, TemperatureSensorModel.OnePointTwo).TemperatureInCelcius();
var convertedTemperature = ((9.0/5.0)*temperature) + 32;
tempHandler.RecordTemperature(convertedTemperature);
await System.Threading.Tasks.Task.Delay(5000);
}
}
}
} | mit | C# |
23dcd526e3c9c1b54d273e9a48729c64c231605e | Add nullcheck for CI | ZLima12/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework | osu.Framework.Tests/Visual/TestCaseScreenshot.cs | osu.Framework.Tests/Visual/TestCaseScreenshot.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Platform;
using osu.Framework.Testing;
using OpenTK;
using OpenTK.Graphics;
using SixLabors.ImageSharp;
namespace osu.Framework.Tests.Visual
{
public class TestCaseScreenshot : TestCase
{
[Resolved]
private GameHost host { get; set; }
private Sprite display;
[BackgroundDependencyLoader]
private void load()
{
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Masking = true,
BorderColour = Color4.Green,
BorderThickness = 2,
Child = display = new Sprite { RelativeSizeAxes = Axes.Both }
};
AddStep("take screenshot", takeScreenshot);
}
private void takeScreenshot()
{
if (host.Window == null)
return;
host.TakeScreenshotAsync().ContinueWith(t => Schedule(() =>
{
var image = t.Result;
var tex = new Texture(image.Width, image.Height);
tex.SetData(new TextureUpload(new RawTexture(image.Width, image.Height, image.SavePixelData())));
display.Texture = tex;
}));
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Platform;
using osu.Framework.Testing;
using OpenTK;
using OpenTK.Graphics;
using SixLabors.ImageSharp;
namespace osu.Framework.Tests.Visual
{
public class TestCaseScreenshot : TestCase
{
[Resolved]
private GameHost host { get; set; }
private Sprite display;
[BackgroundDependencyLoader]
private void load()
{
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Masking = true,
BorderColour = Color4.Green,
BorderThickness = 2,
Child = display = new Sprite { RelativeSizeAxes = Axes.Both }
};
AddStep("take screenshot", takeScreenshot);
}
private void takeScreenshot() => host.TakeScreenshotAsync().ContinueWith(t => Schedule(() =>
{
var image = t.Result;
var tex = new Texture(image.Width, image.Height);
tex.SetData(new TextureUpload(new RawTexture(image.Width, image.Height, image.SavePixelData())));
display.Texture = tex;
}));
}
}
| mit | C# |
78943a21d81fc6658a5be485f354b7f925b4636e | Update osu.Game/Beatmaps/ControlPoints/IControlPoint.cs | peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu | osu.Game/Beatmaps/ControlPoints/IControlPoint.cs | osu.Game/Beatmaps/ControlPoints/IControlPoint.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.Beatmaps.ControlPoints
{
public interface IControlPoint
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
double Time { get; }
}
}
| // 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.Beatmaps.ControlPoints
{
public interface IControlPoint
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
public double Time { get; }
}
}
| mit | C# |
457f7e32c323d95383e5bb72e7229b98473f3ebd | Update update url | MatthiWare/UpdateLib | UpdateLib/TestApp/Program.cs | UpdateLib/TestApp/Program.cs | using MatthiWare.UpdateLib;
using MatthiWare.UpdateLib.Logging;
using MatthiWare.UpdateLib.Logging.Writers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
// we still want our updater to have visual styles in case of update cmd argument switch
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Updater.Instance
.ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml")
//.ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml")
.ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug)
.ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter()))
.ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter()))
.ConfigureUnsafeConnections(true)
.ConfigureCacheInvalidation(TimeSpan.FromSeconds(30))
.ConfigureUpdateNeedsAdmin(false)
.ConfigureInstallationMode(InstallationMode.Shared)
.Initialize();
Application.Run(new Form1());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
MessageBox.Show(e.ToString());
}
}
}
}
| using MatthiWare.UpdateLib;
using MatthiWare.UpdateLib.Logging;
using MatthiWare.UpdateLib.Logging.Writers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
// we still want our updater to have visual styles in case of update cmd argument switch
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Updater.Instance
//.ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml")
.ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml")
.ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug)
.ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter()))
.ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter()))
.ConfigureUnsafeConnections(true)
.ConfigureCacheInvalidation(TimeSpan.FromSeconds(30))
.ConfigureUpdateNeedsAdmin(false)
.ConfigureInstallationMode(InstallationMode.Shared)
.Initialize();
Application.Run(new Form1());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
MessageBox.Show(e.ToString());
}
}
}
}
| agpl-3.0 | C# |
956e303c5a245b6ed2ff74acf07da36679f4d982 | Delete a comma | imba-tjd/CSharp-Code-Repository | 单个文件的程序/pingt.cs | 单个文件的程序/pingt.cs | using System;
using System.Diagnostics;
// 对tcping的简单封装,自动使用443
class PingT
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("参数不正确");
Environment.Exit(1);
}
// 无论输入主机还是网址都能运行,后者会自动提取出主机;但为了使用Uri,又要当输入前者时加上协议
string url = args[0].Trim();
if (!url.StartsWith("http"))
url = "http://" + url;
string host = new Uri(url).Host;
Process.Start(new ProcessStartInfo("cmd", $"/C tcping -n 8 {host} 443") { UseShellExecute = false }).WaitForExit();
}
}
| using System;
using System.Diagnostics;
// 对tcping的简单封装,自动使用443
class PingT
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("参数不正确");
Environment.Exit(1);
}
// 无论输入主机还是网址都能运行,后者会自动提取出主机,;但为了使用Uri,又要当输入前者时加上协议
string url = args[0].Trim();
if (!url.StartsWith("http"))
url = "http://" + url;
string host = new Uri(url).Host;
Process.Start(new ProcessStartInfo("cmd", $"/C tcping -n 8 {host} 443") { UseShellExecute = false }).WaitForExit();
}
}
| mit | C# |
d3c58c848deba41d97cb71fbce36b4d89a515555 | Add licence header | naoey/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,2yangk23/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,peppy/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,Frontear/osuKyzer,peppy/osu-new,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,Drezi126/osu,smoogipooo/osu,ppy/osu,ppy/osu,peppy/osu,johnneijzen/osu,Nabile-Rahmani/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu | osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapProcessor.cs | osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapProcessor.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Beatmaps
{
internal class CatchBeatmapProcessor : BeatmapProcessor<CatchBaseHit>
{
public override void PostProcess(Beatmap<CatchBaseHit> beatmap)
{
if (beatmap.ComboColors.Count == 0)
return;
int comboIndex = 0;
int colourIndex = 0;
CatchBaseHit lastObj = null;
foreach (var obj in beatmap.HitObjects)
{
if (obj.NewCombo)
{
if (lastObj != null) lastObj.LastInCombo = true;
comboIndex = 0;
colourIndex = (colourIndex + 1) % beatmap.ComboColors.Count;
}
obj.ComboIndex = comboIndex++;
obj.ComboColour = beatmap.ComboColors[colourIndex];
lastObj = obj;
}
}
}
}
| using osu.Game.Beatmaps;
using osu.Game.Rulesets.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Beatmaps
{
internal class CatchBeatmapProcessor : BeatmapProcessor<CatchBaseHit>
{
public override void PostProcess(Beatmap<CatchBaseHit> beatmap)
{
if (beatmap.ComboColors.Count == 0)
return;
int comboIndex = 0;
int colourIndex = 0;
CatchBaseHit lastObj = null;
foreach (var obj in beatmap.HitObjects)
{
if (obj.NewCombo)
{
if (lastObj != null) lastObj.LastInCombo = true;
comboIndex = 0;
colourIndex = (colourIndex + 1) % beatmap.ComboColors.Count;
}
obj.ComboIndex = comboIndex++;
obj.ComboColour = beatmap.ComboColors[colourIndex];
lastObj = obj;
}
}
}
}
| mit | C# |
e7367377ad6a29abc7efc8fb48bee8c709f3d948 | Fix test on OSX | BlueMountainCapital/Deedle,AtwooTM/Deedle,buybackoff/Deedle,BlueMountainCapital/Deedle,buybackoff/Deedle,AtwooTM/Deedle,caioproiete/Deedle,filmor/Deedle,tpetricek/Deedle,filmor/Deedle,buybackoff/Deedle,tpetricek/Deedle,filmor/Deedle,caioproiete/Deedle,Dependencies/Deedle,jeyoor/Deedle,BlueMountainCapital/Deedle,jeyoor/Deedle,tpetricek/Deedle,Dependencies/Deedle,jeyoor/Deedle,AtwooTM/Deedle,caioproiete/Deedle,Dependencies/Deedle | tests/Deedle.CSharp.Tests/Frame.cs | tests/Deedle.CSharp.Tests/Frame.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Deedle;
using System.Runtime.CompilerServices;
using System.IO;
namespace Deedle.CSharp.Tests
{
/* ----------------------------------------------------------------------------------
* Test calling Frame.Zip from C#
* --------------------------------------------------------------------------------*/
public class FrameZipTests
{
public static Frame<int, string> LoadMSFT([CallerFilePath] string source = "")
{
var file = Path.Combine(Path.GetDirectoryName(source), ".." + Path.DirectorySeparatorChar + "Deedle.Tests" + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + "MSFT.csv");
return Frame.ReadCsv(file, inferRows:10);
}
[Test]
public static void CanSubtractNumericalValues()
{
var df = LoadMSFT();
var actual = df.Zip<float, float, float>(df, (n1, n2) => n1 - n2).GetAllValues<float>().Sum();
Assert.AreEqual(0.0, actual);
}
}
/* ----------------------------------------------------------------------------------
* Test data frame dynamic
* --------------------------------------------------------------------------------*/
public class DynamicFrameTests
{
[Test]
public static void CanAddSeriesDynamically()
{
for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right
{
var df =
new FrameBuilder.Columns<int, string> {
{ "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.4} }.Series }
}.Frame;
dynamic dfd = df;
dfd.Test1 = new[] { 1, 2 };
dfd.Test2 = df.GetSeries<double>("Test");
dfd.Test3 = new Dictionary<int, string> { { 1, "A" }, { 2, "B" } };
var row = df.Rows[2];
Assert.AreEqual(22.4, row["Test"]);
Assert.AreEqual(2, row["Test1"]);
Assert.AreEqual(22.4, row["Test2"]);
Assert.AreEqual("B", ((KeyValuePair<int, string>)row["Test3"]).Value);
}
}
[Test]
public static void CanGetSeriesDynamically()
{
for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right
{
var df =
new FrameBuilder.Columns<int, string> {
{ "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.2} }.Series }
}.Frame;
dynamic dfd = df;
Series<int, double> s0 = dfd.Test;
dynamic s1 = dfd.Test;
Assert.AreEqual(11.1, s0[1]);
Assert.AreEqual(11.1, s1[1]);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Deedle;
using System.Runtime.CompilerServices;
using System.IO;
namespace Deedle.CSharp.Tests
{
/* ----------------------------------------------------------------------------------
* Test calling Frame.Zip from C#
* --------------------------------------------------------------------------------*/
public class FrameZipTests
{
public static Frame<int, string> LoadMSFT([CallerFilePath] string source = "")
{
var file = Path.Combine(Path.GetDirectoryName(source), @"..\Deedle.Tests\data\MSFT.csv");
return Frame.ReadCsv(file, inferRows:10);
}
[Test]
public static void CanSubtractNumericalValues()
{
var df = LoadMSFT();
var actual = df.Zip<float, float, float>(df, (n1, n2) => n1 - n2).GetAllValues<float>().Sum();
Assert.AreEqual(0.0, actual);
}
}
/* ----------------------------------------------------------------------------------
* Test data frame dynamic
* --------------------------------------------------------------------------------*/
public class DynamicFrameTests
{
[Test]
public static void CanAddSeriesDynamically()
{
for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right
{
var df =
new FrameBuilder.Columns<int, string> {
{ "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.4} }.Series }
}.Frame;
dynamic dfd = df;
dfd.Test1 = new[] { 1, 2 };
dfd.Test2 = df.GetSeries<double>("Test");
dfd.Test3 = new Dictionary<int, string> { { 1, "A" }, { 2, "B" } };
var row = df.Rows[2];
Assert.AreEqual(22.4, row["Test"]);
Assert.AreEqual(2, row["Test1"]);
Assert.AreEqual(22.4, row["Test2"]);
Assert.AreEqual("B", ((KeyValuePair<int, string>)row["Test3"]).Value);
}
}
[Test]
public static void CanGetSeriesDynamically()
{
for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right
{
var df =
new FrameBuilder.Columns<int, string> {
{ "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.2} }.Series }
}.Frame;
dynamic dfd = df;
Series<int, double> s0 = dfd.Test;
dynamic s1 = dfd.Test;
Assert.AreEqual(11.1, s0[1]);
Assert.AreEqual(11.1, s1[1]);
}
}
}
}
| bsd-2-clause | C# |
dee514939f5e97f9f88a6f05df3ae6ae7364e70c | Move to modern nuget. Make Sprite compile by stubbing missing interface methods. | eylvisaker/AgateLib | AgateLib.Tests/UnitTests/Extensions/ListExtensions.cs | AgateLib.Tests/UnitTests/Extensions/ListExtensions.cs | using System.Collections.Generic;
using AgateLib.Extensions.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.Extensions
{
[TestClass]
public class ListExtensions
{
[TestMethod]
public void SortPrimitives()
{
List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 };
Assert.AreEqual(10, li.Count);
li.InsertionSort();
for (int i = 0; i < li.Count; i++)
Assert.AreEqual(i + 1, li[i]);
}
[TestMethod]
public void InsertionSortTest()
{
List<int> list = new List<int> { 4, 2, 3, 1, 6, 7, 8, 9 };
list.InsertionSort();
Assert.AreEqual(1, list[0]);
Assert.AreEqual(9, list[list.Count - 1]);
}
}
}
| using System.Collections.Generic;
using AgateLib.Extensions.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AgateLib.UnitTests.Extensions
{
[TestClass]
public class ListExtensions
{
[TestMethod]
public void SortPrimitives()
{
List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 };
Assert.AreEqual(10, li.Count);
li.InsertionSort();
for (int i = 0; i < li.Count; i++)
Assert.AreEqual(i + 1, li[i]);
}
}
}
| mit | C# |
ac6dd367e638298e1fb832af208d66ba757b217f | Update to version number | ForkandBeard/Alferd-Spritesheet-Unpacker | ASU/Properties/AssemblyInfo.cs | ASU/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("ASU")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ASU")]
[assembly: AssemblyCopyright("Copyright © www.forkandbeard.co.uk 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e203a411-3418-4854-8dd6-feee98945489")]
// 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("14.0.0.0")]
[assembly: AssemblyFileVersion("14.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ASU")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ASU")]
[assembly: AssemblyCopyright("Copyright © www.forkandbeard.co.uk 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e203a411-3418-4854-8dd6-feee98945489")]
// 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("13.0.0.0")]
[assembly: AssemblyFileVersion("13.0.0.0")]
| mit | C# |
e518dd8a960659ed0ec711f95e58331ed254c7f4 | Add new file userAuth.cpl/Droid/MainActivity.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | userAuth.cpl/Droid/MainActivity.cs | userAuth.cpl/Droid/MainActivity.cs |