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 |
|---|---|---|---|---|---|---|---|---|
dfce0e54251bdf4c49e958f9f05234fb6b86b23d | improve comments | jeromerg/NCase,jeromerg/NCase,jeromerg/NCase | src/NCase.Autofac/NCaseModule.cs | src/NCase.Autofac/NCaseModule.cs | using Autofac;
using NCase.Api;
using NCase.Api.Vis;
using NCase.Imp;
using NCase.Imp.Vis;
using NDsl.Autofac;
namespace NCase.Autofac
{
public class NCaseModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
// modules
builder.RegisterModule<CoreModule>();
builder.RegisterModule<RecPlayModule>();
// Parser (visit IToken flat-list and produces INode AST)
builder.RegisterType<ParserDirector>() .As<IParserDirector>() .InstancePerDependency();
builder.RegisterType<ParserVisitors>() .AsImplementedInterfaces().SingleInstance();
// Cases generator (lazily visit INode AST and construct all cases one by one)
builder.RegisterType<CaseGeneratorDirector>() .As<ICaseGeneratorDirector>().InstancePerDependency();
builder.RegisterType<CaseGeneratorVisitors>() .AsImplementedInterfaces().SingleInstance();
// Replay visitors (visit the INode in a case-set and prepare for replay, i.e. load responses into the interceptors)
builder.RegisterType<ReplayDirector>() .As<IReplayDirector>() .InstancePerDependency();
builder.RegisterType<ReplayVisitors>() .AsImplementedInterfaces().SingleInstance();
// case builder
builder.RegisterType<CaseBuilder>().As<ICaseBuilder>().InstancePerDependency();
}
}
}
| using Autofac;
using NCase.Api;
using NCase.Api.Vis;
using NCase.Imp;
using NCase.Imp.Vis;
using NDsl.Autofac;
namespace NCase.Autofac
{
public class NCaseModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
// modules
builder.RegisterModule<CoreModule>();
builder.RegisterModule<RecPlayModule>();
// directors
builder.RegisterType<CaseGeneratorDirector>() .As<ICaseGeneratorDirector>().InstancePerDependency();
builder.RegisterType<ParserDirector>() .As<IParserDirector>() .InstancePerDependency();
builder.RegisterType<ReplayDirector>() .As<IReplayDirector>() .InstancePerDependency();
// visitors
builder.RegisterType<CaseGeneratorVisitors>() .AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ParserVisitors>() .AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ReplayVisitors>() .AsImplementedInterfaces().SingleInstance();
// case builder
builder.RegisterType<CaseBuilder>().As<ICaseBuilder>().InstancePerDependency();
}
}
}
| apache-2.0 | C# |
9448ed557d0d488c86de4d0fa786f60188d17306 | Remove unnecessary conditions | farity/farity | Farity.Tests/SubtractTests.cs | Farity.Tests/SubtractTests.cs | using System;
using Xunit;
namespace Farity.Tests
{
public class SubtractTests
{
[Theory]
[InlineData(1, 2)]
[InlineData(-1, 2)]
public void SubtractSubtractsTwoIntegers(int a, int b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1L, 2L)]
[InlineData(-1L, 2L)]
public void SubtractSubtractsTwoLongs(long a, long b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1U, 2U)]
[InlineData(12U, 2U)]
public void SubtractSubtractsTwoUints(uint a, uint b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1UL, 2UL)]
[InlineData(11UL, 2UL)]
public void SubtractSubtractsTwoUlongs(ulong a, ulong b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Fact]
public void SubtractSubtractsTwoDecimals()
{
var a = 2.33m;
var b = 1.99m;
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
}
} | using System;
using Xunit;
namespace Farity.Tests
{
public class SubtractTests
{
[Theory]
[InlineData(1, 2)]
[InlineData(-1, 2)]
public void SubtractSubtractsTwoIntegers(int a, int b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1L, 2L)]
[InlineData(-1L, 2L)]
public void SubtractSubtractsTwoLongs(long a, long b)
{
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1U, 2U)]
[InlineData(12U, 2U)]
public void SubtractSubtractsTwoUints(uint a, uint b)
{
var expected = a > b ? a - b : 0;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(1UL, 2UL)]
[InlineData(11UL, 2UL)]
public void SubtractSubtractsTwoUlongs(ulong a, ulong b)
{
var expected = a > b ? a - b : 0;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
[Fact]
public void SubtractSubtractsTwoDecimals()
{
var a = 2.33m;
var b = 1.99m;
var expected = a - b;
var actual = F.Subtract(a, b);
Assert.Equal(expected, actual);
}
}
} | mit | C# |
fbae55b0c231b7b113431a23f08df8a2a7327d06 | Remove buttons home view | RateMyPoPo/website,RateMyPoPo/website,RateMyPoPo/website,RateMyPoPo/website | FedUp/Views/Home/Index.cshtml | FedUp/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>FedUp</h1>
<p class="lead">Empowering citizens in police interactions via mobile evidence collection. </p>
<p><a href="https://github.com/RateMyPoPo" class="btn btn-primary btn-lg">Check out our github »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Geolocation</h2>
<p>
Records, stores, and maps out gps data during the time of police interaction.
</div>
<div class="col-md-4">
<h2>Audio Recording</h2>
<p>Verbal harassment or improper police procedure is often overlooked. Audio is a crucial piece of forensic evidence, but usually missing from security and police footage.</p>
</div>
<div class="col-md-4">
<h2>Case Folders</h2>
<p>Automatically uploads case and client folders to Dropbox. This insures reliable storage of user or wittness evidence without tampering or confiscation by the police.</p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>FedUp</h1>
<p class="lead">Empowering citizens in police interactions via mobile evidence collection of geolocation, timestamps, and audio.</p>
<p><a href="https://github.com/RateMyPoPo" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Frictionless Experience</h2>
<p>
??idk??
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Audio Recording</h2>
<p>Verbal harassment or improper police procedure is often looked over and lost. Audio is a crucial piece of forensic evidence, but usually missing from security and police footage.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Case Folders</h2>
<p>FedUp automatically uploads to case and client folders stored in the cloud. This insures reliable storage of user or wittness evidence without tampering or confiscation by the police.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | apache-2.0 | C# |
370ccc8c28725b240222e6ed49980bc179ef4ed9 | Add extension method for convert colore color to WinForms color | CoraleStudios/Colore,WolfspiritM/Colore | Corale.Colore.WinForms/Extensions.cs | Corale.Colore.WinForms/Extensions.cs | // <copyright file="Extensions.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
namespace Corale.Colore.WinForms
{
using Corale.Colore.Annotations;
using ColoreColor = Corale.Colore.Core.Color;
using SystemColor = System.Drawing.Color;
/// <summary>
/// Extension methods for integrating Colore with WinForms.
/// </summary>
[PublicAPI]
public static class Extensions
{
/// <summary>
/// Converts a System.Drawing <see cref="SystemColor" /> to a
/// Colore <see cref="ColoreColor" />.
/// </summary>
/// <param name="source">The color to convert.</param>
/// <returns>
/// A <see cref="ColoreColor" /> representing the
/// given <see cref="SystemColor" />.
/// </returns>
public static ColoreColor ToColoreColor(this SystemColor source)
{
return new ColoreColor(source.R, source.G, source.B);
}
/// <summary>
/// Converts a Colore <see cref="ColoreColor" /> to a
/// System.Drawing <see cref="WpfColor" />
/// </summary>
/// <param name="source">The color to convert.</param>
/// <returns>
/// A <see cref="SystemColor" /> representing the
/// given <see cref="ColoreColor" />.
/// </returns>
public static SystemColor ToSystemColor(this ColoreColor source)
{
return SystemColor.FromRgb(source.R, source.G, source.B);
}
}
}
| // <copyright file="Extensions.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
namespace Corale.Colore.WinForms
{
using Corale.Colore.Annotations;
using ColoreColor = Corale.Colore.Core.Color;
using SystemColor = System.Drawing.Color;
/// <summary>
/// Extension methods for integrating Colore with WinForms.
/// </summary>
[PublicAPI]
public static class Extensions
{
/// <summary>
/// Converts a System.Drawing <see cref="SystemColor" /> to a
/// Colore <see cref="ColoreColor" />.
/// </summary>
/// <param name="source">The color to convert.</param>
/// <returns>
/// A <see cref="ColoreColor" /> representing the
/// given <see cref="SystemColor" />.
/// </returns>
public static ColoreColor ToColoreColor(this SystemColor source)
{
return new ColoreColor(source.R, source.G, source.B);
}
}
}
| mit | C# |
931d742b2993841ac629a4995c440d3f91d2c01d | Fix cref. | chtoucas/Narvalo.NET,chtoucas/Narvalo.NET | src/Narvalo.Fx/Linq/Qperators.cs | src/Narvalo.Fx/Linq/Qperators.cs | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Linq
{
/// <summary>
/// Provides a set of static and extension methods for querying
/// objects that implement <see cref="System.Collections.Generic.IEnumerable{T}"/>.
/// </summary>
/// <remarks>
/// New LINQ operators:
/// - Projecting: SelectAny (deferred)
/// - Filtering: WhereAny (deferred)
/// - Set: Append (deferred), Prepend (deferred)
/// - Element: FirstOrNone, LastOrNone, SingleOrNone, ElementAtOrNone
/// - Aggregation: Aggregate (deferred)
/// - Quantifiers: IsEmpty
/// - Generation: EmptyIfNull
/// We have also operators accepting arguments in the Kleisli "category":
/// SelectWith (deferred), ZipWith (deferred), WhereBy (deferred), Fold, Reduce.
/// </remarks>
public static partial class Qperators { }
}
| // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Linq
{
/// <summary>
/// Provides a set of static and extension methods for querying
/// objects that implement <see cref="IEnumerable{T}"/>.
/// </summary>
/// <remarks>
/// New LINQ operators:
/// - Projecting: SelectAny (deferred)
/// - Filtering: WhereAny (deferred)
/// - Set: Append (deferred), Prepend (deferred)
/// - Element: FirstOrNone, LastOrNone, SingleOrNone, ElementAtOrNone
/// - Aggregation: Aggregate (deferred)
/// - Quantifiers: IsEmpty
/// - Generation: EmptyIfNull
/// We have also operators accepting arguments in the Kleisli "category":
/// SelectWith (deferred), ZipWith (deferred), WhereBy (deferred), Fold, Reduce.
/// </remarks>
public static partial class Qperators { }
}
| bsd-2-clause | C# |
374864a7aa7dd2fb829f7ec0ca3d343dbbd9e136 | Update version info | LambdaSix/InfiniMap,LambdaSix/InfiniMap | InfiniMap/Properties/AssemblyInfo.cs | InfiniMap/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("InfiniMap")]
[assembly: AssemblyDescription("Cubic-chunked map library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2014-2016 LambdaSix")]
[assembly: AssemblyProduct("InfiniMap")]
[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("b1ad1139-a54e-4e6f-88d0-84a124c53aa4")]
// 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.1.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("InfiniMap")]
[assembly: AssemblyDescription("Cubic-chunked map library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2014-2016 LambdaSix")]
[assembly: AssemblyProduct("InfiniMap")]
[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("b1ad1139-a54e-4e6f-88d0-84a124c53aa4")]
// 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.1.*")]
[assembly: AssemblyFileVersion("1.0.2.*")]
| mit | C# |
024edd228b7c470facac316530713616e735342c | Add missing "the" | ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework | osu.Framework/Input/States/MouseState.cs | osu.Framework/Input/States/MouseState.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.Extensions.TypeExtensions;
using osu.Framework.Input.StateChanges;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.States
{
public class MouseState
{
public readonly ButtonStates<MouseButton> Buttons = new ButtonStates<MouseButton>();
public Vector2 Scroll { get; set; }
public Vector2 Position { get; set; }
public bool IsPositionValid { get; set; } = true;
/// <summary>
/// The last input source to make a change to the state.
/// </summary>
public IInput LastSource { get; set; }
public bool IsPressed(MouseButton button) => Buttons.IsPressed(button);
public void SetPressed(MouseButton button, bool pressed) => Buttons.SetPressed(button, pressed);
public override string ToString()
{
string position = IsPositionValid ? $"({Position.X:F0},{Position.Y:F0})" : "(Invalid)";
return $@"{GetType().ReadableName()} {position} {Buttons} Scroll ({Scroll.X:F2},{Scroll.Y:F2})";
}
}
}
| // 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.Extensions.TypeExtensions;
using osu.Framework.Input.StateChanges;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.States
{
public class MouseState
{
public readonly ButtonStates<MouseButton> Buttons = new ButtonStates<MouseButton>();
public Vector2 Scroll { get; set; }
public Vector2 Position { get; set; }
public bool IsPositionValid { get; set; } = true;
/// <summary>
/// The last input source to make a change to state.
/// </summary>
public IInput LastSource { get; set; }
public bool IsPressed(MouseButton button) => Buttons.IsPressed(button);
public void SetPressed(MouseButton button, bool pressed) => Buttons.SetPressed(button, pressed);
public override string ToString()
{
string position = IsPositionValid ? $"({Position.X:F0},{Position.Y:F0})" : "(Invalid)";
return $@"{GetType().ReadableName()} {position} {Buttons} Scroll ({Scroll.X:F2},{Scroll.Y:F2})";
}
}
}
| mit | C# |
45b4fc9201849483d0d08ec770c6c5b89d413d6a | Add xmldoc | NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,ppy/osu,UselessToucan/osu,ZLima12/osu,ppy/osu | osu.Game.Rulesets.Osu/OsuInputManager.cs | osu.Game.Rulesets.Osu/OsuInputManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu
{
public class OsuInputManager : RulesetInputManager<OsuAction>
{
public IEnumerable<OsuAction> PressedActions => KeyBindingContainer.PressedActions;
public bool AllowUserPresses
{
set => ((OsuKeyBindingContainer)KeyBindingContainer).AllowUserPresses = value;
}
/// <summary>
/// Whether the user's cursor movement events should be accepted.
/// Can be used to block only movement while still accepting button input.
/// </summary>
public bool AllowUserCursorMovement { get; set; } = true;
protected override RulesetKeyBindingContainer CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new OsuKeyBindingContainer(ruleset, variant, unique);
public OsuInputManager(RulesetInfo ruleset)
: base(ruleset, 0, SimultaneousBindingMode.Unique)
{
}
protected override bool Handle(UIEvent e)
{
if (e is MouseMoveEvent && !AllowUserCursorMovement) return false;
return base.Handle(e);
}
private class OsuKeyBindingContainer : RulesetKeyBindingContainer
{
public bool AllowUserPresses = true;
public OsuKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override bool Handle(UIEvent e)
{
if (!AllowUserPresses) return false;
return base.Handle(e);
}
}
}
public enum OsuAction
{
[Description("Left button")]
LeftButton,
[Description("Right button")]
RightButton
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.ComponentModel;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu
{
public class OsuInputManager : RulesetInputManager<OsuAction>
{
public IEnumerable<OsuAction> PressedActions => KeyBindingContainer.PressedActions;
public bool AllowUserPresses
{
set => ((OsuKeyBindingContainer)KeyBindingContainer).AllowUserPresses = value;
}
public bool AllowUserCursorMovement { get; set; } = true;
protected override RulesetKeyBindingContainer CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new OsuKeyBindingContainer(ruleset, variant, unique);
public OsuInputManager(RulesetInfo ruleset)
: base(ruleset, 0, SimultaneousBindingMode.Unique)
{
}
protected override bool Handle(UIEvent e)
{
if (e is MouseMoveEvent && !AllowUserCursorMovement) return false;
return base.Handle(e);
}
private class OsuKeyBindingContainer : RulesetKeyBindingContainer
{
public bool AllowUserPresses = true;
public OsuKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override bool Handle(UIEvent e)
{
if (!AllowUserPresses) return false;
return base.Handle(e);
}
}
}
public enum OsuAction
{
[Description("Left button")]
LeftButton,
[Description("Right button")]
RightButton
}
}
| mit | C# |
f419518887b2d840cb06f80f04bc2393985fc903 | Make comment xmldoc | smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,naoey/osu,naoey/osu,smoogipooo/osu,smoogipoo/osu,EVAST9919/osu,naoey/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu,DrabWeb/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,ppy/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,Nabile-Rahmani/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,DrabWeb/osu,johnneijzen/osu,Frontear/osuKyzer,NeoAdonis/osu,peppy/osu-new | osu.Game/Rulesets/Mods/IApplicableMod.cs | osu.Game/Rulesets/Mods/IApplicableMod.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// The base interface for a mod which can be applied in some way.
/// If this is not implemented by a mod, it will not be available for use in-game.
/// </summary>
public interface IApplicableMod
{
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Rulesets.Mods
{
// The base interface for a mod which can be applied in some way.
public interface IApplicableMod
{
}
}
| mit | C# |
928bce8fcdee3daf785539cd068b48274eae30e0 | Fix crash when attempting to watch a replay when the storage file doesn't exist | ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game/Scoring/LegacyDatabasedScore.cs | osu.Game/Scoring/LegacyDatabasedScore.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;
namespace osu.Game.Scoring
{
public class LegacyDatabasedScore : Score
{
public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
{
ScoreInfo = score;
string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();
if (replayFilename == null)
return;
using (var stream = store.GetStream(replayFilename))
{
if (stream == null)
return;
Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
using osu.Game.Rulesets;
using osu.Game.Scoring.Legacy;
namespace osu.Game.Scoring
{
public class LegacyDatabasedScore : Score
{
public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store)
{
ScoreInfo = score;
string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath();
if (replayFilename == null)
return;
using (var stream = store.GetStream(replayFilename))
Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay;
}
}
}
| mit | C# |
ad985c526682817f37b3d2ea82cc97eb637146da | Update CMSG_LOGINREQUEST.cs | minhjemmesiden/Wakfusharp | Network/Packets/CMSG_LOGINREQUEST.cs | Network/Packets/CMSG_LOGINREQUEST.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WakSharp.Network.Packets
{
public class CMSG_LOGINREQUEST : WakfuClientMessage
{
public string Username { get; set; }
public string Password { get; set; }
public CMSG_LOGINREQUEST(byte[] data)
: base(data)
{
/* var b = new byte[data.Length - 5];
b = this.Reader.ReadBytes(data.Length - 5);
b = Utilities.Crypto.CryptoManager.RSA.Decrypt(b, false);
var decoded = new IO.BigEndianReader(b);
var rsaVerification = decoded.ReadULong();
var username = decoded.ReadString();
var password = decoded.ReadString();
Console.Out.WriteLine("3");
*/
this.Username = "admin";
this.Password = "admin";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WakSharp.Network.Packets
{
public class CMSG_LOGINREQUEST : WakfuClientMessage
{
public string Username { get; set; }
public string Password { get; set; }
public CMSG_LOGINREQUEST(byte[] data)
: base(data)
{
/* var b = new byte[data.Length - 5];
b = this.Reader.ReadBytes(data.Length - 5);
b = Utilities.Crypto.CryptoManager.RSA.Decrypt(b, false);
var decoded = new IO.BigEndianReader(b);
var rsaVerification = decoded.ReadULong();
var username = decoded.ReadString();
var password = decoded.ReadString();
Console.Out.WriteLine("3");
*/
this.Username = "spil778";
this.Password = "czu26ueh";
}
}
}
| mit | C# |
0c7739e00f99070305d5b5a3c3a8ffad72d699bd | Add AutoPlay property | modplug/LottieXamarin,fabionuno/LottieXamarin,martijn00/LottieXamarin,fabionuno/LottieXamarin,martijn00/LottieXamarin | Lottie.Forms/AnimationView.cs | Lottie.Forms/AnimationView.cs | using System;
using Xamarin.Forms;
namespace Lottie.Forms
{
public class AnimationView : View
{
public static readonly BindableProperty ProgressProperty = BindableProperty.Create(nameof(Progress),
typeof(float), typeof(AnimationView), default(float));
public static readonly BindableProperty LoopProperty = BindableProperty.Create(nameof(Loop), typeof(bool),
typeof(AnimationView), default(bool));
public static readonly BindableProperty IsPlayingProperty = BindableProperty.Create(nameof(IsPlaying),
typeof(bool), typeof(AnimationView), default(bool));
public static readonly BindableProperty DurationProperty = BindableProperty.Create(nameof(Duration),
typeof(TimeSpan), typeof(AnimationView), default(TimeSpan));
public static readonly BindableProperty AnimationProperty = BindableProperty.Create(nameof(Animation),
typeof(string), typeof(AnimationView), default(string));
public static readonly BindableProperty AutoPlayProperty = BindableProperty.Create(nameof(AutoPlay),
typeof(bool), typeof(AnimationView), default(bool));
public float Progress
{
get { return (float) GetValue(ProgressProperty); }
set { SetValue(ProgressProperty, value); }
}
public string Animation
{
get { return (string) GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
public TimeSpan Duration
{
get { return (TimeSpan) GetValue(DurationProperty); }
set { SetValue(DurationProperty, value); }
}
public bool Loop
{
get { return (bool) GetValue(LoopProperty); }
set { SetValue(LoopProperty, value); }
}
public bool AutoPlay
{
get { return (bool)GetValue(AutoPlayProperty); }
set { SetValue(AutoPlayProperty, value); }
}
public bool IsPlaying
{
get { return (bool) GetValue(IsPlayingProperty); }
set { SetValue(IsPlayingProperty, value); }
}
public event EventHandler OnPlay;
public void Play()
{
OnPlay?.Invoke(this, new EventArgs());
}
public event EventHandler OnPause;
public void Pause()
{
OnPause?.Invoke(this, new EventArgs());
}
}
} | using System;
using Xamarin.Forms;
namespace Lottie.Forms
{
public class AnimationView : View
{
public static readonly BindableProperty ProgressProperty = BindableProperty.Create(nameof(Progress),
typeof(float), typeof(AnimationView), default(float));
public static readonly BindableProperty LoopProperty = BindableProperty.Create(nameof(Loop), typeof(bool),
typeof(AnimationView), default(bool));
public static readonly BindableProperty IsPlayingProperty = BindableProperty.Create(nameof(IsPlaying),
typeof(bool), typeof(AnimationView), default(bool));
public static readonly BindableProperty DurationProperty = BindableProperty.Create(nameof(Duration),
typeof(TimeSpan), typeof(AnimationView), default(TimeSpan));
public static readonly BindableProperty AnimationProperty = BindableProperty.Create(nameof(Animation),
typeof(string), typeof(AnimationView), default(string));
public float Progress
{
get { return (float) GetValue(ProgressProperty); }
set { SetValue(ProgressProperty, value); }
}
public string Animation
{
get { return (string) GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
public TimeSpan Duration
{
get { return (TimeSpan) GetValue(DurationProperty); }
set { SetValue(DurationProperty, value); }
}
public bool Loop
{
get { return (bool) GetValue(LoopProperty); }
set { SetValue(LoopProperty, value); }
}
public bool IsPlaying
{
get { return (bool) GetValue(IsPlayingProperty); }
set { SetValue(IsPlayingProperty, value); }
}
public event EventHandler OnPlay;
public void Play()
{
OnPlay?.Invoke(this, new EventArgs());
}
public event EventHandler OnPause;
public void Pause()
{
OnPause?.Invoke(this, new EventArgs());
}
}
} | apache-2.0 | C# |
d1d7b1bb59c018631837e783a67553f8230389e1 | revert to before branch | Earlz/lucidmvc,Earlz/lucidmvc | BarelyMVC/Routing/RedirectHandler.cs | BarelyMVC/Routing/RedirectHandler.cs | /*
Copyright (c) 2010 - 2012 Jordan "Earlz/hckr83" Earls <http://lastyearswishes.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
namespace Earlz.BarelyMVC
{
public class RedirectHandler : BareHttpHandler
{
string Url;
bool Permanent;
/// <summary>
/// Sends a redirect to the specified URL.
/// If permanent is true, will send a 301 permanent redirect rather than a 302
/// </summary>
public RedirectHandler (bool permanent, string url)
{
Url=url;
Permanent=permanent;
}
public override Earlz.BarelyMVC.ViewEngine.IBarelyView Get()
{
if(Permanent)
{
//no support for 301s built into ASP.Net
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",Url);
Context.ApplicationInstance.CompleteRequest();
}
else
{
Response.Redirect(Url, true);
}
return null;
}
}
}
| /*
Copyright (c) 2010 - 2012 Jordan "Earlz/hckr83" Earls <http://lastyearswishes.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
namespace Earlz.BarelyMVC
{
public class RedirectHandler : BareHttpHandler
{
string Url;
bool Permanent;
/// <summary>
/// Sends a redirect to the specified URL.
/// If permanent is true, will send a 301 permanent redirect rather than a 302
/// </summary>
public RedirectHandler (bool permanent, string url)
{
Url=url;
Permanent=permanent;
}
public override Earlz.BarelyMVC.ViewEngine.IBarelyView Get()
{
if(Permanent)
{
//no support for 301s built into ASP.Net
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",Url);
Context.ApplicationInstance.CompleteRequest();
}
else
{
Response.Redirect(Url, true);
}
return null;
}
}
}
| bsd-3-clause | C# |
711c2dd1ac1dfdb5a898065e9d66519c2b66f355 | Update GetFile.cs | muhammedikinci/FuzzyCore | FuzzyCore/CommandClasses/GetFile.cs | FuzzyCore/CommandClasses/GetFile.cs | using FuzzyCore.Data;
using FuzzyCore.Server;
using System;
using System.IO;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
private String FilePath;
private String FileName;
private JsonCommand mCommand;
public GetFile(Data.JsonCommand Command)
{
FilePath = Command.FilePath;
FileName = Command.Text;
this.mCommand = Command;
}
bool FileControl()
{
FileInfo mfileInfo = new FileInfo(FilePath + "/" + FileName);
return mfileInfo.Exists;
}
public byte[] GetFileBytes()
{
if (FileControl())
{
byte[] file = File.ReadAllBytes(FilePath + "/" + FileName);
return file;
}
return new byte[0];
}
public string GetFileText()
{
if (FileControl())
{
return File.ReadAllText(FilePath + "/" + FileName);
}
return "";
}
}
}
| using FuzzyCore.Data;
using FuzzyCore.Server;
using System;
using System.IO;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
private String FilePath;
private String FileName;
private JsonCommand mCommand;
public GetFile(Data.JsonCommand Command)
{
FilePath = Command.FilePath;
FileName = Command.Text;
this.mCommand = Command;
}
bool FileControl()
{
FileInfo mfileInfo = new FileInfo(FilePath);
return mfileInfo.Exists;
}
public byte[] GetFileBytes()
{
if (FileControl())
{
byte[] file = File.ReadAllBytes(FilePath + "/" + FileName);
return file;
}
return new byte[0];
}
public string GetFileText()
{
if (FileControl())
{
return File.ReadAllText(FilePath + "/" + FileName);
}
return "";
}
}
}
| mit | C# |
e33332c4aedb5b92b286748a447001d85697329b | Fix datetime unit test | smarkets/IronSmarkets | IronSmarkets.Tests/DateTimeTests.cs | IronSmarkets.Tests/DateTimeTests.cs | // Copyright (c) 2011 Smarkets Limited
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using Xunit;
using IronSmarkets.Data;
namespace IronSmarkets.Tests
{
public sealed class DateTimeTests
{
[Fact]
public void MicrosecondsRoundtrip()
{
var dt = MicrosecondNow();
var dt2 = MicrosecondNow().AddDays(1);
Assert.Equal(dt, SetoMap.FromMicroseconds(SetoMap.ToMicroseconds(dt)));
Assert.NotEqual(dt2, SetoMap.FromMicroseconds(SetoMap.ToMicroseconds(dt)));
Assert.Equal((ulong)9800, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(9800)));
Assert.Equal((ulong)1, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(1)));
Assert.NotEqual((ulong)1, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(2)));
}
/// <summary>
/// Provides a DateTime with microsecond resolution (instead
/// of 100-nanoseconds by default)
/// </summary>
private DateTime MicrosecondNow()
{
var dt = DateTime.UtcNow;
return new DateTime(dt.Ticks - (dt.Ticks % 10), DateTimeKind.Utc);
}
}
}
| // Copyright (c) 2011 Smarkets Limited
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using Xunit;
using IronSmarkets.Data;
namespace IronSmarkets.Tests
{
public sealed class DateTimeTests
{
[Fact]
public void MicrosecondsRoundtrip()
{
var dt = MicrosecondNow();
var dt2 = MicrosecondNow().AddDays(1);
Assert.Equal(dt, SetoMap.FromMicroseconds(SetoMap.ToMicroseconds(dt)));
Assert.NotEqual(dt2, SetoMap.FromMicroseconds(SetoMap.ToMicroseconds(dt)));
Assert.Equal((ulong)9800, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(9800)));
Assert.Equal((ulong)1, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(1)));
Assert.NotEqual((ulong)1, SetoMap.ToMicroseconds(SetoMap.FromMicroseconds(2)));
}
/// <summary>
/// Provides a DateTime with microsecond resolution (instead
/// of 100-nanoseconds by default)
/// </summary>
private DateTime MicrosecondNow()
{
var dt = DateTime.UtcNow;
return new DateTime(dt.Ticks - (dt.Ticks % 10));
}
}
}
| mit | C# |
78d027b8d11f38256eb56004f9f6f84f5a6767df | Put body data type check into switch statement | yojimbo87/ArangoDB-NET | src/Arango/Arango.Client/Protocol/Response.cs | src/Arango/Arango.Client/Protocol/Response.cs | using System;
using System.Net;
using Arango.fastJSON;
namespace Arango.Client.Protocol
{
internal class Response
{
internal int StatusCode { get; set; }
internal WebHeaderCollection Headers { get; set; }
internal string Body { get; set; }
internal DataType DataType { get; set; }
internal object Data { get; set; }
internal Exception Exception { get; set; }
internal AEerror Error { get; set; }
internal void DeserializeBody()
{
if (string.IsNullOrEmpty(Body))
{
DataType = DataType.Null;
Data = null;
}
else
{
var trimmedBody = Body.Trim();
switch (trimmedBody[0])
{
// body contains JSON array
case '[':
DataType = DataType.List;
break;
// body contains JSON object
case '{':
DataType = DataType.Document;
break;
default:
DataType = DataType.Primitive;
break;
}
Data = JSON.Parse(trimmedBody);
}
}
}
}
| using System;
using System.Net;
using Arango.fastJSON;
namespace Arango.Client.Protocol
{
internal class Response
{
internal int StatusCode { get; set; }
internal WebHeaderCollection Headers { get; set; }
internal string Body { get; set; }
internal DataType DataType { get; set; }
internal object Data { get; set; }
internal Exception Exception { get; set; }
internal AEerror Error { get; set; }
internal void DeserializeBody()
{
if (string.IsNullOrEmpty(Body))
{
DataType = DataType.Null;
Data = null;
}
else
{
var trimmedBody = Body.Trim();
// body contains JSON array
if (trimmedBody[0] == '[')
{
DataType = DataType.List;
}
// body contains JSON object
else if (trimmedBody[0] == '{')
{
DataType = DataType.Document;
}
else
{
DataType = DataType.Primitive;
}
Data = JSON.Parse(trimmedBody);
}
}
}
}
| mit | C# |
5e6a3321faa2ddc1665c6f3346b423d8326e4685 | Increase version | cap9/EEPhysics | EEPhysics/Properties/AssemblyInfo.cs | EEPhysics/Properties/AssemblyInfo.cs | using System.Runtime.InteropServices;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EEPhysics")]
[assembly: AssemblyDescription("A helper library for the game Everybody Edits for simulating player physics.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.4.6")]
[assembly: AssemblyFileVersion("1.4.4.6")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EEPhysics")]
[assembly: AssemblyDescription("A helper library for the game Everybody Edits for simulating player physics.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.4.5")]
[assembly: AssemblyFileVersion("1.4.4.5")]
| mit | C# |
ba6c5309e44adeafd2fce84b39cb629dec59b29a | Format date with user culture | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | SnittListan/Infrastructure/AutoMapperProfiles/MatchProfile.cs | SnittListan/Infrastructure/AutoMapperProfiles/MatchProfile.cs | using System.Threading;
using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;
namespace SnittListan.Infrastructure
{
public class MatchProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Match, MatchViewModel>()
.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture)))
.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
}
}
} | using AutoMapper;
using SnittListan.Models;
using SnittListan.ViewModels;
namespace SnittListan.Infrastructure
{
public class MatchProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Match, MatchViewModel>()
.ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToShortDateString()))
.ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore()))
.ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam)));
}
}
} | mit | C# |
ff5e6c0dcfeb8d9eb62ad5527486faa7af24af75 | Make DefaultComboColours a property | NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu | osu.Game/Skinning/SkinConfiguration.cs | osu.Game/Skinning/SkinConfiguration.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps.Formats;
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// An empty skin configuration.
/// </summary>
public class SkinConfiguration : IHasComboColours, IHasCustomColours
{
public readonly SkinInfo SkinInfo = new SkinInfo();
/// <summary>
/// Whether to allow <see cref="DefaultComboColours"/> as a fallback list for when no combo colours are provided.
/// </summary>
internal bool AllowDefaultComboColoursFallback = true;
public static List<Color4> DefaultComboColours { get; } = new List<Color4>
{
new Color4(255, 192, 0, 255),
new Color4(0, 202, 0, 255),
new Color4(18, 124, 255, 255),
new Color4(242, 24, 57, 255),
};
private List<Color4> comboColours = new List<Color4>();
public IReadOnlyList<Color4> ComboColours
{
get
{
if (comboColours.Count > 0)
return comboColours;
if (AllowDefaultComboColoursFallback)
return DefaultComboColours;
return null;
}
set => comboColours = value.ToList();
}
public void AddComboColours(params Color4[] colours) => comboColours.AddRange(colours);
public Dictionary<string, Color4> CustomColours { get; set; } = new Dictionary<string, Color4>();
public readonly Dictionary<string, string> ConfigDictionary = new Dictionary<string, string>();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps.Formats;
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// An empty skin configuration.
/// </summary>
public class SkinConfiguration : IHasComboColours, IHasCustomColours
{
public readonly SkinInfo SkinInfo = new SkinInfo();
/// <summary>
/// Whether to allow <see cref="DefaultComboColours"/> as a fallback list for when no combo colours are provided.
/// </summary>
internal bool AllowDefaultComboColoursFallback = true;
public static List<Color4> DefaultComboColours = new List<Color4>
{
new Color4(255, 192, 0, 255),
new Color4(0, 202, 0, 255),
new Color4(18, 124, 255, 255),
new Color4(242, 24, 57, 255),
};
private List<Color4> comboColours = new List<Color4>();
public IReadOnlyList<Color4> ComboColours
{
get
{
if (comboColours.Count > 0)
return comboColours;
if (AllowDefaultComboColoursFallback)
return DefaultComboColours;
return null;
}
set => comboColours = value.ToList();
}
public void AddComboColours(params Color4[] colours) => comboColours.AddRange(colours);
public Dictionary<string, Color4> CustomColours { get; set; } = new Dictionary<string, Color4>();
public readonly Dictionary<string, string> ConfigDictionary = new Dictionary<string, string>();
}
}
| mit | C# |
ecd934ae7a86c9852844180f54af819023460fbe | update the server dto | imranmomin/Hangfire.Firebase | Hangfire.Firebase/Entities/Server.cs | Hangfire.Firebase/Entities/Server.cs | using System;
namespace Hangfire.Firebase.Entities
{
internal class Server
{
public string Id { get; set; }
public int Workers { get; set; }
public string[] Queues { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime LastHeartbeat { get; set; }
}
} | using System;
namespace Hangfire.Firebase.Entities
{
internal class Server
{
public string Id { get; set; }
public string Name { get; set; }
public DateTime LastHeartbeat { get; set; }
}
} | mit | C# |
0048c192919400ad0da939c32406a5f3a876ed71 | Make ExceptionProblemDetails public | khellang/Middleware,khellang/Middleware | src/ProblemDetails/ExceptionProblemDetails.cs | src/ProblemDetails/ExceptionProblemDetails.cs | using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.ProblemDetails
{
public class ExceptionProblemDetails : StatusCodeProblemDetails
{
private static readonly string[] LineSeparators = { Environment.NewLine };
public ExceptionProblemDetails(Exception error) : this(error, StatusCodes.Status500InternalServerError)
{
}
public ExceptionProblemDetails(Exception error, int statusCode) : base(statusCode)
{
Detail = error.Message;
Instance = GetHelpLink(error);
StackTrace = GetStackTraceLines(error.StackTrace);
Title = error.GetType().FullName;
}
public string[] StackTrace { get; set; }
private static string GetHelpLink(Exception error)
{
var link = error.HelpLink;
if (string.IsNullOrEmpty(link))
{
return null;
}
if (Uri.TryCreate(link, UriKind.Absolute, out var result))
{
return result.ToString();
}
return null;
}
private static string[] GetStackTraceLines(string stackTrace)
{
if (string.IsNullOrEmpty(stackTrace))
{
return null;
}
return stackTrace.Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.ProblemDetails
{
internal class ExceptionProblemDetails : StatusCodeProblemDetails
{
private static readonly string[] LineSeparators = { Environment.NewLine };
public ExceptionProblemDetails(Exception error) : this(error, StatusCodes.Status500InternalServerError)
{
}
public ExceptionProblemDetails(Exception error, int statusCode) : base(statusCode)
{
Detail = error.Message;
Instance = GetHelpLink(error);
StackTrace = GetStackTraceLines(error.StackTrace);
Title = error.GetType().FullName;
}
public string[] StackTrace { get; set; }
private static string GetHelpLink(Exception error)
{
var link = error.HelpLink;
if (string.IsNullOrEmpty(link))
{
return null;
}
if (Uri.TryCreate(link, UriKind.Absolute, out var result))
{
return result.ToString();
}
return null;
}
private static string[] GetStackTraceLines(string stackTrace)
{
if (string.IsNullOrEmpty(stackTrace))
{
return null;
}
return stackTrace.Split(LineSeparators, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| mit | C# |
0e9bb6f5a7b93b3e6c18356c883a6fe372ae0fff | Update SDK version to v.4.0.1 | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.1"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.0"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| apache-2.0 | C# |
b91b9320af94cd34e90c6edaf082ab506b733c55 | make obsolete message more descriptive on constructor | dkackman/FakeHttp | FakeHttp/ResponseCallbacks.cs | FakeHttp/ResponseCallbacks.cs | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace FakeHttp
{
/// <summary>
/// Default implementations of the <see cref="IResponseCallbacks"/> interface that do nothing
/// </summary>
public class ResponseCallbacks : IResponseCallbacks
{
private readonly Func<string, string, bool> _paramFilter;
/// <summary>
/// This ctor is only meant for backwards compatiblity with the use of the paramFilter constructors
/// </summary>
/// <param name="paramFilter"></param>
[Obsolete("For backwards compatibility only. Implement IResponseCallbacks or derive from this class instead of using this constructor.")]
public ResponseCallbacks(Func<string, string, bool> paramFilter)
{
if (paramFilter == null) throw new ArgumentNullException("paramFilter");
_paramFilter = paramFilter;
}
/// <summary>
/// ctor
/// </summary>
public ResponseCallbacks()
{
}
/// <summary>
/// Called just before the response is returned. Update deserialized values as necessary
/// Primarily for cases where time based header values (like content expiration) need up to date values
/// </summary>
/// <param name="info">The deserialized <see cref="ResponseInfo"/></param>
public virtual void Deserialized(ResponseInfo info)
{
}
/// <summary>
/// Determines if a given query paramter should be excluded from serialziation
/// </summary>
/// <param name="name">The name of the Uri query parameter</param>
/// <param name="value">The value of the uri query parameter</param>
/// <returns>False</returns>
public virtual bool FilterParameter(string name, string value)
{
if (_paramFilter != null)
{
return _paramFilter(name, value);
}
return false;
}
/// <summary>
/// Called after content is retrieved from the actual service and before it is is saved to disk.
/// Primarily allows for response content to mask sensitive data (ex. SSN or other PII) before it is saved to storage
/// </summary>
/// <param name="response">The response</param>
/// <returns>The original content stream</returns>
public virtual async Task<Stream> Serializing(HttpResponseMessage response)
{
return await response.Content.ReadAsStreamAsync();
}
}
}
| using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace FakeHttp
{
/// <summary>
/// Default implementations of the <see cref="IResponseCallbacks"/> interface that do nothing
/// </summary>
public class ResponseCallbacks : IResponseCallbacks
{
private readonly Func<string, string, bool> _paramFilter;
/// <summary>
/// This ctor is only meant for backwards compatiblity with the use of the paramFilter constructors
/// </summary>
/// <param name="paramFilter"></param>
[Obsolete("Use constructor that takes IResponseCallbacks instead")]
public ResponseCallbacks(Func<string, string, bool> paramFilter)
{
if (paramFilter == null) throw new ArgumentNullException("paramFilter");
_paramFilter = paramFilter;
}
/// <summary>
/// ctor
/// </summary>
public ResponseCallbacks()
{
}
/// <summary>
/// Called just before the response is returned. Update deserialized values as necessary
/// Primarily for cases where time based header values (like content expiration) need up to date values
/// </summary>
/// <param name="info">The deserialized <see cref="ResponseInfo"/></param>
public virtual void Deserialized(ResponseInfo info)
{
}
/// <summary>
/// Determines if a given query paramter should be excluded from serialziation
/// </summary>
/// <param name="name">The name of the Uri query parameter</param>
/// <param name="value">The value of the uri query parameter</param>
/// <returns>False</returns>
public virtual bool FilterParameter(string name, string value)
{
if (_paramFilter != null)
{
return _paramFilter(name, value);
}
return false;
}
/// <summary>
/// Called after content is retrieved from the actual service and before it is is saved to disk.
/// Primarily allows for response content to mask sensitive data (ex. SSN or other PII) before it is saved to storage
/// </summary>
/// <param name="response">The response</param>
/// <returns>The original content stream</returns>
public virtual async Task<Stream> Serializing(HttpResponseMessage response)
{
return await response.Content.ReadAsStreamAsync();
}
}
}
| apache-2.0 | C# |
c9111628657a30bb95a9c766503c9586124b37bd | Update 20170707.cs | twilightspike/cuddly-disco,twilightspike/cuddly-disco | main/20170707.cs | main/20170707.cs | float timer = 80f;
/*120sec = 2min*/
void Update(){
timer = Time.deltaTime;
GetComponent<ok>().text = timer.ToString();
}
| float timer = 80f;
| mit | C# |
831132300e4df39366c4fbb62f0848e10fe46604 | Update Program.cs | stephanstapel/ZUGFeRD-csharp,stephanstapel/ZUGFeRD-csharp | ZUGFeRDToExcelTest/Program.cs | ZUGFeRDToExcelTest/Program.cs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZUGFeRDToExcelTest
{
class Program
{
static void Main(string[] args)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZUGFeRDToExcelTest
{
class Program
{
static void Main(string[] args)
{
}
}
}
| apache-2.0 | C# |
a18e0b3b2faa0d94601021a688ee88efe09cb15b | Fix test scene | UselessToucan/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,peppy/osu,peppy/osu,ZLima12/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,peppy/osu-new | osu.Game.Tests/Visual/Online/TestSceneChangelogOverlay.cs | osu.Game.Tests/Visual/Online/TestSceneChangelogOverlay.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
using osu.Game.Overlays.Changelog;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneChangelogOverlay : OsuTestScene
{
private ChangelogOverlay changelog;
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(BadgeDisplay),
typeof(StreamBadge),
typeof(ChangelogHeader),
typeof(ChangelogContent),
typeof(ChangelogListing),
typeof(ChangelogSingleBuild),
typeof(ChangelogBuild),
};
protected override void LoadComplete()
{
base.LoadComplete();
Add(changelog = new ChangelogOverlay());
AddStep(@"Show", changelog.Show);
AddStep(@"Hide", changelog.Hide);
AddWaitStep("wait for hide", 3);
AddStep(@"Show with Lazer 2018.712.0", () =>
{
changelog.ShowBuild(new APIChangelogBuild
{
Version = "2018.712.0",
DisplayVersion = "2018.712.0",
UpdateStream = new APIUpdateStream { Name = "lazer" },
ChangelogEntries = new List<APIChangelogEntry>()
{
new APIChangelogEntry
{
Category = "Test",
Title = "Title",
MessageHtml = "Message",
}
}
});
changelog.Show();
});
AddWaitStep("wait for show", 3);
AddStep(@"Hide", changelog.Hide);
AddWaitStep("wait for hide", 3);
AddStep(@"Show with listing", () =>
{
changelog.ShowListing();
changelog.Show();
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
using osu.Game.Overlays.Changelog;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneChangelogOverlay : OsuTestScene
{
private ChangelogOverlay changelog;
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(BadgeDisplay),
typeof(StreamBadge),
typeof(ChangelogHeader),
typeof(ChangelogContent),
typeof(ChangelogListing),
typeof(ChangelogSingleBuild),
typeof(ChangelogBuild),
};
protected override void LoadComplete()
{
base.LoadComplete();
Add(changelog = new ChangelogOverlay());
AddStep(@"Show", changelog.Show);
AddStep(@"Hide", changelog.Hide);
AddWaitStep("wait for hide", 3);
AddStep(@"Show with Lazer 2018.712.0", () =>
{
changelog.ShowBuild(new APIChangelogBuild
{
Version = "2018.712.0",
UpdateStream = new APIUpdateStream { Name = "lazer" },
});
changelog.Show();
});
AddWaitStep("wait for show", 3);
AddStep(@"Hide", changelog.Hide);
AddWaitStep("wait for hide", 3);
AddStep(@"Show with listing", () =>
{
changelog.ShowListing();
changelog.Show();
});
}
}
}
| mit | C# |
c602b58165eab126545073c6227c8fd39534de42 | Add checks for Wasta and Cinnamon in PlatformUtilities | sillsdev/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,hatton/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso | Palaso/PlatformUtilities/Platform.cs | Palaso/PlatformUtilities/Platform.cs | // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
// Parts based on code by MJ Hutchinson http://mjhutchinson.com/journal/2010/01/25/integrating_gtk_application_mac
using System;
namespace Palaso.PlatformUtilities
{
public static class Platform
{
private static readonly string UnixNameMac = "Darwin";
private static readonly string UnixNameLinux = "Linux";
private static bool? m_isMono;
private static string m_unixName;
private static string m_sessionManager;
public static bool IsUnix
{
get { return Environment.OSVersion.Platform == PlatformID.Unix; }
}
public static bool IsLinux
{
get { return IsUnix && (UnixName == UnixNameLinux); }
}
public static bool IsMac
{
get { return IsUnix && (UnixName == UnixNameMac); }
}
public static bool IsWindows
{
get { return !IsUnix; }
}
public static bool IsMono
{
get
{
if (m_isMono == null)
m_isMono = Type.GetType("Mono.Runtime") != null;
return (bool)m_isMono;
}
}
public static bool IsDotNet
{
get { return !IsMono; }
}
private static string UnixName
{
get
{
if (m_unixName == null)
{
IntPtr buf = IntPtr.Zero;
try
{
buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192);
// This is a hacktastic way of getting sysname from uname ()
if (uname (buf) == 0)
m_unixName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf);
}
catch
{
m_unixName = String.Empty;
}
finally {
if (buf != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal (buf);
}
}
return m_unixName;
}
}
public static bool IsWasta
{
get { return IsUnix && System.IO.File.Exists("/etc/wasta-release"); }
}
public static bool IsCinnamon
{
get { return IsUnix && SessionManager.StartsWith("/usr/bin/cinnamon-session"); }
}
private static string SessionManager
{
get
{
if (m_sessionManager == null)
{
IntPtr buf = IntPtr.Zero;
try
{
// This is the only way I've figured out to get the session manager.
buf = System.Runtime.InteropServices.Marshal.AllocHGlobal(8192);
var len = readlink("/etc/alternatives/x-session-manager", buf, 8192);
if (len > 0)
m_sessionManager = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(buf);
else
m_sessionManager = String.Empty;
}
catch
{
m_sessionManager = String.Empty;
}
finally
{
if (buf != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal(buf);
}
}
return m_sessionManager;
}
}
[System.Runtime.InteropServices.DllImport ("libc")]
static extern int uname (IntPtr buf);
[System.Runtime.InteropServices.DllImport ("libc")]
static extern int readlink(string path, IntPtr buf, int bufsiz);
}
}
| // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
// Parts based on code by MJ Hutchinson http://mjhutchinson.com/journal/2010/01/25/integrating_gtk_application_mac
using System;
namespace Palaso.PlatformUtilities
{
public static class Platform
{
private static readonly string UnixNameMac = "Darwin";
private static readonly string UnixNameLinux = "Linux";
private static bool? m_isMono;
private static string m_unixName;
public static bool IsUnix
{
get { return Environment.OSVersion.Platform == PlatformID.Unix; }
}
public static bool IsLinux
{
get { return IsUnix && (UnixName == UnixNameLinux); }
}
public static bool IsMac
{
get { return IsUnix && (UnixName == UnixNameMac); }
}
public static bool IsWindows
{
get { return !IsUnix; }
}
public static bool IsMono
{
get
{
if (m_isMono == null)
m_isMono = Type.GetType("Mono.Runtime") != null;
return (bool)m_isMono;
}
}
public static bool IsDotNet
{
get { return !IsMono; }
}
private static string UnixName
{
get
{
if (m_unixName == null)
{
IntPtr buf = IntPtr.Zero;
try
{
buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192);
// This is a hacktastic way of getting sysname from uname ()
if (uname (buf) == 0)
m_unixName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf);
}
catch
{
m_unixName = String.Empty;
}
finally {
if (buf != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal (buf);
}
}
return m_unixName;
}
}
[System.Runtime.InteropServices.DllImport ("libc")]
static extern int uname (IntPtr buf);
}
}
| mit | C# |
79fe9aea114c5bd23ed5df166ae8c635c1a8e903 | Document Level | HQC-Team-Minesweeper-5/Minesweeper | src/Minesweeper.Logic/Level.cs | src/Minesweeper.Logic/Level.cs | namespace Minesweeper.Logic
{
/// <summary>
/// Util class that holds the params of the chosen level in the begining of the game
/// </summary>
public class Level
{
public Level(int numberOfRows, int numberOfCols, int numberOfMines)
{
this.NumberOfRows = numberOfRows;
this.NumberOfCols = numberOfCols;
this.NumberOfMines = numberOfMines;
}
public int NumberOfRows { get; private set; }
public int NumberOfCols { get; private set; }
public int NumberOfMines { get; private set; }
}
}
| namespace Minesweeper.Logic
{
public class Level
{
public Level(int numberOfRows, int numberOfCols, int numberOfMines)
{
this.NumberOfRows = numberOfRows;
this.NumberOfCols = numberOfCols;
this.NumberOfMines = numberOfMines;
}
public int NumberOfRows { get; private set; }
public int NumberOfCols { get; private set; }
public int NumberOfMines { get; private set; }
}
}
| mit | C# |
f80e4ea94c7105776879dd368c0b5095f5a0f885 | Make Preconditions.CheckNotNull internal so we can use it elsewhere | jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode | CSharp8/Nullability/Preconditions.cs | CSharp8/Nullability/Preconditions.cs | using System;
using System.Diagnostics.CodeAnalysis;
namespace Nullability
{
class Precondition
{
static void Main()
{
string? text = MaybeNull();
string textNotNull = CheckNotNull(text);
// This is relatively obvious...
Console.WriteLine(textNotNull.Length);
// This is less so. The NotNull attribute implies that the
// method will be validating the input, so the method
// won't return if the value is null.
Console.WriteLine(text.Length);
}
internal static T CheckNotNull<T>([NotNull] T? input) where T : class =>
input ?? throw new ArgumentNullException();
internal static string? MaybeNull() => DateTime.UtcNow.Second == 0 ? null : "not null";
}
}
| using System;
using System.Diagnostics.CodeAnalysis;
namespace Nullability
{
class Precondition
{
static void Main()
{
string? text = MaybeNull();
string textNotNull = CheckNotNull(text);
// This is relatively obvious...
Console.WriteLine(textNotNull.Length);
// This is less so. The NotNull attribute implies that the
// method will be validating the input, so the method
// won't return if the value is null.
Console.WriteLine(text.Length);
}
static T CheckNotNull<T>([NotNull] T? input) where T : class =>
input ?? throw new ArgumentNullException();
static string? MaybeNull() => DateTime.UtcNow.Second == 0 ? null : "not null";
}
}
| apache-2.0 | C# |
ae2120f9eb26e23ffb8fd49b91d98fbecf2dd26b | Revert back to old signature (transpilers get confused with multiple version); add opcode=Call | pardeike/Harmony | Harmony/Transpilers.cs | Harmony/Transpilers.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = callOpcode ?? OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | mit | C# |
ac03ef3d108c8498f92df50cc3bbc2f9ff06a462 | Convert Main to be async | martincostello/website,martincostello/website,martincostello/website,martincostello/website | src/Website/Program.cs | src/Website/Program.cs | // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using System.Threading.Tasks;
using Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> that returns the exit code from the application.
/// </returns>
public static async Task<int> Main(string[] args)
{
try
{
using (var host = BuildWebHost(args))
{
await host.RunAsync();
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
private static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseKestrel((p) => p.AddServerHeader = false)
.UseAutofac()
.UseAzureAppServices()
.UseApplicationInsights()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
}
}
}
| // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// The exit code from the application.
/// </returns>
public static int Main(string[] args)
{
try
{
using (var host = BuildWebHost(args))
{
host.Run();
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
private static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseKestrel((p) => p.AddServerHeader = false)
.UseAutofac()
.UseAzureAppServices()
.UseApplicationInsights()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
}
}
}
| apache-2.0 | C# |
c2956613bb1c41cf894f0ab2ee5abd7b363e9356 | Fix for saving window state while minimized on closing | Esri/military-planner-application-csharp | source/MilitaryPlanner/Views/MainWindow.xaml.cs | source/MilitaryPlanner/Views/MainWindow.xaml.cs | using System.Windows;
namespace MilitaryPlanner.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//InitializeComponent();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
// if window is minimized, restore to avoid opening minimized on next run
if(WindowState == System.Windows.WindowState.Minimized)
{
WindowState = System.Windows.WindowState.Normal;
}
}
}
}
| using System.Windows;
namespace MilitaryPlanner.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//InitializeComponent();
}
}
}
| apache-2.0 | C# |
b41765ffde15bb7308261b203a5267339414eaaa | Remove unused constructor for Core.FSM.GestureMachine | rubyu/CreviceApp,rubyu/CreviceApp | CreviceApp/Core.FSM.GestureMachine.cs | CreviceApp/Core.FSM.GestureMachine.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreviceApp.Core.FSM
{
public class GestureMachine : IDisposable
{
public StateGlobal Global { get; private set; }
public IState State { get; private set; }
public IEnumerable<GestureDefinition> GestureDefinition { get; private set; }
private object lockObject = new object();
public GestureMachine(Config.UserConfig userConfig, IEnumerable<GestureDefinition> gestureDef)
{
this.Global = new StateGlobal(userConfig);
this.State = new State0(Global, gestureDef);
this.GestureDefinition = gestureDef;
}
public bool Input(Def.Event.IEvent evnt, Point point)
{
lock (lockObject)
{
var res = State.Input(evnt, point);
if (State.GetType() != res.NextState.GetType())
{
Debug.Print("The state of GestureMachine was changed: {0} -> {1}", State.GetType().Name, res.NextState.GetType().Name);
}
if (res.StrokeWatcher.IsResetRequested)
{
Global.ResetStrokeWatcher();
}
State = res.NextState;
return res.Event.IsConsumed;
}
}
public void Reset()
{
lock (lockObject)
{
State = State.Reset();
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
lock (lockObject)
{
Global.Dispose();
}
}
~GestureMachine()
{
Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreviceApp.Core.FSM
{
public class GestureMachine : IDisposable
{
public StateGlobal Global { get; private set; }
public IState State { get; private set; }
public IEnumerable<GestureDefinition> GestureDefinition { get; private set; }
private object lockObject = new object();
public GestureMachine(IEnumerable<GestureDefinition> gestureDef) : this(new Config.UserConfig(), gestureDef)
{
}
public GestureMachine(Config.UserConfig userConfig, IEnumerable<GestureDefinition> gestureDef)
{
this.Global = new StateGlobal(userConfig);
this.State = new State0(Global, gestureDef);
this.GestureDefinition = gestureDef;
}
public bool Input(Def.Event.IEvent evnt, Point point)
{
lock (lockObject)
{
var res = State.Input(evnt, point);
if (State.GetType() != res.NextState.GetType())
{
Debug.Print("The state of GestureMachine was changed: {0} -> {1}", State.GetType().Name, res.NextState.GetType().Name);
}
if (res.StrokeWatcher.IsResetRequested)
{
Global.ResetStrokeWatcher();
}
State = res.NextState;
return res.Event.IsConsumed;
}
}
public void Reset()
{
lock (lockObject)
{
State = State.Reset();
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
lock (lockObject)
{
Global.Dispose();
}
}
~GestureMachine()
{
Dispose();
}
}
}
| mit | C# |
14ea0baf7e482e8fef42b37dd5ac32a463219181 | Disable options when not executing in VS | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.VisualStudio/Settings/OptionsPage.cs | src/GitHub.VisualStudio/Settings/OptionsPage.cs | using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Runtime.InteropServices;
using GitHub.Exports;
using GitHub.Logging;
using GitHub.Settings;
using GitHub.VisualStudio.UI;
using Microsoft.VisualStudio.Shell;
using Serilog;
namespace GitHub.VisualStudio
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
[Guid("68C87C7B-0212-4256-BB6D-6A6BB847A3A7")]
public class OptionsPage : UIElementDialogPage
{
static readonly ILogger log = LogManager.ForContext<OptionsPage>();
OptionsControl child;
IPackageSettings packageSettings;
protected override UIElement Child
{
get
{
if (!ExportForVisualStudioProcessAttribute.IsVisualStudioProcess())
{
return new Grid(); // Show blank page
}
return child ?? (child = new OptionsControl());
}
}
protected override void OnActivate(CancelEventArgs e)
{
if (!ExportForVisualStudioProcessAttribute.IsVisualStudioProcess())
{
log.Warning("Don't activate options for non-Visual Studio process");
return;
}
base.OnActivate(e);
packageSettings = Services.DefaultExportProvider.GetExportedValue<IPackageSettings>();
LoadSettings();
}
void LoadSettings()
{
child.CollectMetrics = packageSettings.CollectMetrics;
child.EditorComments = packageSettings.EditorComments;
child.EnableTraceLogging = packageSettings.EnableTraceLogging;
}
void SaveSettings()
{
packageSettings.CollectMetrics = child.CollectMetrics;
packageSettings.EditorComments = child.EditorComments;
packageSettings.EnableTraceLogging = child.EnableTraceLogging;
packageSettings.Save();
}
protected override void OnApply(PageApplyEventArgs args)
{
if (!ExportForVisualStudioProcessAttribute.IsVisualStudioProcess())
{
log.Warning("Don't apply options for non-Visual Studio process");
return;
}
if (args.ApplyBehavior == ApplyKind.Apply)
{
SaveSettings();
}
base.OnApply(args);
}
}
}
| using GitHub.Settings;
using GitHub.VisualStudio.UI;
using Microsoft.VisualStudio.Shell;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
namespace GitHub.VisualStudio
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
[Guid("68C87C7B-0212-4256-BB6D-6A6BB847A3A7")]
public class OptionsPage : UIElementDialogPage
{
OptionsControl child;
IPackageSettings packageSettings;
protected override UIElement Child
{
get { return child ?? (child = new OptionsControl()); }
}
protected override void OnActivate(CancelEventArgs e)
{
base.OnActivate(e);
packageSettings = Services.DefaultExportProvider.GetExportedValue<IPackageSettings>();
LoadSettings();
}
void LoadSettings()
{
child.CollectMetrics = packageSettings.CollectMetrics;
child.EditorComments = packageSettings.EditorComments;
child.EnableTraceLogging = packageSettings.EnableTraceLogging;
}
void SaveSettings()
{
packageSettings.CollectMetrics = child.CollectMetrics;
packageSettings.EditorComments = child.EditorComments;
packageSettings.EnableTraceLogging = child.EnableTraceLogging;
packageSettings.Save();
}
protected override void OnApply(PageApplyEventArgs args)
{
if (args.ApplyBehavior == ApplyKind.Apply)
{
SaveSettings();
}
base.OnApply(args);
}
}
}
| mit | C# |
5871d52fd004bc82ccc5ad2106e64242d8ed1cee | Make M readonly | coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore | src/Miningcore/Blockchain/Ergo/ErgoConstants.cs | src/Miningcore/Blockchain/Ergo/ErgoConstants.cs | using System.Text.RegularExpressions;
// ReSharper disable InconsistentNaming
namespace Miningcore.Blockchain.Ergo;
public static class ErgoConstants
{
public const uint ShareMultiplier = 256;
public const decimal SmallestUnit = 1000000000;
public static readonly Regex RegexChain = new("ergo-([^-]+)-.+", RegexOptions.Compiled);
public static readonly byte[] M = Enumerable.Range(0, 1024)
.Select(x => BitConverter.GetBytes((ulong) x).Reverse())
.SelectMany(byteArr => byteArr)
.ToArray();
}
| using System.Text.RegularExpressions;
// ReSharper disable InconsistentNaming
namespace Miningcore.Blockchain.Ergo;
public static class ErgoConstants
{
public const uint ShareMultiplier = 256;
public const decimal SmallestUnit = 1000000000;
public static readonly Regex RegexChain = new("ergo-([^-]+)-.+", RegexOptions.Compiled);
public static byte[] M = Enumerable.Range(0, 1024)
.Select(x => BitConverter.GetBytes((ulong) x).Reverse())
.SelectMany(byteArr => byteArr)
.ToArray();
}
| mit | C# |
fd0e50d57626c8fca9a3eb204468cc0ad0350c2c | Make precedence test public to be discoverable by test runner. | plasma-umass/parcel,plasma-umass/parcel,plasma-umass/parcel | ParcelTest/PrecedenceTests.cs | ParcelTest/PrecedenceTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;
namespace ParcelTest
{
[TestClass]
public class PrecedenceTests
{
[TestMethod]
public void MultiplicationVsAdditionPrecedenceTest()
{
var mwb = MockWorkbook.standardMockWorkbook();
var e = mwb.envForSheet(1);
var f = "=2*3+1";
ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);
Expr correct =
Expr.NewBinOpExpr(
"+",
Expr.NewBinOpExpr(
"*",
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
);
try
{
Expr ast = asto.Value;
Assert.AreEqual(correct, ast);
}
catch (NullReferenceException nre)
{
Assert.Fail("Parse error: " + nre.Message);
}
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>;
using Expr = AST.Expression;
namespace ParcelTest
{
[TestClass]
class PrecedenceTests
{
[TestMethod]
public void MultiplicationVsAdditionPrecedenceTest()
{
var mwb = MockWorkbook.standardMockWorkbook();
var e = mwb.envForSheet(1);
var f = "=2*3+1";
ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName);
Expr correct =
Expr.NewBinOpExpr(
"+",
Expr.NewBinOpExpr(
"*",
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0))
),
Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0))
);
try
{
Expr ast = asto.Value;
Assert.AreEqual(correct, ast);
}
catch (NullReferenceException nre)
{
Assert.Fail("Parse error: " + nre.Message);
}
}
}
}
| bsd-2-clause | C# |
d3e610c636f4aa654ada72486a0caf5b9cb2ac58 | Update version to 1.0.0.2 | ddobric/durabletask,Azure/durabletask,yonglehou/durabletask,affandar/durabletask,jasoneilts/durabletask | Framework/Properties/AssemblyInfo.cs | Framework/Properties/AssemblyInfo.cs | // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.2")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")] | // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")] | apache-2.0 | C# |
81c16d8d10260cd6aa4590dd55ce6af4228ca871 | Fix post filter test after boost/descriptor refactoring | KodrAus/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,jonyadamit/elasticsearch-net,jonyadamit/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net | src/Nest/QueryDsl/MatchAllQuery.cs | src/Nest/QueryDsl/MatchAllQuery.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
public interface IMatchAllQuery : IQuery
{
[JsonProperty(PropertyName = "norm_field")]
string NormField { get; set; }
}
public class MatchAllQuery : QueryBase, IMatchAllQuery
{
public string NormField { get; set; }
bool IQuery.Conditionless => false;
protected override void WrapInContainer(IQueryContainer container)
{
container.MatchAllQuery = this;
}
}
public class MatchAllQueryDescriptor
: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
, IMatchAllQuery
{
bool IQuery.Conditionless => false;
string IMatchAllQuery.NormField { get; set; }
public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))]
public interface IMatchAllQuery : IQuery
{
[JsonProperty(PropertyName = "boost")]
double? Boost { get; set; }
[JsonProperty(PropertyName = "norm_field")]
string NormField { get; set; }
}
public class MatchAllQuery : QueryBase, IMatchAllQuery
{
public double? Boost { get; set; }
public string NormField { get; set; }
bool IQuery.Conditionless => false;
protected override void WrapInContainer(IQueryContainer container)
{
container.MatchAllQuery = this;
}
}
public class MatchAllQueryDescriptor
: QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery>
, IMatchAllQuery
{
bool IQuery.Conditionless => false;
string IQuery.Name { get; set; }
double? IMatchAllQuery.Boost { get; set; }
string IMatchAllQuery.NormField { get; set; }
public MatchAllQueryDescriptor Boost(double? boost) => Assign(a => a.Boost = boost);
public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField);
}
}
| apache-2.0 | C# |
6cca579472db9129cef29ef43441b928a69774e3 | Fix TU | rducom/ALM | Alm.Test/AnswerTest.cs | Alm.Test/AnswerTest.cs | using System;
using Xunit;
namespace Alm.Test
{
public class AnswerTest
{
[Fact]
public void TryGetTheAnswer()
{
var computer = new MegaComputer();
Assert.Throws<ArgumentNullException>(() => computer.Ask(null));
}
}
}
| using System;
using Xunit;
namespace Alm.Test
{
public class AnswerTest
{
[Fact]
public void TryGetTheAnswer()
{
var computer = new MegaComputer();
Assert.Throws<Exception>(() => computer.Ask(null));
}
}
}
| mit | C# |
ab639214795a0bf44a93de911ee5c473d95bd6cf | Add option to disable gravity for debugging. | PlanetLotus/TetrisClone2D | Assets/ShapeManager.cs | Assets/ShapeManager.cs | using UnityEngine;
using System;
public class ShapeManager : MonoBehaviour
{
public GameObject StartingObject;
public bool DisableGravity;
public void MoveActiveShapeDown()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x, position.y - 1, 0);
}
public void MoveActiveShapeLeft()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x - 1, position.y, 0);
}
public void MoveActiveShapeRight()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x + 1, position.y, 0);
}
public void RotateActiveShape()
{
if (activeShape == null)
{
return;
}
activeShape.transform.Rotate(0, 0, 90);
}
private void Start()
{
// Initialize shapes
if (StartingObject == null)
{
throw new InvalidOperationException("startingObject must be set in editor.");
}
StartingObject.transform.position = new Vector2(0, 10);
StartingObject = Instantiate(StartingObject);
activeShape = StartingObject;
// Begin updates, and repeat every second
InvokeRepeating("UpdateShapes", 1f, 1f);
}
private void UpdateShapes()
{
if (!DisableGravity)
{
Vector3 position = StartingObject.transform.position;
StartingObject.transform.position = new Vector3(position.x, position.y - 1, 0);
}
}
private GameObject activeShape;
}
| using UnityEngine;
using System;
public class ShapeManager : MonoBehaviour
{
public GameObject StartingObject;
public void MoveActiveShapeDown()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x, position.y - 1, 0);
}
public void MoveActiveShapeLeft()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x - 1, position.y, 0);
}
public void MoveActiveShapeRight()
{
if (activeShape == null)
{
return;
}
Vector3 position = activeShape.transform.position;
activeShape.transform.position = new Vector3(position.x + 1, position.y, 0);
}
public void RotateActiveShape()
{
if (activeShape == null)
{
return;
}
activeShape.transform.Rotate(0, 0, 90);
}
private void Start()
{
// Initialize shapes
if (StartingObject == null)
{
throw new InvalidOperationException("startingObject must be set in editor.");
}
StartingObject.transform.position = new Vector2(0, 10);
StartingObject = Instantiate(StartingObject);
activeShape = StartingObject;
// Begin updates, and repeat every second
InvokeRepeating("UpdateShapes", 1f, 1f);
}
private void UpdateShapes()
{
Vector3 position = StartingObject.transform.position;
StartingObject.transform.position = new Vector3(position.x, position.y - 1, 0);
Debug.Log(StartingObject.transform.position);
}
private GameObject activeShape;
}
| mit | C# |
9398327b675e2595323a816c5e2962385cd1df8b | Fix order of startup | mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager | SupportManager.Web/Program.cs | SupportManager.Web/Program.cs | using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;
namespace SupportManager.Web
{
public class Program
{
private static string[] args;
public static void Main()
{
HostFactory.Run(cfg =>
{
cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));
cfg.SetServiceName("SupportManager.Web");
cfg.SetDisplayName("SupportManager.Web");
cfg.SetDescription("SupportManager Web Interface");
cfg.Service<IWebHost>(svc =>
{
svc.ConstructUsing(CreateWebHost);
svc.WhenStarted(webHost =>
{
webHost.Start();
RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely);
});
svc.WhenStopped(webHost => webHost.Dispose());
});
cfg.RunAsLocalSystem();
cfg.StartAutomatically();
});
}
private static IWebHost CreateWebHost()
{
var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
if (!Debugger.IsAttached)
{
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = true;
});
builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
}
return builder.Build();
}
}
}
| using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;
namespace SupportManager.Web
{
public class Program
{
private static string[] args;
public static void Main()
{
HostFactory.Run(cfg =>
{
cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));
cfg.SetServiceName("SupportManager.Web");
cfg.SetDisplayName("SupportManager.Web");
cfg.SetDescription("SupportManager Web Interface");
cfg.Service<IWebHost>(svc =>
{
svc.ConstructUsing(CreateWebHost);
svc.WhenStarted(webHost =>
{
RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely);
webHost.Start();
});
svc.WhenStopped(webHost => webHost.Dispose());
});
cfg.RunAsLocalSystem();
cfg.StartAutomatically();
});
}
private static IWebHost CreateWebHost()
{
var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
if (!Debugger.IsAttached)
{
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = true;
});
builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
}
return builder.Build();
}
}
}
| mit | C# |
e2489b3b74c6a2422187e77b4d79d906cf9f1f87 | Update AssemblyInfo.cs | Brightspace/D2L.Security.OAuth2 | src/D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs | src/D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "D2L.Security.WebApi" )]
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
[assembly: AssemblyCompany( "Desire2Learn" )]
[assembly: AssemblyProduct( "Brightspace" )]
[assembly: AssemblyInformationalVersion( "7.1.0.0" )]
[assembly: AssemblyVersion( "7.1.0.0" )]
[assembly: AssemblyFileVersion( "7.1.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
| using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "D2L.Security.WebApi" )]
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
[assembly: AssemblyCompany( "Desire2Learn" )]
[assembly: AssemblyProduct( "Brightspace" )]
[assembly: AssemblyInformationalVersion( "7.1.0.0" )]
[assembly: AssemblyVersion( "7.1.0.0" )]
[assembly: AssemblyFileVersion( "7.10.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
| apache-2.0 | C# |
a588432febbf61ea6824cec1cd322046c22d0071 | add another test | huoxudong125/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET | Src/Metrics.Tests/AtomicLongTests.cs | Src/Metrics.Tests/AtomicLongTests.cs | using FluentAssertions;
using Metrics.Utils;
using Xunit;
namespace Metrics.Tests
{
public class AtomicLongTests
{
[Fact]
public void AtomicLongDefaultsToZero()
{
new AtomicLong().Value.Should().Be(0L);
}
[Fact]
public void AtomicLongCanBeCreatedWithValue()
{
new AtomicLong(5L).Value.Should().Be(5L);
}
[Fact]
public void AtomicLongCanSetAndReadValue()
{
var num = new AtomicLong();
num.SetValue(32);
num.Value.Should().Be(32);
}
[Fact]
public void AtomicLongCanGetAndSet()
{
var num = new AtomicLong();
num.SetValue(32);
long val = num.GetAndSet(64);
val.Should().Be(32);
num.Value.Should().Be(64);
}
[Fact]
public void AtomicLongCanBeIncremented()
{
AtomicLong l = new AtomicLong();
l.Increment();
l.Value.Should().Be(1L);
}
[Fact]
public void AtomicLongCanBeIncrementedMultipleTimes()
{
AtomicLong l = new AtomicLong();
l.Increment();
l.Increment();
l.Increment();
l.Value.Should().Be(3L);
}
[Fact]
public void AtomicLongCanAddValue()
{
AtomicLong l = new AtomicLong();
l.Add(7L);
l.Value.Should().Be(7L);
}
[Fact]
public void AtomicLongCanBeDecremented()
{
AtomicLong l = new AtomicLong(10L);
l.Decrement();
l.Value.Should().Be(9L);
}
[Fact]
public void AtomicLongCanBeAssigned()
{
AtomicLong x = new AtomicLong(10L);
AtomicLong y = x;
y.Value.Should().Be(10L);
}
}
}
| using FluentAssertions;
using Metrics.Utils;
using Xunit;
namespace Metrics.Tests
{
public class AtomicLongTests
{
[Fact]
public void AtomicLongDefaultsToZero()
{
new AtomicLong().Value.Should().Be(0L);
}
[Fact]
public void AtomicLongCanBeCreatedWithValue()
{
new AtomicLong(5L).Value.Should().Be(5L);
}
[Fact]
public void AtomicLongCanSetAndReadValue()
{
var num = new AtomicLong();
num.SetValue(32);
num.Value.Should().Be(32);
}
[Fact]
public void AtomicLongCanBeIncremented()
{
AtomicLong l = new AtomicLong();
l.Increment();
l.Value.Should().Be(1L);
}
[Fact]
public void AtomicLongCanBeIncrementedMultipleTimes()
{
AtomicLong l = new AtomicLong();
l.Increment();
l.Increment();
l.Increment();
l.Value.Should().Be(3L);
}
[Fact]
public void AtomicLongCanAddValue()
{
AtomicLong l = new AtomicLong();
l.Add(7L);
l.Value.Should().Be(7L);
}
[Fact]
public void AtomicLongCanBeDecremented()
{
AtomicLong l = new AtomicLong(10L);
l.Decrement();
l.Value.Should().Be(9L);
}
[Fact]
public void AtomicLongCanBeAssigned()
{
AtomicLong x = new AtomicLong(10L);
AtomicLong y = x;
y.Value.Should().Be(10L);
}
}
}
| apache-2.0 | C# |
ea3b36807426d70a30b633924d1b352c31d19975 | remove "https://" prefix from sso validate token address | bgTeamDev/bgTeam.Core,bgTeamDev/bgTeam.Core | src/bgTeam.SSO.Client/SsoClient.cs | src/bgTeam.SSO.Client/SsoClient.cs | namespace bgTeam.SSO.Client
{
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
// TODO: cache responses: public key -> response
// TODO: http client issues review: http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/
// TODO: add some client-side check. Don't call the remote service unless the client-side checks were passed
// TODO: get rid of using issuer or make cipher asymmetric and validate it via public key https://piotrgankiewicz.com/2017/07/24/jwt-rsa-hmac-asp-net-core/
public class SsoClient
{
public async Task<bool> ValidateToken(string token)
{
const string validateUrl = "api/auth/validatetoken";
var address = $"{GetIssuerAddressFromToken(token)}/{validateUrl}";
SsoReplyResult reply = null;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var res = await httpClient.GetStringAsync(new Uri(address));
reply = JsonConvert.DeserializeObject<SsoReplyResult>(res);
}
return reply.Succeeded;
}
private string GetIssuerAddressFromToken(string token)
{
var jwtHandler = new JwtSecurityTokenHandler();
var jwtToken = jwtHandler.ReadJwtToken(token);
return jwtToken.Issuer;
}
private class SsoReplyResult
{
public bool Succeeded { get; set; }
}
}
}
| namespace bgTeam.SSO.Client
{
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
// TODO: cache responses: public key -> response
// TODO: http client issues review: http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/
// TODO: add some client-side check. Don't call the remote service unless the client-side checks were passed
// TODO: get rid of using issuer or make cipher asymmetric and validate it via public key https://piotrgankiewicz.com/2017/07/24/jwt-rsa-hmac-asp-net-core/
public class SsoClient
{
public async Task<bool> ValidateToken(string token)
{
const string validateUrl = "api/auth/validatetoken";
var address = $"https://{GetIssuerAddressFromToken(token)}/{validateUrl}";
SsoReplyResult reply = null;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var res = await httpClient.GetStringAsync(new Uri(address));
reply = JsonConvert.DeserializeObject<SsoReplyResult>(res);
}
return reply.Succeeded;
}
private string GetIssuerAddressFromToken(string token)
{
var jwtHandler = new JwtSecurityTokenHandler();
var jwtToken = jwtHandler.ReadJwtToken(token);
return jwtToken.Issuer;
}
private class SsoReplyResult
{
public bool Succeeded { get; set; }
}
}
}
| mit | C# |
79aeeb49b5a2a02167cda5f81178fdb233631fd9 | Tweak date formatting | mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection | src/Cash-Flow-Projection/Models/Entry.cs | src/Cash-Flow-Projection/Models/Entry.cs | using System;
using System.ComponentModel.DataAnnotations;
namespace Cash_Flow_Projection.Models
{
public class Entry
{
/// <summary>
/// A unique identifer generated for the entry
/// </summary>
public String id { get; set; } = Guid.NewGuid().ToString();
/// <summary>
/// Date the entry occurred
/// </summary>
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:MMM dd}")]
public DateTime Date { get; set; } = DateTime.Today;
/// <summary>
/// A short, visible description of the transaction
/// </summary>
public String Description { get; set; }
/// <summary>
/// The amount of the transaction, negative represents cash expenditures, positive represents income.
///
/// If the entry is a balance snapshot, this represents the balance at this point in time.
/// </summary>
[DataType(DataType.Currency)]
public Decimal Amount { get; set; }
/// <summary>
/// If true, this entry denotes the snapshot cash balance at the given datetime
/// </summary>
public Boolean IsBalance { get; set; }
/// <summary>
/// Which account this transaction applies to
/// </summary>
public Account Account { get; set; } = Account.Cash;
}
public enum Account : byte
{
Cash,
Credit
}
} | using System;
using System.ComponentModel.DataAnnotations;
namespace Cash_Flow_Projection.Models
{
public class Entry
{
/// <summary>
/// A unique identifer generated for the entry
/// </summary>
public String id { get; set; } = Guid.NewGuid().ToString();
/// <summary>
/// Date the entry occurred
/// </summary>
[DataType(DataType.Date)]
public DateTime Date { get; set; } = DateTime.Today;
/// <summary>
/// A short, visible description of the transaction
/// </summary>
public String Description { get; set; }
/// <summary>
/// The amount of the transaction, negative represents cash expenditures, positive represents income.
///
/// If the entry is a balance snapshot, this represents the balance at this point in time.
/// </summary>
[DataType(DataType.Currency)]
public Decimal Amount { get; set; }
/// <summary>
/// If true, this entry denotes the snapshot cash balance at the given datetime
/// </summary>
public Boolean IsBalance { get; set; }
/// <summary>
/// Which account this transaction applies to
/// </summary>
public Account Account { get; set; } = Account.Cash;
}
public enum Account : byte
{
Cash,
Credit
}
} | mit | C# |
be4f536b06560425d14eb0c9320ca667e84e5c66 | Make MetadataToken IEquatable | gluck/cecil | Mono.Cecil.Metadata/MetadataToken.cs | Mono.Cecil.Metadata/MetadataToken.cs | //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace Mono.Cecil {
public struct MetadataToken : IEquatable<MetadataToken> {
readonly uint token;
public uint RID {
get { return token & 0x00ffffff; }
}
public TokenType TokenType {
get { return (TokenType) (token & 0xff000000); }
}
public static readonly MetadataToken Zero = new MetadataToken ((uint) 0);
public MetadataToken (uint token)
{
this.token = token;
}
public MetadataToken (TokenType type)
: this (type, 0)
{
}
public MetadataToken (TokenType type, uint rid)
{
token = (uint) type | rid;
}
public MetadataToken (TokenType type, int rid)
{
token = (uint) type | (uint) rid;
}
public int ToInt32 ()
{
return (int) token;
}
public uint ToUInt32 ()
{
return token;
}
public override int GetHashCode ()
{
return (int) token;
}
public bool Equals (MetadataToken other)
{
return other.token == token;
}
public override bool Equals (object obj)
{
if (obj is MetadataToken) {
var other = (MetadataToken) obj;
return other.token == token;
}
return false;
}
public static bool operator == (MetadataToken one, MetadataToken other)
{
return one.token == other.token;
}
public static bool operator != (MetadataToken one, MetadataToken other)
{
return one.token != other.token;
}
public override string ToString ()
{
return string.Format ("[{0}:0x{1}]", TokenType, RID.ToString ("x4"));
}
}
}
| //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
namespace Mono.Cecil {
public struct MetadataToken {
readonly uint token;
public uint RID {
get { return token & 0x00ffffff; }
}
public TokenType TokenType {
get { return (TokenType) (token & 0xff000000); }
}
public static readonly MetadataToken Zero = new MetadataToken ((uint) 0);
public MetadataToken (uint token)
{
this.token = token;
}
public MetadataToken (TokenType type)
: this (type, 0)
{
}
public MetadataToken (TokenType type, uint rid)
{
token = (uint) type | rid;
}
public MetadataToken (TokenType type, int rid)
{
token = (uint) type | (uint) rid;
}
public int ToInt32 ()
{
return (int) token;
}
public uint ToUInt32 ()
{
return token;
}
public override int GetHashCode ()
{
return (int) token;
}
public override bool Equals (object obj)
{
if (obj is MetadataToken) {
var other = (MetadataToken) obj;
return other.token == token;
}
return false;
}
public static bool operator == (MetadataToken one, MetadataToken other)
{
return one.token == other.token;
}
public static bool operator != (MetadataToken one, MetadataToken other)
{
return one.token != other.token;
}
public override string ToString ()
{
return string.Format ("[{0}:0x{1}]", TokenType, RID.ToString ("x4"));
}
}
}
| mit | C# |
981048e8f80a4987a36b0e24ac517b9ba59f40ed | test implementation of error page | ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth | GalleryMVC_With_Auth/Views/Errors/Index.cshtml | GalleryMVC_With_Auth/Views/Errors/Index.cshtml | @model Exception
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Model.Message |
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
| apache-2.0 | C# |
40245838d6762fff8d384dcea47828d9062b323e | add test | SixLabors/Fonts | tests/SixLabors.Fonts.Tests/Issues/Issues_47.cs | tests/SixLabors.Fonts.Tests/Issues/Issues_47.cs | using System.Collections.Immutable;
using SixLabors.Fonts.Tests.Fakes;
using Xunit;
namespace SixLabors.Fonts.Tests.Issues
{
public class Issues_47
{
[Theory]
[InlineData("hello world hello world hello world hello world")]
public void LeftAlignedTextNewLineShouldNotStartWithWhiteSpace(string text)
{
var font = CreateFont("\t x");
GlyphRenderer r = new GlyphRenderer();
ImmutableArray<GlyphLayout> layout = new TextLayout().GenerateLayout(text, new RendererOptions(new Font(font, 30), 72)
{
WrappingWidth = 350,
HorizontalAlignment = HorizontalAlignment.Left
});
float lineYPos = layout[0].Location.Y;
foreach (GlyphLayout glyph in layout)
{
if (lineYPos != glyph.Location.Y)
{
Assert.Equal(false, glyph.IsWhiteSpace);
lineYPos = glyph.Location.Y;
}
}
}
[Theory]
[InlineData(HorizontalAlignment.Left)]
[InlineData(HorizontalAlignment.Right)]
[InlineData(HorizontalAlignment.Center)]
public void WrappedTextShouldNotEndOrStartWithWhiteSpace(HorizontalAlignment horiAlignment)
{
var font = CreateFont("\t x");
var text = "hello world hello world hello world hello world";
GlyphRenderer r = new GlyphRenderer();
ImmutableArray<GlyphLayout> layout = new TextLayout().GenerateLayout(text, new RendererOptions(new Font(font, 30), 72)
{
WrappingWidth = 350,
HorizontalAlignment = horiAlignment
});
float lineYPos = layout[0].Location.Y;
for (int i = 0; i < layout.Length; i++)
{
GlyphLayout glyph = layout[i];
if (lineYPos != glyph.Location.Y)
{
Assert.Equal(false, glyph.IsWhiteSpace);
Assert.Equal(false, layout[i - 1].IsWhiteSpace);
lineYPos = glyph.Location.Y;
}
}
}
public static Font CreateFont(string text)
{
FontCollection fc = new FontCollection();
Font d = fc.Install(new FakeFontInstance(text)).CreateFont(12);
return new Font(d, 1);
}
}
}
| using System.Collections.Immutable;
using SixLabors.Fonts.Tests.Fakes;
using Xunit;
namespace SixLabors.Fonts.Tests.Issues
{
public class Issues_47
{
[Theory]
[InlineData("hello world hello world hello world hello world")]
public void LeftAlignedTextNewLineShouldNotStartWithWhiteSpace(string text)
{
var font = CreateFont("\t x");
GlyphRenderer r = new GlyphRenderer();
ImmutableArray<GlyphLayout> layout = new TextLayout().GenerateLayout(text, new RendererOptions(new Font(font, 30), 72)
{
WrappingWidth = 350,
HorizontalAlignment = HorizontalAlignment.Left
});
float lineYPos = layout[0].Location.Y;
foreach (GlyphLayout glyph in layout)
{
if (lineYPos != glyph.Location.Y)
{
Assert.Equal(false, glyph.IsWhiteSpace);
lineYPos = glyph.Location.Y;
}
}
}
public static Font CreateFont(string text)
{
FontCollection fc = new FontCollection();
Font d = fc.Install(new FakeFontInstance(text)).CreateFont(12);
return new Font(d, 1);
}
}
}
| apache-2.0 | C# |
913a0490fd9d6b1e7a0f8f66055cd1c5c8f3cd24 | add logs | dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP | src/DotNetCore.CAP/Internal/ICallbackMessageSender.Default.cs | src/DotNetCore.CAP/Internal/ICallbackMessageSender.Default.cs | using System;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Infrastructure;
using DotNetCore.CAP.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DotNetCore.CAP.Internal
{
internal class CallbackMessageSender : ICallbackMessageSender
{
private readonly ILogger<CallbackMessageSender> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IContentSerializer _contentSerializer;
private readonly IMessagePacker _messagePacker;
public CallbackMessageSender(
ILogger<CallbackMessageSender> logger,
IServiceProvider serviceProvider,
IContentSerializer contentSerializer,
IMessagePacker messagePacker)
{
_logger = logger;
_serviceProvider = serviceProvider;
_contentSerializer = contentSerializer;
_messagePacker = messagePacker;
}
public async Task SendAsync(string messageId, string topicName, object bodyObj)
{
string body;
if (bodyObj != null && Helper.IsComplexType(bodyObj.GetType()))
body = _contentSerializer.Serialize(bodyObj);
else
body = bodyObj?.ToString();
_logger.LogDebug($"Callback message will publishing, name:{topicName},content:{body}");
var callbackMessage = new CapMessageDto
{
Id = messageId,
Content = body
};
var content = _messagePacker.Pack(callbackMessage);
var publishedMessage = new CapPublishedMessage
{
Name = topicName,
Content = content,
StatusName = StatusName.Scheduled
};
using (var scope = _serviceProvider.CreateScope())
{
var provider = scope.ServiceProvider;
var callbackPublisher = provider.GetService<ICallbackPublisher>();
await callbackPublisher.PublishAsync(publishedMessage);
}
}
}
}
| using System;
using System.Threading.Tasks;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Infrastructure;
using DotNetCore.CAP.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DotNetCore.CAP.Internal
{
internal class CallbackMessageSender : ICallbackMessageSender
{
private readonly ILogger<CallbackMessageSender> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IContentSerializer _contentSerializer;
private readonly IMessagePacker _messagePacker;
public CallbackMessageSender(
ILogger<CallbackMessageSender> logger,
IServiceProvider serviceProvider,
IContentSerializer contentSerializer,
IMessagePacker messagePacker)
{
_logger = logger;
_serviceProvider = serviceProvider;
_contentSerializer = contentSerializer;
_messagePacker = messagePacker;
}
public async Task SendAsync(string messageId, string topicName, object bodyObj)
{
string body = null;
if (bodyObj != null && Helper.IsComplexType(bodyObj.GetType()))
body = _contentSerializer.Serialize(bodyObj);
else
body = bodyObj?.ToString();
var callbackMessage = new CapMessageDto
{
Id = messageId,
Content = body
};
var content = _messagePacker.Pack(callbackMessage);
var publishedMessage = new CapPublishedMessage
{
Name = topicName,
Content = content,
StatusName = StatusName.Scheduled
};
using (var scope = _serviceProvider.CreateScope())
{
var provider = scope.ServiceProvider;
var callbackPublisher = provider.GetService<ICallbackPublisher>();
await callbackPublisher.PublishAsync(publishedMessage);
}
}
}
}
| mit | C# |
53f3c227ef23c24aed528e87c670f0db2d4da49d | Remove the silly error I am adding | RockstarLabs/GeoToast,RockstarLabs/GeoToast,RockstarLabs/GeoToast | src/GeoToast/Infrastructure/Filters/ValidateModelAttribute.cs | src/GeoToast/Infrastructure/Filters/ValidateModelAttribute.cs | using System.Linq;
using GeoToast.Infrastructure.Errors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace GeoToast.Infrastructure.Filters
{
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new ValidationFailedResult(context.ModelState);
}
}
}
} | using System.Linq;
using GeoToast.Infrastructure.Errors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace GeoToast.Infrastructure.Filters
{
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.ModelState.AddModelError("", "This is a model wide error");
context.Result = new ValidationFailedResult(context.ModelState);
}
}
}
} | mit | C# |
1f27d2b04fb19558a40ef8de296adab17d6303f8 | Bump Assembly version to 1.0.0.11 | Azure/durabletask,affandar/durabletask,ddobric/durabletask | Framework/Properties/AssemblyInfo.cs | Framework/Properties/AssemblyInfo.cs | // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.11")]
[assembly: AssemblyFileVersion("1.0.0.11")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")]
| // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.10")]
[assembly: AssemblyFileVersion("1.0.0.10")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")]
| apache-2.0 | C# |
7b27f6b37829e98a6643e737227eb0616032aa2b | Add droplet rotation animation | ppy/osu,peppy/osu-new,EVAST9919/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu | osu.Game.Rulesets.Catch/Objects/Drawable/DrawableDroplet.cs | osu.Game.Rulesets.Catch/Objects/Drawable/DrawableDroplet.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Game.Rulesets.Catch.Objects.Drawable.Pieces;
using osu.Game.Skinning;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public class DrawableDroplet : PalpableCatchHitObject<Droplet>
{
public override bool StaysOnPlate => false;
public DrawableDroplet(Droplet h)
: base(h)
{
}
[BackgroundDependencyLoader]
private void load()
{
ScaleContainer.Child = new SkinnableDrawable(
new CatchSkinComponent(CatchSkinComponents.Droplet), _ => new Pulp
{
Size = Size / 4,
AccentColour = { Value = Color4.White }
});
}
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
// roughly matches osu-stable
float startRotation = RNG.NextSingle() * 20;
double duration = HitObject.TimePreempt + 2000;
this.RotateTo(startRotation).RotateTo(startRotation + 720, duration);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects.Drawable.Pieces;
using osu.Game.Skinning;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Catch.Objects.Drawable
{
public class DrawableDroplet : PalpableCatchHitObject<Droplet>
{
public override bool StaysOnPlate => false;
public DrawableDroplet(Droplet h)
: base(h)
{
}
[BackgroundDependencyLoader]
private void load()
{
ScaleContainer.Child = new SkinnableDrawable(
new CatchSkinComponent(CatchSkinComponents.Droplet), _ => new Pulp
{
Size = Size / 4,
AccentColour = { Value = Color4.White }
});
}
}
}
| mit | C# |
c5dba2c3e12f4accbf86285f4868c4035ed11de9 | Fix compilation issue introduced with the windows service feature | laurentkempe/Nubot,lionelplessis/Nubot,laurentkempe/Nubot,lionelplessis/Nubot | Nubot/Plugins/Httpd.cs | Nubot/Plugins/Httpd.cs | namespace Nubot.Plugins{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Net;
using System.Text;
using Interfaces;
using Nancy;
using Nancy.TinyIoc;
[Export(typeof(IRobotPlugin))]
public class Httpd : NancyModule, IRobotPlugin
{
private readonly IRobot _robot;
public Httpd()
: base("/")
{
Name = "Httpd";
_robot = TinyIoCContainer.Current.Resolve<IRobot>();
Get["nubot/version"] = x => _robot.Version;
Get["nubot/ping"] = x => "PONG";
Get["nubot/time"] = x => string.Format("Server time is: {0}", DateTime.Now);
Get["nubot/info"] = x =>
{
var currentProcess = Process.GetCurrentProcess();
return string.Format("[pid:{0}] [Start Time:{1}]", currentProcess.Id, currentProcess.StartTime);
};
Get["nubot/ip"] = x => new WebClient().DownloadString("http://ifconfig.me/ip");
Get["nubot/plugins"] = x => ShowPlugins();
}
private string ShowPlugins()
{
var stringBuilder = new StringBuilder();
stringBuilder.Append("<ul>");
foreach (var plugin in _robot.RobotPlugins)
{
stringBuilder.AppendFormat("<li>{0}</li>", plugin.Name);
}
stringBuilder.Append("</ul>");
return stringBuilder.ToString();
}
public string Name { get; private set; }
public IEnumerable<string> HelpMessages { get; private set; }
public void Respond(string message)
{
}
}
} | namespace Nubot.Plugins{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Net;
using System.Text;
using Interfaces;
using Nancy;
using Nancy.TinyIoc;
[Export(typeof(IRobotPlugin))]
public class Httpd : NancyModule, IRobotPlugin
{
private readonly IRobot _robot;
public Httpd()
: base("/")
{
Name = "Httpd";
_robot = TinyIoCContainer.Current.Resolve<IRobot>();
Get["nubot/version"] = x => _robot.Version;
Get["nubot/ping"] = x => "PONG";
Get["nubot/time"] = x => string.Format("Server time is: {0}", DateTime.Now);
Get["nubot/info"] = x =>
{
var currentProcess = Process.GetCurrentProcess();
return string.Format("[pid:{0}] [Start Time:{1}]", currentProcess.Id, currentProcess.StartTime);
};
Get["nubot/ip"] = x => new WebClient().DownloadString("http://ifconfig.me/ip");
Get["nubot/plugins"] = x => ShowPlugins();
}
private string ShowPlugins()
{
var stringBuilder = new StringBuilder();
stringBuilder.Append("<ul>");
foreach (var plugin in _robot.RobotPlugins)
{
stringBuilder.AppendFormat("<li>{0}</li>", plugin.Name);
}
stringBuilder.Append("</ul>");
return stringBuilder.ToString();
}
public string Name { get; private set; }
public IEnumerable<string> HelpMessages { get; }
public void Respond(string message)
{
}
}
} | mit | C# |
0bbaafc51f0850426b5e5c4639a45420c6637fe8 | Add QueryEduLevels and QueryEduProgramLevels methods | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Data/UniversityDataRepository.cs | R7.University/Data/UniversityDataRepository.cs | //
// UniversityDataRepository.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;
using R7.University.Models;
namespace R7.University.Data
{
public class UniversityDataRepository: DataRepositoryBase
{
public UniversityDataRepository (IDataContext dataContext): base (dataContext)
{
}
public UniversityDataRepository ()
{
}
#region DataRepositoryBase implementation
public override IDataContext CreateDataContext ()
{
return UniversityDataContextFactory.Instance.Create ();
}
#endregion
#region Custom methods
public IQueryable<EduLevelInfo> QueryEduLevels ()
{
return Query<EduLevelInfo> ().OrderBy (el => el.EduLevelID);
}
public IQueryable<EduLevelInfo> QueryEduProgramLevels ()
{
return Query<EduLevelInfo> ().Where (el => el.ParentEduLevelId == null).OrderBy (el => el.EduLevelID);
}
#endregion
}
}
| //
// UniversityDataRepository.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;
using R7.University.Models;
namespace R7.University.Data
{
public class UniversityDataRepository: DataRepositoryBase
{
public UniversityDataRepository (IDataContext dataContext): base (dataContext)
{
}
public UniversityDataRepository ()
{
}
#region DataRepositoryBase implementation
public override IDataContext CreateDataContext ()
{
return UniversityDataContextFactory.Instance.Create ();
}
#endregion
#region Custom methods
public IQueryable<EduLevelInfo> QueryEduProgramLevels ()
{
return Query<EduLevelInfo> ().Where (el => el.ParentEduLevelId == null);
}
#endregion
}
}
| agpl-3.0 | C# |
ba0e233f85032e6534ffa6174a632cb7d906a3e7 | Fix OS based character Encoding issue | Tochemey/Iso85834Net | ModIso8583.Test/Parse/TestEncoding.cs | ModIso8583.Test/Parse/TestEncoding.cs | using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;
namespace ModIso8583.Test.Parse
{
public class TestEncoding
{
[Fact]
public void WindowsToUtf8()
{
string data = "05ácido";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
if (OsUtil.IsLinux())
encoding = Encoding.UTF8;
sbyte[] buf = data.GetSbytes(encoding);
LlvarParseInfo parser = new LlvarParseInfo
{
Encoding = Encoding.Default
};
if (OsUtil.IsLinux())
parser.Encoding = Encoding.UTF8;
IsoValue field = parser.Parse(1, buf, 0, null);
Assert.Equal(field.Value, data.Substring(2));
parser.Encoding = encoding;
field = parser.Parse(1, buf, 0, null);
Assert.Equal(data.Substring(2), field.Value);
}
}
} | using System;
using System.Text;
using ModIso8583.Parse;
using ModIso8583.Util;
using Xunit;
namespace ModIso8583.Test.Parse
{
public class TestEncoding
{
[Fact(Skip = "character encoding issue")]
public void WindowsToUtf8()
{
string data = "05ácido";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
if (OsUtil.IsLinux())
encoding = Encoding.Default;
sbyte[] buf = data.GetSbytes(encoding);
LlvarParseInfo parser = new LlvarParseInfo
{
Encoding = Encoding.Default
};
IsoValue field = parser.Parse(1, buf, 0, null);
Assert.Equal(field.Value, data.Substring(2));
parser.Encoding = encoding;
field = parser.Parse(1, buf, 0, null);
Assert.Equal(data.Substring(2), field.Value);
}
}
} | mit | C# |
cea1370e10baa7fe3dd06dda54513a01c1eb17ca | Remove unused variable | aj-r/RiotNet | RiotNet/JsonContent.cs | RiotNet/JsonContent.cs | using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace RiotNet
{
/// <summary>
/// Represents HTTP content in JSON format.
/// </summary>
public class JsonContent : HttpContent
{
private object content;
/// <summary>
/// Creates a new <see cref="JsonContent"/> instance.
/// </summary>
/// <param name="content">The object to serialize in JSON format.</param>
public JsonContent(object content)
{
this.content = content;
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
/// <inheritdoc />
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var serializer = JsonSerializer.Create(RiotClient.JsonSettings);
var writer = new StreamWriter(stream);
var jsonWriter = new JsonTextWriter(writer);
serializer.Serialize(jsonWriter, content);
return writer.FlushAsync();
}
/// <inheritdoc />
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
}
| using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace RiotNet
{
/// <summary>
/// Represents HTTP content in JSON format.
/// </summary>
public class JsonContent : HttpContent
{
private object content;
/// <summary>
/// Creates a new <see cref="JsonContent"/> instance.
/// </summary>
/// <param name="content">The object to serialize in JSON format.</param>
public JsonContent(object content)
{
this.content = content;
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
/// <inheritdoc />
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var serializeToStreamTask = new TaskCompletionSource<bool>();
var serializer = JsonSerializer.Create(RiotClient.JsonSettings);
var writer = new StreamWriter(stream);
var jsonWriter = new JsonTextWriter(writer);
serializer.Serialize(jsonWriter, content);
return writer.FlushAsync();
}
/// <inheritdoc />
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
}
| mit | C# |
c8f3014356e54c5137d542e3b2c526ad33524b1c | Handle Discover | LordMike/TMDbLib | TMDbLib/Client/TMDbClientDiscover.cs | TMDbLib/Client/TMDbClientDiscover.cs | using System.Collections.Specialized;
using System.Threading.Tasks;
using RestSharp;
using TMDbLib.Objects.Discover;
using TMDbLib.Objects.General;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Can be used to discover new tv shows matching certain criteria
/// </summary>
public DiscoverTv DiscoverTvShows()
{
return new DiscoverTv(this);
}
/// <summary>
/// Can be used to discover movies matching certain criteria
/// </summary>
public DiscoverMovie DiscoverMovies()
{
return new DiscoverMovie(this);
}
internal async Task<SearchContainer<T>> DiscoverPerform<T>(string endpoint, string language, int page, NameValueCollection parameters)
{
TmdbRestRequest request = _client2.Create(endpoint);
if (page != 1 && page > 1)
request.AddParameter("page", page.ToString());
if (!string.IsNullOrWhiteSpace(language))
request.AddParameter("language", language);
foreach (string key in parameters.Keys)
request.AddParameter(key, parameters[key]);
TmdbRestResponse<SearchContainer<T>> response = await request.ExecuteGetTaskAsync<SearchContainer<T>>();
return response;
}
}
}
| using System.Collections.Specialized;
using System.Threading.Tasks;
using RestSharp;
using TMDbLib.Objects.Discover;
using TMDbLib.Objects.General;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// Can be used to discover new tv shows matching certain criteria
/// </summary>
public DiscoverTv DiscoverTvShows()
{
return new DiscoverTv(this);
}
/// <summary>
/// Can be used to discover movies matching certain criteria
/// </summary>
public DiscoverMovie DiscoverMovies()
{
return new DiscoverMovie(this);
}
internal async Task<SearchContainer<T>> DiscoverPerform<T>(string endpoint, string language, int page, NameValueCollection parameters)
{
RestRequest request = new RestRequest(endpoint);
if (page != 1 && page > 1)
request.AddParameter("page", page);
if (!string.IsNullOrWhiteSpace(language))
request.AddParameter("language", language);
foreach (string key in parameters.Keys)
request.AddParameter(key, parameters[key]);
IRestResponse<SearchContainer<T>> response = await _client.ExecuteGetTaskAsync<SearchContainer<T>>(request);
return response.Data;
}
}
}
| mit | C# |
7666d5973f036662981d7117879f6cf4814ddfb3 | fix build issue in coreclr | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/WebSites/BasicWebSite/Controllers/OrderController.cs | test/WebSites/BasicWebSite/Controllers/OrderController.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNet.Mvc;
namespace BasicWebSite
{
public class OrderController : Controller
{
public int GetServiceOrder(string serviceType, string actualType)
{
var elementType = Type.GetType(serviceType);
var queryType = typeof(IEnumerable<>).MakeGenericType(elementType);
var services = (IEnumerable<object>)Resolver.GetService(queryType);
foreach (var service in services)
{
if (actualType != null && service.GetType().AssemblyQualifiedName == actualType)
{
var orderProperty = elementType.GetTypeInfo().GetDeclaredProperty("Order");
return (int)orderProperty.GetValue(service);
}
else if (actualType == null)
{
var orderProperty = elementType.GetProperty("Order");
return (int)orderProperty.GetValue(service);
}
}
throw new InvalidOperationException();
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
namespace BasicWebSite
{
public class OrderController : Controller
{
public int GetServiceOrder(string serviceType, string actualType)
{
var elementType = Type.GetType(serviceType);
var queryType = typeof(IEnumerable<>).MakeGenericType(elementType);
var services = (IEnumerable<object>)Resolver.GetService(queryType);
foreach (var service in services)
{
if (actualType != null && service.GetType().AssemblyQualifiedName == actualType)
{
var orderProperty = elementType.GetProperty("Order");
return (int)orderProperty.GetValue(service);
}
else if (actualType == null)
{
var orderProperty = elementType.GetProperty("Order");
return (int)orderProperty.GetValue(service);
}
}
throw new InvalidOperationException();
}
}
} | apache-2.0 | C# |
bc9e8d83d2035591679e8de2167d4e815873c066 | Add distance method to Vector3 | dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo | DynamixelServo.Quadruped/Vector3.cs | DynamixelServo.Quadruped/Vector3.cs | using System;
namespace DynamixelServo.Quadruped
{
public struct Vector3
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator *(Vector3 vector, float multiplier)
{
return new Vector3(vector.X * multiplier, vector.Y * multiplier, vector.Z * multiplier);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
public static float Distance(Vector3 a, Vector3 b)
{
return (float) Math.Sqrt((a.X - b.X).Square() + (a.Y - b.Y).Square() + (a.Z - b.Z).Square());
}
public override string ToString()
{
return $"[{X:f3}; {Y:f3}; {Z:f3}]";
}
}
}
| namespace DynamixelServo.Quadruped
{
public struct Vector3
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator *(Vector3 vector, float multiplier)
{
return new Vector3(vector.X * multiplier, vector.Y * multiplier, vector.Z * multiplier);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
public override string ToString()
{
return $"[{X:f3}; {Y:f3}; {Z:f3}]";
}
}
}
| apache-2.0 | C# |
7cadb51cdf5d1bd1b67915eaca31ca0192968eb6 | Update control comments | anjdreas/roslyn-analyzers | SampleConsoleApp/Program.cs | SampleConsoleApp/Program.cs | namespace SampleConsoleApp
{
internal static class Program
{
private static void Main(string[] args)
{
// ObjectInitializer_AssignAll enable
Foo foo = new Foo
{
PropInt = 1,
// ObjectInitializer_AssignAll disable
Bar = new Bar
{
//PropInt = 2
}
};
}
private class Foo
{
public int PropInt { get; set; }
public Bar Bar { get; internal set; }
}
private class Bar
{
public int PropInt { get; set; }
}
}
} | namespace SampleConsoleApp
{
internal static class Program
{
private static void Main(string[] args)
{
// Roslyn enable analyzer ObjectInitializer_AssignAll
Foo foo = new Foo
{
PropInt = 1,
// Roslyn disable analyzer ObjectInitializer_AssignAll
Bar = new Bar
{
//PropInt = 2
}
};
}
private class Foo
{
public int PropInt { get; set; }
public Bar Bar { get; internal set; }
}
private class Bar
{
public int PropInt { get; set; }
}
}
} | mit | C# |
e89d08f5f34eb8cac20a46b4f892bac2c84fd697 | Disable exception throwing when ModelState is not valid | dmytrokuzmin/RepairisCore,dmytrokuzmin/RepairisCore,dmytrokuzmin/RepairisCore | src/Repairis.Web.Core/Controllers/RepairisControllerBase.cs | src/Repairis.Web.Core/Controllers/RepairisControllerBase.cs | using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Abp.Runtime.Validation;
using Microsoft.AspNetCore.Identity;
namespace Repairis.Controllers
{
[DisableValidation]
public abstract class RepairisControllerBase: AbpController
{
protected RepairisControllerBase()
{
LocalizationSourceName = RepairisConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
} | using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Microsoft.AspNetCore.Identity;
namespace Repairis.Controllers
{
public abstract class RepairisControllerBase: AbpController
{
protected RepairisControllerBase()
{
LocalizationSourceName = RepairisConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
} | mit | C# |
082c8910a2a05b78dabbdc76b646f693635049ba | change help url | stanac/shutdown | ShutDown/MainWindow.xaml.cs | ShutDown/MainWindow.xaml.cs | using ShutDown.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ShutDown
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected override void OnInitialized(EventArgs e)
{
MouseDown += (s, me) =>
{
if (me.ChangedButton == MouseButton.Left)
{
DragMove();
}
};
(DataContext as MainViewModel).CloseApp += (s, ec) => { Close(); };
base.OnInitialized(e);
}
private void MinBtnClick(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void CloseBtnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void AddPatternClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Coming up in v1.1", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void HelpBtnClick(object sender, RoutedEventArgs e)
{
Process.Start("http://stanac.github.io/shutdown/");
}
}
}
| using ShutDown.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ShutDown
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected override void OnInitialized(EventArgs e)
{
MouseDown += (s, me) =>
{
if (me.ChangedButton == MouseButton.Left)
{
DragMove();
}
};
(DataContext as MainViewModel).CloseApp += (s, ec) => { Close(); };
base.OnInitialized(e);
}
private void MinBtnClick(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void CloseBtnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void AddPatternClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Coming up in v1.1", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void HelpBtnClick(object sender, RoutedEventArgs e)
{
Process.Start("http://google.com");
}
}
}
| mit | C# |
844b136657da4590e73c54125ac7adce2b2bb7cb | Add relay.md | bitbeans/SimpleDnsCrypt | SimpleDnsCrypt/Helper/PatchHelper.cs | SimpleDnsCrypt/Helper/PatchHelper.cs | namespace SimpleDnsCrypt.Helper
{
/// <summary>
/// Class to update the configuration file.
/// </summary>
public static class PatchHelper
{
public static bool Patch()
{
var version = VersionHelper.PublishVersion;
if (!DnscryptProxyConfigurationManager.LoadConfiguration()) return false;
if (version.Equals("0.6.5"))
{
//added: netprobe_address = '255.255.255.0:53'
//changed: netprobe_timeout = 0
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_address = "255.255.255.0:53";
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_timeout = 0;
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
if (version.Equals("0.6.6"))
{
//changed: netprobe_address = '9.9.9.9:53'
//changed: netprobe_timeout = 60
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_address = "9.9.9.9:53";
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_timeout = 60;
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
if (version.Equals("0.6.8") || version.Equals("0.6.9"))
{
//changed: timeout = 5000
//added: reject_ttl = 600
//changed: cache_size = 1024
//changed: cache_min_ttl = 2400
//added: cache_neg_min_ttl = 60
//added: cache_neg_max_ttl = 600
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.timeout = 5000;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.reject_ttl = 600;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_size = 1024;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_min_ttl = 2400;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_neg_min_ttl = 60;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_neg_max_ttl = 600;
var sources = DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.sources;
if (!sources.ContainsKey("relays"))
{
sources.Add("relays", new Models.Source
{
urls = new string[] { "https://github.com/DNSCrypt/dnscrypt-resolvers/raw/master/v2/relays.md", "https://download.dnscrypt.info/resolvers-list/v2/relays.md" },
cache_file = "relays.md",
minisign_key = "RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3",
refresh_delay = 72,
prefix = ""
});
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.sources = sources;
}
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
return false;
}
}
}
| namespace SimpleDnsCrypt.Helper
{
/// <summary>
/// Class to update the configuration file.
/// </summary>
public static class PatchHelper
{
public static bool Patch()
{
var version = VersionHelper.PublishVersion;
if (!DnscryptProxyConfigurationManager.LoadConfiguration()) return false;
if (version.Equals("0.6.5"))
{
//added: netprobe_address = '255.255.255.0:53'
//changed: netprobe_timeout = 0
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_address = "255.255.255.0:53";
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_timeout = 0;
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
if (version.Equals("0.6.6"))
{
//changed: netprobe_address = '9.9.9.9:53'
//changed: netprobe_timeout = 60
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_address = "9.9.9.9:53";
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.netprobe_timeout = 60;
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
if (version.Equals("0.6.8") || version.Equals("0.6.9"))
{
//changed: timeout = 5000
//added: reject_ttl = 600
//changed: cache_size = 1024
//changed: cache_min_ttl = 2400
//added: cache_neg_min_ttl = 60
//added: cache_neg_max_ttl = 600
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.timeout = 5000;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.reject_ttl = 600;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_size = 1024;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_min_ttl = 2400;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_neg_min_ttl = 60;
DnscryptProxyConfigurationManager.DnscryptProxyConfiguration.cache_neg_max_ttl = 600;
return DnscryptProxyConfigurationManager.SaveConfiguration();
}
return false;
}
}
}
| mit | C# |
487d077dca59f0d416d0a6fac77660ba1a623acf | Remove readonly | AlexCatarino/pythonnet,AlexCatarino/pythonnet,AlexCatarino/pythonnet,AlexCatarino/pythonnet | src/runtime/typeaccessormanager.cs | src/runtime/typeaccessormanager.cs | using System;
using System.Collections.Generic;
using System.Dynamic;
using FastMember;
namespace Python.Runtime
{
/// <summary>
/// TypeAccessorManager creates TypeAccessor instances when necessary.
/// </summary>
public class TypeAccessorManager
{
private static Dictionary<Type, TypeAccessor> Cache = new Dictionary<Type, TypeAccessor>(128);
/// <summary>
/// Returns the TypeAccessor of a type, or null if FastMember doesn't work on the type.
/// </summary>
/// <param name="type">The type to get the TypeAccessor for</param>
/// <returns>A TypeAccessor instance that can be used as a faster alternative to reflection, or null if FastMember doesn't work on the type</returns>
public static TypeAccessor GetTypeAccessor(Type type)
{
TypeAccessor typeAccessor;
if (Cache.TryGetValue(type, out typeAccessor))
{
return typeAccessor;
}
// TypeAccessor has issues with dynamic types and inner types of generic classes
// In those cases we fall back to reflection, which is significantly slower but has less limitations
if (type.DeclaringType?.ContainsGenericParameters != true &&
!typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
{
typeAccessor = TypeAccessor.Create(type);
}
Cache.Add(type, typeAccessor);
return typeAccessor;
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
using FastMember;
namespace Python.Runtime
{
/// <summary>
/// TypeAccessorManager creates TypeAccessor instances when necessary.
/// </summary>
public class TypeAccessorManager
{
private static readonly Dictionary<Type, TypeAccessor> Cache = new Dictionary<Type, TypeAccessor>(128);
/// <summary>
/// Returns the TypeAccessor of a type, or null if FastMember doesn't work on the type.
/// </summary>
/// <param name="type">The type to get the TypeAccessor for</param>
/// <returns>A TypeAccessor instance that can be used as a faster alternative to reflection, or null if FastMember doesn't work on the type</returns>
public static TypeAccessor GetTypeAccessor(Type type)
{
TypeAccessor typeAccessor;
if (Cache.TryGetValue(type, out typeAccessor))
{
return typeAccessor;
}
// TypeAccessor has issues with dynamic types and inner types of generic classes
// In those cases we fall back to reflection, which is significantly slower but has less limitations
if (type.DeclaringType?.ContainsGenericParameters != true &&
!typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
{
typeAccessor = TypeAccessor.Create(type);
}
Cache.Add(type, typeAccessor);
return typeAccessor;
}
}
}
| mit | C# |
22d993ae6bc88fd8eceb0edfa30cb83285067082 | Remove IOperation.IsInstantaneous, no longer needed. | huin/kerbcam2 | kerbcam2/IOperation.cs | kerbcam2/IOperation.cs |
namespace kerbcam2 {
/// <summary>
/// Handles modification of the world (or camera) during a given time range.
/// Strictly speaking, the times are inclusive of the start time, and
/// exclusive of the end time, except where they are equal, which implies
/// an instantaneous effect.
/// </summary>
interface IOperation {
/// <summary>
/// Returns the earliest TimeKey for the operation.
/// </summary>
/// <returns>Earliest TimeKey for the operation.</returns>
TimeKey GetStartTime();
/// <summary>
/// Returns the latest TimeKey for the operation. This is equal to the
/// start time when the operation is instantaneous.
/// </summary>
/// <returns>Earliest TimeKey for the operation.</returns>
TimeKey GetEndTime();
/// <summary>
/// The timeline that the operation uses for its TimeKeys.
/// </summary>
/// <returns>The related Timeline.</returns>
Timeline GetTimeline();
// TODO: Method(s) relating to having an effect on the world.
// The methods within "Mutate world" cause the operation to act upon
// the world.
#region Mutate world
/// <summary>
/// Tells the operation to precompute anything it needs to prior to
/// playback.
/// </summary>
void PrepareForUpdates();
void UpdateFor(Actuators actuators, float time);
// Things that interpolate across multiple time keys will need to track
// which relevant time keys they are between.
#endregion
}
}
|
namespace kerbcam2 {
/// <summary>
/// Handles modification of the world (or camera) during a given time range.
/// Strictly speaking, the times are inclusive of the start time, and
/// exclusive of the end time, except where they are equal, which implies
/// an instantaneous effect.
/// </summary>
interface IOperation {
/// <summary>
/// Returns the earliest TimeKey for the operation.
/// </summary>
/// <returns>Earliest TimeKey for the operation.</returns>
TimeKey GetStartTime();
/// <summary>
/// Returns the latest TimeKey for the operation. This is equal to the
/// start time when the operation is instantaneous.
/// </summary>
/// <returns>Earliest TimeKey for the operation.</returns>
TimeKey GetEndTime();
/// <summary>
/// Is this operation an instantaneous operation?
/// </summary>
/// <returns>true if the operation is instantaneous.</returns>
bool IsInstantaneous();
/// <summary>
/// The timeline that the operation uses for its TimeKeys.
/// </summary>
/// <returns>The related Timeline.</returns>
Timeline GetTimeline();
// TODO: Method(s) relating to having an effect on the world.
// The methods within "Mutate world" cause the operation to act upon
// the world.
#region Mutate world
/// <summary>
/// Tells the operation to precompute anything it needs to prior to
/// playback.
/// </summary>
void PrepareForUpdates();
void UpdateFor(Actuators actuators, float time);
// Things that interpolate across multiple time keys will need to track
// which relevant time keys they are between.
#endregion
}
}
| bsd-3-clause | C# |
c34d4123d71d9d829510e9aaa8ca8a54878ed0e7 | Update StubBehavior.cs | XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors | tests/Avalonia.Xaml.Interactivity.UnitTests/StubBehavior.cs | tests/Avalonia.Xaml.Interactivity.UnitTests/StubBehavior.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Xaml.Interactivity.UnitTests
{
public class StubBehavior : AvaloniaObject, IBehavior
{
public int AttachCount
{
get;
private set;
}
public int DetachCount
{
get;
private set;
}
public ActionCollection Actions
{
get;
private set;
}
public StubBehavior()
{
Actions = new ActionCollection();
}
public AvaloniaObject AssociatedObject
{
get;
private set;
}
public void Attach(AvaloniaObject avaloniaObject)
{
AssociatedObject = avaloniaObject;
AttachCount++;
}
public void Detach()
{
AssociatedObject = null;
DetachCount++;
}
public IEnumerable<object> Execute(object sender, object parameter)
{
return Interaction.ExecuteActions(sender, Actions, parameter);
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections.Generic;
namespace Avalonia.Xaml.Interactivity.UnitTests
{
public class StubBehavior : AvaloniaObject, IBehavior
{
public int AttachCount
{
get;
private set;
}
public int DetachCount
{
get;
private set;
}
public ActionCollection Actions
{
get;
private set;
}
public StubBehavior()
{
Actions = new ActionCollection();
}
public AvaloniaObject AssociatedObject
{
get;
private set;
}
public void Attach(AvaloniaObject AvaloniaObject)
{
AssociatedObject = AvaloniaObject;
AttachCount++;
}
public void Detach()
{
AssociatedObject = null;
DetachCount++;
}
public IEnumerable<object> Execute(object sender, object parameter)
{
return Interaction.ExecuteActions(sender, Actions, parameter);
}
}
}
| mit | C# |
46c0f9ed8635f330319d53ae4596e80e3067bff4 | Remove unused imports | MHeasell/Mappy,MHeasell/Mappy | Mappy/Models/IMapViewSettingsModel.cs | Mappy/Models/IMapViewSettingsModel.cs | namespace Mappy.Models
{
using System;
using System.Drawing;
using System.Windows.Forms;
using Mappy.Database;
public interface IMapViewSettingsModel
{
IObservable<bool> GridVisible { get; }
IObservable<Color> GridColor { get; }
IObservable<Size> GridSize { get; }
IObservable<bool> HeightmapVisible { get; }
IObservable<bool> FeaturesVisible { get; }
IObservable<IFeatureDatabase> FeatureRecords { get; }
IObservable<IMainModel> Map { get; }
IObservable<int> ViewportWidth { get; }
IObservable<int> ViewportHeight { get; }
void SetViewportSize(Size size);
void SetViewportLocation(Point pos);
void OpenFromDragDrop(string filename);
void DragDropData(IDataObject data, Point loc);
}
}
| namespace Mappy.Models
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Mappy.Data;
using Mappy.Database;
public interface IMapViewSettingsModel
{
IObservable<bool> GridVisible { get; }
IObservable<Color> GridColor { get; }
IObservable<Size> GridSize { get; }
IObservable<bool> HeightmapVisible { get; }
IObservable<bool> FeaturesVisible { get; }
IObservable<IFeatureDatabase> FeatureRecords { get; }
IObservable<IMainModel> Map { get; }
IObservable<int> ViewportWidth { get; }
IObservable<int> ViewportHeight { get; }
void SetViewportSize(Size size);
void SetViewportLocation(Point pos);
void OpenFromDragDrop(string filename);
void DragDropData(IDataObject data, Point loc);
}
}
| mit | C# |
faa9c244842262cfeec00ce94011f45911959a1e | fix jtoken | Xarlot/NGitLab,maikebing/NGitLab | NGitLab/NGitLab/Json/Sha1Converter.cs | NGitLab/NGitLab/Json/Sha1Converter.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NGitLab.Json {
public class Sha1Converter : JsonConverter {
public override bool CanConvert(Type objectType) {
return objectType == typeof(Sha1);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
return new Sha1((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
JToken token = JToken.FromObject(value.ToString());
token.WriteTo(writer);
}
}
}
| using System;
using Newtonsoft.Json;
namespace NGitLab.Json {
public class Sha1Converter : JsonConverter {
public override bool CanConvert(Type objectType) {
return objectType == typeof(Sha1);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
return new Sha1((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
JToken token = JToken.FromObject(value.ToString());
token.WriteTo(writer);
}
}
}
| mit | C# |
04750ce524823faa1a0091e0e49c2e1419be2727 | Use ReactiveUI Events for Loaded and SelectionChanged | ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms | Ets.Mobile/Ets.Mobile.WindowsPhone/Pages/Main/MainPage.xaml.cs | Ets.Mobile/Ets.Mobile.WindowsPhone/Pages/Main/MainPage.xaml.cs | using System;
using Windows.UI.Xaml;
using EventsMixin = Windows.UI.Xaml.Controls.EventsMixin;
namespace Ets.Mobile.Pages.Main
{
public sealed partial class MainPage
{
partial void PartialInitialize()
{
// Ensure to hide the status bar
var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
statusBar.BackgroundOpacity = 0;
statusBar.HideAsync().GetResults();
// Handle the button visibility according to Pivot Context (SelectedIndex)
this.Events().Loaded.Subscribe(e =>
{
EventsMixin.Events(MainPivot).SelectionChanged.Subscribe(e2 =>
{
RefreshToday.Visibility = Visibility.Collapsed;
RefreshGrade.Visibility = Visibility.Collapsed;
switch (MainPivot.SelectedIndex)
{
case (int)MainPivotItem.Today:
RefreshToday.Visibility = Visibility.Visible;
break;
case (int)MainPivotItem.Grade:
RefreshGrade.Visibility = Visibility.Visible;
break;
}
});
});
}
}
} | using ReactiveUI;
using Windows.UI.Xaml;
namespace Ets.Mobile.Pages.Main
{
public sealed partial class MainPage
{
partial void PartialInitialize()
{
// Ensure to hide the status bar
var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
statusBar.BackgroundOpacity = 0;
statusBar.HideAsync().GetResults();
// Grade Presenter
// NOTE: Do not remove this code, can't bind to the presenter's source
this.OneWayBind(ViewModel, x => x.GradesPresenter, x => x.Grade.DataContext);
// Handle the button visibility according to Pivot Context (SelectedIndex)
Loaded += (s, e) =>
{
MainPivot.SelectionChanged += (sender, e2) =>
{
RefreshToday.Visibility = Visibility.Collapsed;
RefreshGrade.Visibility = Visibility.Collapsed;
switch (MainPivot.SelectedIndex)
{
case (int)MainPivotItem.Today:
RefreshToday.Visibility = Visibility.Visible;
break;
case (int)MainPivotItem.Grade:
RefreshGrade.Visibility = Visibility.Visible;
break;
}
};
};
}
}
} | apache-2.0 | C# |
8044107b5f3597c7a034dbe2946b919b4988f9f8 | update the solution for karaoke. | komitoff/Softuni-Programming-Fundamentals,komitoff/Softuni-Programming-Fundamentals,komitoff/Softuni-Programming-Fundamentals,komitoff/Softuni-Programming-Fundamentals,komitoff/Softuni-Programming-Fundamentals | ExamPreparation/Exam1June2016/SoftuniKaraoke/SoftuniKaraoke.cs | ExamPreparation/Exam1June2016/SoftuniKaraoke/SoftuniKaraoke.cs | using System;
using System.Collections.Generic;
using System.Linq;
class SoftuniKaraoke
{
static void Main()
{
List<string> appliedParticipants = Console.ReadLine().Split(',').ToList();
List<string> aviableSongs = Console.ReadLine().TrimStart().Split(',').ToList();
for (int i = 0; i < appliedParticipants.Count; i++)
{
appliedParticipants[i] = appliedParticipants[i].TrimStart();
}
for (int i = 0; i < aviableSongs.Count; i++)
{
aviableSongs[i] = aviableSongs[i].TrimStart();
}
Dictionary<string, List<string>> awardedParticipants =
new Dictionary<string, List<string>>();
string cmd = Console.ReadLine();
while (!cmd.Equals("dawn"))
{
string[] execution = cmd.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string participant = execution[0].TrimStart();
string song = execution[1].TrimStart();
string award = execution[2].TrimStart();
if (aviableSongs.Contains(song) && appliedParticipants.Contains(participant))
{
AddAward(participant, song, award, awardedParticipants);
}
cmd = Console.ReadLine();
}
if (awardedParticipants.Count == 0)
{
Console.WriteLine("No awards");
}
foreach (var person in awardedParticipants.OrderByDescending(p => p.Value.Count).ThenBy(p => p.Key))
{
Console.WriteLine($"{person.Key}: {person.Value.Count} awards");
string[] awards = awardedParticipants[person.Key].OrderBy(x => x).ToArray();
foreach (var award in awardedParticipants[person.Key].OrderBy(x => x))
{
Console.WriteLine($"--{award}");
}
}
}
private static void AddAward(string participant, string song, string award, Dictionary<string, List<string>> awardedParticipants)
{
if (!awardedParticipants.ContainsKey(participant))
{
awardedParticipants.Add(participant,new List<string>());
}
if (!awardedParticipants[participant].Contains(award))
{
awardedParticipants[participant].Add(award);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
class SoftuniKaraoke
{
static void Main()
{
List<string> appliedParticipants = Console.ReadLine().Split(',').ToList();
List<string> aviableSongs = Console.ReadLine().TrimStart().Split(',').ToList();
for (int i = 0; i < appliedParticipants.Count; i++)
{
appliedParticipants[i] = appliedParticipants[i].TrimStart();
}
for (int i = 0; i < aviableSongs.Count; i++)
{
aviableSongs[i] = aviableSongs[i].TrimStart();
}
Dictionary<string, List<string>> awardedParticipants =
new Dictionary<string, List<string>>();
string cmd = Console.ReadLine();
while (!cmd.Equals("dawn"))
{
string[] execution = cmd.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string participant = execution[0].TrimStart();
string song = execution[1].TrimStart();
string award = execution[2].TrimStart();
if (aviableSongs.Contains(song) && appliedParticipants.Contains(participant))
{
AddAward(participant, song, award, awardedParticipants);
}
cmd = Console.ReadLine();
}
if (awardedParticipants.Count == 0)
{
Console.WriteLine("No awards");
}
foreach (var person in awardedParticipants.OrderByDescending(p => p.Value.Count).ThenBy(p => p.Key))
{
Console.WriteLine($"{person.Key}: {person.Value.Count} awards");
string[] awards = awardedParticipants[person.Key].OrderBy(x => x).ToArray();
foreach (var award in awards)
{
Console.WriteLine($"--{award}");
}
}
}
private static void AddAward(string participant, string song, string award, Dictionary<string, List<string>> awardedParticipants)
{
if (!awardedParticipants.ContainsKey(participant))
{
awardedParticipants.Add(participant,new List<string>());
}
if (!awardedParticipants[participant].Contains(award))
{
awardedParticipants[participant].Add(award);
}
}
} | mit | C# |
f6315a8986a513361c3f199d7da651dac53fb8f6 | Add OutputEvent. | Microsoft/vscode-mono-debug,Microsoft/vscode-mono-debug | src/common/Events.cs | src/common/Events.cs | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace OpenDebug
{
public class DebugEvent
{
public string type { get; set; }
public DebugEvent(string typ) {
type = typ;
}
}
public class InitializedEvent : DebugEvent
{
public InitializedEvent() : base("initialized") {
}
}
public class StoppedEvent : DebugEvent
{
public int threadId { get; set; }
public string reason { get; set; }
public Source source { get; set; }
public int line { get; set; }
public int column { get; set; }
public string text { get; set; }
public StoppedEvent(string reasn, Source src, int ln, int col = 0, string txt = null, int tid = 0) : base("stopped") {
reason = reasn;
source = src;
line = ln;
column = col;
text = txt;
threadId = tid;
}
}
public class ExitedEvent : DebugEvent
{
public int exitCode { get; set; }
public ExitedEvent(int exCode) : base("exited") {
exitCode = exCode;
}
}
public class TerminatedEvent : DebugEvent
{
public TerminatedEvent() : base("terminated") {
}
}
public class ThreadEvent : DebugEvent
{
public string reason { get; set; }
public int threadId { get; set; }
public ThreadEvent(string reasn, int tid) : base("thread") {
reason = reasn;
threadId = tid;
}
}
public class OutputEvent : DebugEvent
{
public string category { get; set; }
public string output { get; set; }
public enum Category { console, stdout, stderr };
public OutputEvent(Category cat, string outpt) : base("output") {
if (cat == Category.stdout)
category = "stdout";
else if (cat == Category.stderr)
category = "stderr";
else
category = "console";
output = outpt;
}
public OutputEvent(string outpt) : this(Category.console, outpt)
{
}
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace OpenDebug
{
public class DebugEvent
{
public string type { get; set; }
public DebugEvent(string typ) {
type = typ;
}
}
public class InitializedEvent : DebugEvent
{
public InitializedEvent() : base("initialized") {
}
}
public class StoppedEvent : DebugEvent
{
public int threadId { get; set; }
public string reason { get; set; }
public Source source { get; set; }
public int line { get; set; }
public int column { get; set; }
public string text { get; set; }
public StoppedEvent(string reasn, Source src, int ln, int col = 0, string txt = null, int tid = 0) : base("stopped") {
reason = reasn;
source = src;
line = ln;
column = col;
text = txt;
threadId = tid;
}
}
public class ExitedEvent : DebugEvent
{
public int exitCode { get; set; }
public ExitedEvent(int exCode) : base("exited") {
exitCode = exCode;
}
}
public class TerminatedEvent : DebugEvent
{
public TerminatedEvent() : base("terminated") {
}
}
public class ThreadEvent : DebugEvent
{
public string reason { get; set; }
public int threadId { get; set; }
public ThreadEvent(string reasn, int tid) : base("thread") {
reason = reasn;
threadId = tid;
}
}
}
| mit | C# |
4d0d1fd8674639f1ed8c59735edef29b08cb41ca | Update DurationToDateTimeOffsetConverter.cs | Nikey646/VndbSharp | VndbSharp/Json/Converters/DurationToDateTimeOffsetConverter.cs | VndbSharp/Json/Converters/DurationToDateTimeOffsetConverter.cs | using System;
using Newtonsoft.Json;
namespace VndbSharp.Json.Converters
{
internal class DurationToDateTimeOffsetConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
{
// Is this the correct order? Or should it be 'value - Now'?
serializer.Serialize(writer, (DateTime.Now - (DateTimeOffset) value).TotalSeconds);
}
public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Float) // Is float the type we want here :?
return default(DateTimeOffset);
var seconds = (Double) reader.Value;
return new DateTimeOffset(DateTime.Now).AddSeconds(seconds);
}
public override Boolean CanConvert(Type objectType)
=> objectType == typeof(DateTimeOffset);
}
}
| using System;
using Newtonsoft.Json;
namespace VndbSharp.Json.Converters
{
internal class DurationToDateTimeOffsetConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
{
// Is this the correct order? Or should it be 'value - Now'?
serializer.Serialize(writer, (DateTime.Now - (DateTimeOffset) value).TotalSeconds);
}
public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Float) // Is float the type we want here :?
return default(DateTimeOffset);
var seconds = (Double) reader.Value;
return new DateTimeOffset(DateTime.Now).ToOffset(TimeSpan.FromSeconds(seconds));
}
public override Boolean CanConvert(Type objectType)
=> objectType == typeof(DateTimeOffset);
}
}
| mit | C# |
83bf07d51b6be34b792ec52a2e5418b083dc6fb5 | Update DateContextEnum.cs | ADAPT/ADAPT | source/ADAPT/Common/DateContextEnum.cs | source/ADAPT/Common/DateContextEnum.cs | /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* Copyright (C) 2019 Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* Tarak Reddy, Tim Shearouse - initial API and implementation
* Kathleen Oneal - added additional values
* R. Andres Ferreyra - added PAIL / OM-related values, and comments.
*******************************************************************************/
namespace AgGateway.ADAPT.ApplicationDataModel.Common
{
public enum DateContextEnum
{
Approval,
ProposedStart,
ProposedEnd,
CropSeason, // Interval
TimingEvent, // Interval
ActualStart,
ActualEnd,
RequestedStart,
RequestedEnd,
Expiration, // Relevant for Plans, Work Orders, and Recommendations
Creation, // Relevant to any document or object instance
Modification, // Relevant to any document or object instance
ValidityRange, // Interval. Used for Recommendation documents, also for specialized ISO 19156 Observations (such as forecasts)
RequestedShipping,
ActualShipping,
Calibration, // Relevant to a DeviceElement (esp. Sensor)
Load,
Unload,
Suspend,
Resume,
Unspecified,
Installation, // When was the device, sensor, etc. installed?
Maintenance, // When was maintenance performed on the device, sensor, etc.?
PhenomenonTime, // Important attribute of an ISO 19156 Observation
ResultTime // Interval. Important attribute of an ISO 19156 Observation
}
}
| /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* Copyright (C) 2019 Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* Tarak Reddy, Tim Shearouse - initial API and implementation
* Kathleen Oneal - added additional values
* R. Andres Ferreyra - added PAIL / OM-related values, and comments.
*******************************************************************************/
namespace AgGateway.ADAPT.ApplicationDataModel.Common
{
public enum DateContextEnum
{
Approval,
ProposedStart,
ProposedEnd,
CropSeason, // Interval
TimingEvent, // Interval
ActualStart,
ActualEnd,
RequestedStart,
RequestedEnd,
Expiration,
Creation,
Modification,
ValidityRange, // Interval. Used for Recommendation documents, also for specialized ISO 19156 Observations (such as forecasts)
RequestedShipping,
ActualShipping,
Calibration,
Load,
Unload,
Suspend,
Resume,
Unspecified,
Installation, // When was the device, sensor, etc. installed?
Maintenance, // When was maintenance performed on the device, sensor, etc.?
PhenomenonTime, // Important attribute of an ISO 19156 Observation
ResultTime // Interval. Important attribute of an ISO 19156 Observation
}
}
| epl-1.0 | C# |
9abd73e0350bb472351f23fbe7831da8000d4d37 | Add GetTititleEstimate that accepts data from URI. | bigfont/webapi-cors | CORS/Controllers/ValuesController.cs | CORS/Controllers/ValuesController.cs | using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
return new string[] { "This is a CORS request.", "That works from any origin." };
}
}
}
| using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "This is a CORS request.", "That works from any origin." };
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." };
}
}
} | mit | C# |
ba98e0a15a7b44b1fc4911f4cf6b36409d655244 | Stop Equinox complaining about session download patch not being static | TorchAPI/Torch | Torch/Patches/SessionDownloadPatch.cs | Torch/Patches/SessionDownloadPatch.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;
namespace Torch.Patches
{
[PatchShim]
internal static class SessionDownloadPatch
{
internal static void Patch(PatchContext context)
{
context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
}
// ReSharper disable once InconsistentNaming
private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
{
if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
__result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Sandbox.Game.World;
using Torch.Managers.PatchManager;
using Torch.Mod;
using VRage.Game;
namespace Torch.Patches
{
[PatchShim]
internal class SessionDownloadPatch
{
internal static void Patch(PatchContext context)
{
context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic));
}
// ReSharper disable once InconsistentNaming
private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
{
if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID))
__result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
}
}
}
| apache-2.0 | C# |
522f7379e4ae244b27636657cbb020755013227f | Fix ColoreException test performing wrong comparison. | danpierce1/Colore,CoraleStudios/Colore,Sharparam/Colore,WolfspiritM/Colore | Colore.Tests/ColoreExceptionTests.cs | Colore.Tests/ColoreExceptionTests.cs | namespace Colore.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class ColoreExceptionTests
{
[Test]
public void ShouldSetMessage()
{
const string Expected = "Test message.";
Assert.AreEqual(Expected, new ColoreException("Test message.").Message);
}
[Test]
public void ShouldSetInnerException()
{
var expected = new Exception("Expected.");
var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
Assert.AreEqual(expected.GetType(), actual.GetType());
Assert.AreEqual(expected.Message, actual.Message);
}
}
}
| namespace Colore.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class ColoreExceptionTests
{
[Test]
public void ShouldSetMessage()
{
const string Expected = "Test message.";
Assert.AreEqual(Expected, new ColoreException("Test message."));
}
[Test]
public void ShouldSetInnerException()
{
var expected = new Exception("Expected.");
var actual = new ColoreException(null, new Exception("Expected.")).InnerException;
Assert.AreEqual(expected.GetType(), actual.GetType());
Assert.AreEqual(expected.Message, actual.Message);
}
}
}
| mit | C# |
be1f22298266915202df31ea5c0f554c7e23cae9 | Update the ExposureNotifications (#887) | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | XPlat/ExposureNotification/build.cake | XPlat/ExposureNotification/build.cake | var TARGET = Argument("t", Argument("target", "ci"));
var SRC_COMMIT = "fcff875013295514a22e71648a7c6ad985dc4f9f";
var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip";
var OUTPUT_PATH = (DirectoryPath)"./output/";
var NUGET_VERSION = "0.5.0-preview";
Task("externals")
.Does(() =>
{
DownloadFile(SRC_URL, "./src.zip");
Unzip("./src.zip", "./");
MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src");
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
EnsureDirectoryExists(OUTPUT_PATH);
MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c
.SetConfiguration("Release")
.WithRestore()
.WithTarget("Build")
.WithTarget("Pack")
.WithProperty("PackageVersion", NUGET_VERSION)
.WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath));
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("nuget");
Task("clean")
.Does(() =>
{
CleanDirectories("./externals/");
});
Task("ci")
.IsDependentOn("nuget");
RunTarget(TARGET);
| var TARGET = Argument("t", Argument("target", "ci"));
var SRC_COMMIT = "fb7d888ebce17ab7d579a7c51c3e9ff30688502d";
var SRC_URL = $"https://github.com/xamarin/xamarin.exposurenotification/archive/{SRC_COMMIT}.zip";
var OUTPUT_PATH = (DirectoryPath)"./output/";
var NUGET_VERSION = "0.4.0-preview";
Task("externals")
.Does(() =>
{
DownloadFile(SRC_URL, "./src.zip");
Unzip("./src.zip", "./");
MoveDirectory($"./xamarin.exposurenotification-{SRC_COMMIT}", "./src");
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
EnsureDirectoryExists(OUTPUT_PATH);
MSBuild($"./src/Xamarin.ExposureNotification/Xamarin.ExposureNotification.csproj", c => c
.SetConfiguration("Release")
.WithRestore()
.WithTarget("Build")
.WithTarget("Pack")
.WithProperty("PackageVersion", NUGET_VERSION)
.WithProperty("PackageOutputPath", MakeAbsolute(OUTPUT_PATH).FullPath));
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("nuget");
Task("clean")
.Does(() =>
{
CleanDirectories("./externals/");
});
Task("ci")
.IsDependentOn("nuget");
RunTarget(TARGET);
| mit | C# |
68419a9510963c4c5f27caa7bfb88a3875b39a34 | Improve password reset email copy (#2211) | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Extensions/EmailSenderExtensions.cs | BTCPayServer/Extensions/EmailSenderExtensions.cs | using System.Text.Encodings.Web;
using BTCPayServer.Services.Mails;
namespace BTCPayServer.Services
{
public static class EmailSenderExtensions
{
private static string BODY_STYLE = "font-family: Open Sans, Helvetica Neue,Arial,sans-serif; font-color: #292929;";
private static string HEADER_HTML = "<h1 style='font-size:1.2rem'>BTCPay Server</h1><br/>";
private static string BUTTON_HTML = "<a href='{button_link}' type='submit' style='min-width: 2em;min-height: 20px;text-decoration-line: none;cursor: pointer;display: inline-block;font-weight: 400;color: #fff;text-align: center;vertical-align: middle;user-select: none;background-color: #51b13e;border-color: #51b13e;border: 1px solid transparent;padding: 0.375rem 0.75rem;font-size: 1rem;line-height: 1.5;border-radius: 0.25rem;transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;'>{button_description}</a>";
private static string CallToAction(string actionName, string actionLink)
{
string button = $"{BUTTON_HTML}".Replace("{button_description}", actionName, System.StringComparison.InvariantCulture);
button = button.Replace("{button_link}", actionLink, System.StringComparison.InvariantCulture);
return button;
}
public static void SendEmailConfirmation(this IEmailSender emailSender, string email, string link)
{
emailSender.SendEmail(email, "Confirm your email",
$"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>link</a>");
}
public static void SendSetPasswordConfirmation(this IEmailSender emailSender, string email, string link, bool newPassword)
{
var subject = $"{(newPassword ? "Set" : "Update")} Password";
var body = $"A request has been made to {(newPassword ? "set" : "update")} your BTCPay Server password. Please confirm your password by clicking below. <br/><br/> {CallToAction(subject, HtmlEncoder.Default.Encode(link))}";
emailSender.SendEmail(email,
subject,
$"<html><body style='{BODY_STYLE}'>{HEADER_HTML}{body}</body></html>");
}
}
}
| using System.Text.Encodings.Web;
using BTCPayServer.Services.Mails;
namespace BTCPayServer.Services
{
public static class EmailSenderExtensions
{
public static void SendEmailConfirmation(this IEmailSender emailSender, string email, string link)
{
emailSender.SendEmail(email, "Confirm your email",
$"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>link</a>");
}
public static void SendSetPasswordConfirmation(this IEmailSender emailSender, string email, string link, bool newPassword)
{
emailSender.SendEmail(email,
$"{(newPassword ? "Set" : "Reset")} Password",
$"Please {(newPassword ? "set" : "reset")} your password by clicking here: <a href='{link}'>link</a>");
}
}
}
| mit | C# |
3f4345918fef5162ab200598528f2a1a4c6c6f6c | Update VehicleService.cs | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Services/VehicleService.cs | Battery-Commander.Web/Services/VehicleService.cs | using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class VehicleService
{
public static async Task Reset_Convoy(Database db, Query query)
{
foreach (var vehicle in await Filter(db, query))
{
vehicle.DriverId = null;
vehicle.A_DriverId = null;
vehicle.Chalk = Vehicle.VehicleChalk.Unknown;
vehicle.OrderOfMarch = 0;
foreach (var passenger in vehicle.Passengers.ToList())
{
vehicle.Passengers.Remove(passenger);
}
}
await db.SaveChangesAsync();
}
public static async Task<IEnumerable<Vehicle>> Filter(Database db, Query query)
{
var vehicles =
db
.Vehicles
.Include(vehicle => vehicle.Unit)
.Include(vehicle => vehicle.Driver)
.Include(vehicle => vehicle.A_Driver)
.Include(vehicle => vehicle.Passengers)
.ThenInclude(passenger => passenger.Soldier)
.AsEnumerable();
if (query.Units?.Any() == true)
{
vehicles = vehicles.Where(vehicle => query.Units.Contains(vehicle.UnitId));
}
if (query.Available.HasValue)
{
vehicles = vehicles.Where(vehicle => vehicle.Available == query.Available);
}
return
vehicles
.OrderBy(vehicle => vehicle.Chalk)
.ThenBy(vehicle => vehicle.OrderOfMarch);
}
public class Query
{
public int[] Units { get; set; } = new int[] { };
public Boolean? Available { get; set; } = true;
}
}
}
| using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class VehicleService
{
public static async Task Reset_Convoy(Database db, Query query)
{
foreach (var vehicle in await Filter(db, query))
{
vehicle.DriverId = null;
vehicle.A_DriverId = null;
vehicle.Chalk = Vehicle.VehicleChalk.Unknown;
vehicle.OrderOfMarch = 0;
foreach (var passenger in vehicle.Passengers.ToList())
{
vehicle.Passengers.Remove(passenger);
}
}
await db.SaveChangesAsync();
}
public static async Task<IEnumerable<Vehicle>> Filter(Database db, Query query)
{
var vehicles =
db
.Vehicles
.Include(vehicle => vehicle.Unit)
.Include(vehicle => vehicle.Driver)
.Include(vehicle => vehicle.A_Driver)
.Include(vehicle => vehicle.Passengers)
.ThenInclude(passenger => passenger.Soldier)
.AsEnumerable();
if (query.Units?.Any() == true)
{
vehicles = vehicles.Where(vehicle => query.Units.Contains(vehicle.UnitId));
}
if (query.Available.HasValue)
{
vehicles = vehicles.Where(vehicle => vehicle.Available == query.Available);
}
return
vehicles
.OrderBy(vehicle => vehicle.Chalk)
.ThenBy(vehicle => vehicle.OrderOfMarch);
}
public class Query
{
public int[] Units { get; set; }
public Boolean? Available { get; set; } = true;
}
}
} | mit | C# |
d639d329789153a4b9e20890efcdf2f55276129f | Move details to first in list | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Soldiers/List.cshtml | Battery-Commander.Web/Views/Soldiers/List.cshtml | @model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id })
</td>
</tr>
}
</tbody>
</table> | mit | C# |
f41f14042382a817c35bc21e34fb0c6036ca7f19 | Add to soldier list | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Soldiers/List.cshtml | Battery-Commander.Web/Views/Soldiers/List.cshtml | @model IEnumerable<Soldier>
<h2>Soldiers</h2>
@Html.ActionLink("Add New Soldier", "New")
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<Soldier>
<h2>Soldiers</h2>
@Html.ActionLink("Add New Soldier", "New")
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
</tr>
}
</tbody>
</table> | mit | C# |
01911993b4dd7140f8a4766365e5daebd0d13ee6 | Add thread-safe random number instance | benjaminramey/Faker | Faker/NumberFaker.cs | Faker/NumberFaker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Faker
{
public static class NumberFaker
{
private static readonly RNGCryptoServiceProvider Global = new RNGCryptoServiceProvider();
[ThreadStatic]
private static Random _local;
private static Random Local
{
get
{
Random inst = _local;
if (inst == null)
{
byte[] buffer = new byte[4];
Global.GetBytes(buffer);
_local = inst = new Random(
BitConverter.ToInt32(buffer, 0));
}
return inst;
}
}
public static int Number()
{
return Local.Next();
}
public static int Number(int maxValue)
{
return Local.Next(maxValue);
}
public static int Number(int minValue, int maxValue)
{
return Local.Next(minValue, maxValue);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Faker
{
public static class NumberFaker
{
private static Random _random = new Random();
public static int Number()
{
return _random.Next();
}
public static int Number(int maxValue)
{
return _random.Next(maxValue);
}
public static int Number(int minValue, int maxValue)
{
return _random.Next(minValue, maxValue);
}
}
}
| apache-2.0 | C# |
fc3e9280ede7afe7f1bbf9d4332eb08a7087098f | Add namespace (#823) | GeertvanHorrik/Fody,Fody/Fody | FodyHelpers/Guard.cs | FodyHelpers/Guard.cs | using System;
using System.IO;
namespace Fody
{
[Obsolete("Not for public use")]
public static class Guard
{
public static void AgainstNull(string argumentName, object value)
{
if (value == null)
{
throw new ArgumentNullException(argumentName);
}
}
public static void AgainstNullAndEmpty(string argumentName, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(argumentName);
}
}
public static void FileExists(string argumentName, string path)
{
AgainstNullAndEmpty(argumentName, path);
if (!File.Exists(path))
{
throw new ArgumentException($"File not found. Path: {path}");
}
}
}
}
| using System;
using System.IO;
[Obsolete("Not for public use")]
public static class Guard
{
public static void AgainstNull(string argumentName, object value)
{
if (value == null)
{
throw new ArgumentNullException(argumentName);
}
}
public static void AgainstNullAndEmpty(string argumentName, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(argumentName);
}
}
public static void FileExists(string argumentName, string path)
{
AgainstNullAndEmpty(argumentName, path);
if (!File.Exists(path))
{
throw new ArgumentException($"File not found. Path: {path}");
}
}
} | mit | C# |
e3c29b46fe2f3af3be5e54b08fc198c263db88cf | Revert "Another hack" | matthew-a-thomas/gps-logger,matthew-a-thomas/gps-logger | GPSLogger/Program.cs | GPSLogger/Program.cs | using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace GPSLogger
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace GPSLogger
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| mit | C# |
581cfd7518261a5ea7a6976416db20b6509a422e | Update version number to 0.4.0. | beppler/trayleds | TrayLeds/Properties/AssemblyInfo.cs | TrayLeds/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © 2017 Carlos Alberto Costa Beppler")]
// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © 2017 Carlos Alberto Costa Beppler")]
// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.2.0")]
[assembly: AssemblyFileVersion("0.3.2.0")]
| mit | C# |
fa74d4313f9b91c7f3a20259c2d9337d6fa651af | make Internal Aggregate State as Serializable. | selganor74/Jarvis.Framework,selganor74/Jarvis.Framework,selganor74/Jarvis.Framework,ProximoSrl/Jarvis.Framework | Jarvis.Framework.Kernel/Engine/AggregateState.cs | Jarvis.Framework.Kernel/Engine/AggregateState.cs | using System;
using Fasterflect;
using Jarvis.Framework.Shared.Events;
using Jarvis.Framework.Shared.IdentitySupport;
using Jarvis.NEventStoreEx.CommonDomainEx;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Jarvis.Framework.Kernel.Engine
{
/// <summary>
/// Stato interno dell'aggregato
/// Deve implementare ICloneable se usa strutture o referenze ad oggetti
/// </summary>
[Serializable]
public abstract class AggregateState : ICloneable, IInvariantsChecker
{
/// <summary>
/// Clona lo stato con una copia secca dei valori. Va reimplementata nel caso di utilizzo di strutture o referenze ad oggetti
/// </summary>
/// <returns>copia dello stato</returns>
public object Clone()
{
return DeepCloneMe();
}
public void Apply(IDomainEvent evt)
{
var method = GetType().Method("When", new [] {evt.GetType()}, Flags.InstanceAnyVisibility);
if(method != null)
method.Invoke(this, new object[]{evt});
}
public virtual InvariantCheckResult CheckInvariants()
{
return InvariantCheckResult.Success;
}
/// <summary>
/// Create a deep clone with Serialization. It can be overriden in derived
/// class if you want a more performant way to clone the object. Using
/// serialization gives us the advantage of automatic creation of deep cloned
/// object.
/// </summary>
/// <returns></returns>
protected virtual Object DeepCloneMe()
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new MemoryStream())
{
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(stream);
}
}
}
} | using System;
using Fasterflect;
using Jarvis.Framework.Shared.Events;
using Jarvis.Framework.Shared.IdentitySupport;
using Jarvis.NEventStoreEx.CommonDomainEx;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Jarvis.Framework.Kernel.Engine
{
/// <summary>
/// Stato interno dell'aggregato
/// Deve implementare ICloneable se usa strutture o referenze ad oggetti
/// </summary>
public abstract class AggregateState : ICloneable, IInvariantsChecker
{
/// <summary>
/// Clona lo stato con una copia secca dei valori. Va reimplementata nel caso di utilizzo di strutture o referenze ad oggetti
/// </summary>
/// <returns>copia dello stato</returns>
public object Clone()
{
return DeepCloneMe();
}
public void Apply(IDomainEvent evt)
{
var method = GetType().Method("When", new [] {evt.GetType()}, Flags.InstanceAnyVisibility);
if(method != null)
method.Invoke(this, new object[]{evt});
}
public virtual InvariantCheckResult CheckInvariants()
{
return InvariantCheckResult.Success;
}
/// <summary>
/// Create a deep clone with Serialization. It can be overriden in derived
/// class if you want a more performant way to clone the object. Using
/// serialization gives us the advantage of automatic creation of deep cloned
/// object.
/// </summary>
/// <returns></returns>
protected virtual Object DeepCloneMe()
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new MemoryStream())
{
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(stream);
}
}
}
} | mit | C# |
fc43d93f58e0b889ed0d0c5be364b74ccac6ea29 | Update InclusionChecker.cs | Fody/Virtuosity | Virtuosity.Fody/InclusionChecker.cs | Virtuosity.Fody/InclusionChecker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
public partial class ModuleWeaver
{
public Func<TypeDefinition, bool> ShouldIncludeType;
List<LineMatcher> lineMatchers;
public void ProcessIncludesExcludes()
{
if (ExcludeNamespaces.Any())
{
lineMatchers = GetLines(ExcludeNamespaces).ToList();
ShouldIncludeType = type =>
{
return lineMatchers.All(lineMatcher => !lineMatcher.Match(type.Namespace)) &&
!ContainsIgnoreAttribute(type);
};
return;
}
if (IncludeNamespaces.Any())
{
lineMatchers = GetLines(IncludeNamespaces).ToList();
ShouldIncludeType = type =>
{
return lineMatchers.Any(lineMatcher => lineMatcher.Match(type.Namespace)) &&
!ContainsIgnoreAttribute(type);
};
return;
}
ShouldIncludeType = definition => !ContainsIgnoreAttribute(definition);
}
bool ContainsIgnoreAttribute(TypeDefinition typeDefinition)
{
return typeDefinition.CustomAttributes.ContainsAttribute("DoNotVirtualizeAttribute");
}
public static IEnumerable<LineMatcher> GetLines(List<string> namespaces)
{
return namespaces.Select(BuildLineMatcher);
}
public static LineMatcher BuildLineMatcher(string line)
{
var starStart = false;
if (line.StartsWith("*"))
{
starStart = true;
line = line.Substring(1);
}
var starEnd = false;
if (line.EndsWith("*"))
{
starEnd = true;
line = line.Substring(0, line.Length - 1);
}
ValidateLine(line);
return new LineMatcher
{
Line = line,
StarStart = starStart,
StarEnd = starEnd,
};
}
// ReSharper disable once UnusedParameter.Local
static void ValidateLine(string line)
{
if (line.Contains("*"))
{
throw new Exception("Namespaces can't only start or end with '*'.");
}
if (line.Contains(" "))
{
throw new Exception("Namespaces cant contain spaces.");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
public partial class ModuleWeaver
{
public Func<TypeDefinition, bool> ShouldIncludeType;
List<LineMatcher> lineMatchers;
public void ProcessIncludesExcludes()
{
if (ExcludeNamespaces.Any())
{
lineMatchers = GetLines(ExcludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.All(lineMatcher => !lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
if (IncludeNamespaces.Any())
{
lineMatchers = GetLines(IncludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.Any(lineMatcher => lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
ShouldIncludeType = definition => !ContainsIgnoreAttribute(definition);
}
bool ContainsIgnoreAttribute(TypeDefinition typeDefinition)
{
return typeDefinition.CustomAttributes.ContainsAttribute("DoNotVirtualizeAttribute");
}
public static IEnumerable<LineMatcher> GetLines(List<string> namespaces)
{
return namespaces.Select(BuildLineMatcher);
}
public static LineMatcher BuildLineMatcher(string line)
{
var starStart = false;
if (line.StartsWith("*"))
{
starStart = true;
line = line.Substring(1);
}
var starEnd = false;
if (line.EndsWith("*"))
{
starEnd = true;
line = line.Substring(0, line.Length - 1);
}
ValidateLine(line);
return new LineMatcher
{
Line = line,
StarStart = starStart,
StarEnd = starEnd,
};
}
// ReSharper disable once UnusedParameter.Local
static void ValidateLine(string line)
{
if (line.Contains("*"))
{
throw new Exception("Namespaces can't only start or end with '*'.");
}
if (line.Contains(" "))
{
throw new Exception("Namespaces cant contain spaces.");
}
}
} | mit | C# |
0d62eed32b50c9ce5c8b3d570418f455916bace6 | update drpc demo. | ziyunhx/storm-net-adapter,ziyunhx/storm-net-adapter,ziyunhx/storm-net-adapter,ziyunhx/storm-net-adapter,ziyunhx/storm-net-adapter | src/Samples/Storm.DRPC.Demo/Program.cs | src/Samples/Storm.DRPC.Demo/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Storm;
namespace Storm.DRPC.Demo
{
public class Program
{
public static void Main(string[] args)
{
DRPCClient client = new DRPCClient("host", 3772);
string result = client.execute("simpledrpc", "hello word");
Console.WriteLine(result);
Console.WriteLine("Please input a word and press enter, if you want quit it, press enter only!");
do
{
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
break;
Console.WriteLine(client.execute("simpledrpc", input));
}
while (true);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Storm;
namespace Storm.DRPC.Demo
{
public class Program
{
public static void Main(string[] args)
{
DRPCClient client = new DRPCClient("mech.palaspom.com", 49772);
string result = client.execute("simpledrpc", "hello word");
Console.WriteLine(result);
Console.WriteLine("Please input a word and press enter, if you want quit it, press enter only!");
do
{
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
break;
Console.WriteLine(client.execute("simpledrpc", input));
}
while (true);
}
}
}
| apache-2.0 | C# |
2b7c4b9309749f8fa6ebe1a0e9b6e17fec4a0c6a | Remove duplicate code in TestUtil.cs | Vodurden/Http-Multipart-Data-Parser | Source/HttpMultipartParser.UnitTests/TestUtil.cs | Source/HttpMultipartParser.UnitTests/TestUtil.cs | using System.IO;
using System.Linq;
using System.Text;
namespace HttpMultipartParser.UnitTests
{
internal static class TestUtil
{
public static Stream StringToStream(string input)
{
return StringToStream(input, Encoding.UTF8);
}
public static Stream StringToStream(string input, Encoding encoding)
{
var stream = new MemoryStream();
#pragma warning disable IDE0067 // Dispose objects before losing scope
var writer = new StreamWriter(stream, encoding);
#pragma warning restore IDE0067 // Dispose objects before losing scope
writer.Write(input);
writer.Flush();
stream.Position = 0;
return stream;
}
// Assumes UTF8
public static Stream StringToStreamNoBom(string input)
{
return StringToStream(input, new UTF8Encoding(false));
}
public static byte[] StringToByteNoBom(string input)
{
var encoding = new UTF8Encoding(false);
return encoding.GetBytes(input);
}
public static string TrimAllLines(string input)
{
return
string.Concat(
input.Split('\n')
.Select(x => x.Trim())
.Aggregate((first, second) => first + '\n' + second)
.Where(x => x != '\r'));
/*return Regex.Split(input, "\n")
.Select(x => x.Trim())
.Where(x => x != "\r")
.Aggregate((first, second) => first + System.Environment.NewLine + second);*/
}
}
} | using System.IO;
using System.Linq;
using System.Text;
namespace HttpMultipartParser.UnitTests
{
internal static class TestUtil
{
public static Stream StringToStream(string input)
{
return StringToStream(input, Encoding.UTF8);
}
public static Stream StringToStream(string input, Encoding encoding)
{
var stream = new MemoryStream();
#pragma warning disable IDE0067 // Dispose objects before losing scope
var writer = new StreamWriter(stream, encoding);
#pragma warning restore IDE0067 // Dispose objects before losing scope
writer.Write(input);
writer.Flush();
stream.Position = 0;
return stream;
}
// Assumes UTF8
public static Stream StringToStreamNoBom(string input)
{
var stream = new MemoryStream();
#pragma warning disable IDE0067 // Dispose objects before losing scope
var writer = new StreamWriter(stream, new UTF8Encoding(false));
#pragma warning restore IDE0067 // Dispose objects before losing scope
writer.Write(input);
writer.Flush();
stream.Position = 0;
return stream;
}
public static byte[] StringToByteNoBom(string input)
{
var encoding = new UTF8Encoding(false);
return encoding.GetBytes(input);
}
public static string TrimAllLines(string input)
{
return
string.Concat(
input.Split('\n')
.Select(x => x.Trim())
.Aggregate((first, second) => first + '\n' + second)
.Where(x => x != '\r'));
/*return Regex.Split(input, "\n")
.Select(x => x.Trim())
.Where(x => x != "\r")
.Aggregate((first, second) => first + System.Environment.NewLine + second);*/
}
}
} | mit | C# |
0bb0d6125870c0380b855aa5d548dc78de1685f4 | Update IMongoUnitOfWorkFactory.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/Mongo/IMongoUnitOfWorkFactory.cs | TIKSN.Core/Data/Mongo/IMongoUnitOfWorkFactory.cs | using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.Mongo
{
public interface IMongoUnitOfWorkFactory
{
Task<IMongoUnitOfWork> CreateAsync(CancellationToken cancellationToken);
}
}
| using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.Mongo
{
public interface IMongoUnitOfWorkFactory
{
Task<IMongoUnitOfWork> CreateAsync(CancellationToken cancellationToken);
}
} | mit | C# |
48c297b017700726dd3cfcc21dcda4d1338ca534 | Bump version for beta | maxmind/GeoIP2-dotnet | GeoIP2/Properties/AssemblyInfo.cs | GeoIP2/Properties/AssemblyInfo.cs | #region
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#endregion
// 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("MaxMind.GeoIP2")]
[assembly: AssemblyDescription("MaxMind GeoIP2 Database Reader and Web Service Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MaxMind, Inc.")]
[assembly: AssemblyProduct("MaxMind.GeoIP2")]
[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("7352289c-bf62-4994-bc2b-6cf4c1ea4b2d")]
[assembly: CLSCompliant(true)]
// 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("2.3.0.0")]
[assembly: AssemblyFileVersion("2.4.0")]
[assembly: AssemblyInformationalVersion("2.4.0-beta1")]
[assembly: InternalsVisibleTo("MaxMind.GeoIP2.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | #region
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#endregion
// 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("MaxMind.GeoIP2")]
[assembly: AssemblyDescription("MaxMind GeoIP2 Database Reader and Web Service Client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MaxMind, Inc.")]
[assembly: AssemblyProduct("MaxMind.GeoIP2")]
[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("7352289c-bf62-4994-bc2b-6cf4c1ea4b2d")]
[assembly: CLSCompliant(true)]
// 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("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.1")]
[assembly: AssemblyInformationalVersion("2.3.1")]
[assembly: InternalsVisibleTo("MaxMind.GeoIP2.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | apache-2.0 | C# |
c2f18523c26e1e5d1b8a10b18266f7fc44d4d038 | Fix failing test | Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates | CurrencyRates.Tests/Web/Installers/ContextInstallerTest.cs | CurrencyRates.Tests/Web/Installers/ContextInstallerTest.cs | namespace CurrencyRates.Tests.Web.Installers
{
using Castle.Windsor;
using CurrencyRates.Model;
using CurrencyRates.Web.Installers;
using NUnit.Framework;
[TestFixture]
public class ContextInstallerTest
{
private IWindsorContainer containerWithContext;
[SetUp]
public void SetUp()
{
this.containerWithContext = new WindsorContainer();
this.containerWithContext.Install(new ContextInstaller());
}
[Test]
public void TestContextIsRegistered()
{
this.containerWithContext.Resolve<Context>();
}
}
}
| namespace CurrencyRates.Tests.Web.Installers
{
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ModelBuilder;
using Castle.Windsor;
using CurrencyRates.Model;
using CurrencyRates.Web.Installers;
using NUnit.Framework;
[TestFixture]
public class ContextInstallerTest
{
private IWindsorContainer containerWithContext;
[SetUp]
public void SetUp()
{
this.containerWithContext = new WindsorContainer();
this.containerWithContext.Kernel.ComponentModelBuilder.AddContributor(new LifestyleInspector());
this.containerWithContext.Install(new ContextInstaller());
}
[Test]
public void TestContextIsRegistered()
{
this.containerWithContext.Resolve<Context>();
}
private class LifestyleInspector : IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
Assert.That(model.LifestyleType, Is.EqualTo(LifestyleType.PerWebRequest));
// LifestyleType.PerWebRequest is not available outside .NET MVC
model.LifestyleType = LifestyleType.Undefined;
}
}
}
}
| mit | C# |
2caa7b50735595fb114dac5222aad04486df1b54 | Use Url instead of UrlPath. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | MitternachtWeb/Areas/User/Views/Verifications/Index.cshtml | MitternachtWeb/Areas/User/Views/Verifications/Index.cshtml | @model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>
<h4>Verifizierungen</h4>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.UserInfo.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Guild.Name)
</th>
</tr>
</thead>
<tbody>
@foreach(var (userInfo, guild) in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {
<img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a href="@userInfo.Url">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.Url : userInfo.Username)</a>
</td>
<td>
<a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a>
</td>
</tr>
}
</tbody>
</table>
</div> | @model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)>
<h4>Verifizierungen</h4>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.UserInfo.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Guild.Name)
</th>
</tr>
</thead>
<tbody>
@foreach(var (userInfo, guild) in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) {
<img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a href="@userInfo.UrlPath">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.UrlPath : userInfo.Username)</a>
</td>
<td>
<a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a>
</td>
</tr>
}
</tbody>
</table>
</div> | mit | C# |
2d75d75d2062726af37f0e472393494e1f248c70 | Fix prefix. | PenguinF/sandra-three | Sandra.UI.WF.Chess/SharedUIAction.cs | Sandra.UI.WF.Chess/SharedUIAction.cs | /*********************************************************************************
* SharedUIAction.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* 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;
namespace Sandra.UI.WF
{
internal static class SharedUIAction
{
public const string SharedUIActionPrefix = nameof(SharedUIAction) + ".";
public static readonly DefaultUIActionBinding ZoomIn = new DefaultUIActionBinding(
new UIAction(SharedUIActionPrefix + nameof(ZoomIn)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.ZoomIn,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.Add), },
});
public static readonly DefaultUIActionBinding ZoomOut = new DefaultUIActionBinding(
new UIAction(SharedUIActionPrefix + nameof(ZoomOut)),
new UIActionBinding()
{
ShowInMenu = true,
MenuCaptionKey = LocalizedStringKeys.ZoomOut,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.Subtract), },
});
}
}
| /*********************************************************************************
* SharedUIAction.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* 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;
namespace Sandra.UI.WF
{
internal static class SharedUIAction
{
public const string SharedUIActionPrefix = nameof(MovesTextBox) + ".";
public static readonly DefaultUIActionBinding ZoomIn = new DefaultUIActionBinding(
new UIAction(SharedUIActionPrefix + nameof(ZoomIn)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.ZoomIn,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.Add), },
});
public static readonly DefaultUIActionBinding ZoomOut = new DefaultUIActionBinding(
new UIAction(SharedUIActionPrefix + nameof(ZoomOut)),
new UIActionBinding()
{
ShowInMenu = true,
MenuCaptionKey = LocalizedStringKeys.ZoomOut,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.Subtract), },
});
}
}
| apache-2.0 | C# |
4957d7b6bda19408c64c2a2cf266baeea96e846b | Fix copyright year | locana/locana | Locana/Properties/AssemblyInfo.cs | Locana/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Locana")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Locana")]
[assembly: AssemblyCopyright("Copyright © kazyx 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
| using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Locana")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Locana")]
[assembly: AssemblyCopyright("Copyright © kazyx 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
| mit | C# |
c7c36b104afe215f6ddbebd94cc16b0615fdbcae | Make Local class public | BeowulfStratOps/BSU.Sync | FileTypes/BI/Local.cs | FileTypes/BI/Local.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BSU.Sync.FileTypes.BI
{
public class Local
{
[JsonProperty(propertyName: "autodetectionDirectories")]
public List<string> AutodetectionDirectories { get; set; }
[JsonProperty(propertyName: "dateCreated")]
public DateTime DateCreated { get; set; }
[JsonProperty(propertyName: "knownLocalMods")]
public List<string> KnownLocalMods { get; set; }
[JsonProperty(propertyName: "userDirectories")]
public List<string> UserDirectories { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BSU.Sync.FileTypes.BI
{
class Local
{
[JsonProperty(propertyName: "autodetectionDirectories")]
public List<string> AutodetectionDirectories { get; set; }
[JsonProperty(propertyName: "dateCreated")]
public DateTime DateCreated { get; set; }
[JsonProperty(propertyName: "knownLocalMods")]
public List<string> KnownLocalMods { get; set; }
[JsonProperty(propertyName: "userDirectories")]
public List<string> UserDirectories { get; set; }
}
}
| mit | C# |
93510c9537eab2767ada00112bd3538988a2dd65 | remove use of USE_GENERICS in DefaultPersistentComparator.cs | kjk/volante-obsolete,kjk/volante-obsolete,kjk/volante-obsolete,ingted/volante,kjk/volante-obsolete,ingted/volante,ingted/volante,ingted/volante | csharp/src/impl/DefaultPersistentComparator.cs | csharp/src/impl/DefaultPersistentComparator.cs | namespace NachoDB.Impl
{
using System;
using NachoDB;
public class DefaultPersistentComparator<K,V> : PersistentComparator<K,V> where V:class,IPersistent,IComparable<V>,IComparable<K>
{
public override int CompareMembers(V m1, V m2) {
return m1.CompareTo(m2);
}
public override int CompareMemberWithKey(V mbr, K key) {
return mbr.CompareTo(key);
}
}
}
| namespace NachoDB.Impl
{
using System;
using NachoDB;
#if USE_GENERICS
public class DefaultPersistentComparator<K,V> : PersistentComparator<K,V> where V:class,IPersistent,IComparable<V>,IComparable<K>
{
public override int CompareMembers(V m1, V m2) {
return m1.CompareTo(m2);
}
public override int CompareMemberWithKey(V mbr, K key) {
return mbr.CompareTo(key);
}
}
#else
public class DefaultPersistentComparator : PersistentComparator {
public override int CompareMembers(IPersistent m1, IPersistent m2) {
return ((IComparable)m1).CompareTo(m2);
}
public override int CompareMemberWithKey(IPersistent mbr, object key) {
return ((IComparable)mbr).CompareTo(key);
}
}
#endif
} | mit | C# |
d1b29bdbb0d95b17097cd886d442bbffe7cdab16 | Fix CouchbaseAsyncExample bug | couchbaselabs/couchbase-net-examples,couchbaselabs/couchbase-net-examples,couchbaselabs/couchbase-net-examples | Src/CouchbaseAsyncExample/Program.cs | Src/CouchbaseAsyncExample/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using Couchbase;
using Couchbase.Configuration.Client;
using Couchbase.Core;
namespace CouchbaseAsyncExample
{
class Program
{
public class Person
{
private static readonly string _type = "person";
public Person()
{
Type = _type;
}
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Type { get; private set; }
}
private static void Main(string[] args)
{
var count = 100000;
var config = new ClientConfiguration
{
Servers = new List<Uri>
{
//change this to your cluster to bootstrap
new Uri("http://localhost:8091/pools")
}
};
ClusterHelper.Initialize(config);
var bucket = ClusterHelper.GetBucket("default");
var items = new List<Person>();
for (int i = 0; i < count; i++)
{
items.Add(new Person {Age = 21, Name = "Some name" + i, Id = i.ToString()});
}
Task.Run(async () => await UpsertAllAsync(items, bucket)).ConfigureAwait(false);
Console.Read();
ClusterHelper.Close();
}
public static async Task UpsertAllAsync(List<Person> persons, IBucket bucket)
{
var tasks = new List<Task<IOperationResult<Person>>>();
persons.ForEach(x => tasks.Add(bucket.UpsertAsync(x.Id, x)));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
Console.WriteLine("Total upserted: {0}", results.Length);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using Couchbase;
using Couchbase.Configuration.Client;
using Couchbase.Core;
namespace CouchbaseAsyncExample
{
class Program
{
public class Person
{
private static readonly string _type = "person";
public Person()
{
Type = _type;
}
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Type { get; private set; }
}
private static void Main(string[] args)
{
var count = 100000;
var config = new ClientConfiguration
{
Servers = new List<Uri>
{
//change this to your cluster to bootstrap
new Uri("http://localhost/:8091/pools")
}
};
ClusterHelper.Initialize(config);
var bucket = ClusterHelper.GetBucket("default");
var items = new List<Person>();
for (int i = 0; i < count; i++)
{
items.Add(new Person {Age = 21, Name = "Some name" + i, Id = i.ToString()});
}
Task.Run(async () => await UpsertAllAsync(items, bucket)).ConfigureAwait(false);
Console.Read();
ClusterHelper.Close();
}
public static async Task UpsertAllAsync(List<Person> persons, IBucket bucket)
{
var tasks = new List<Task<OperationResult<Person>>>();
persons.ForEach(x => bucket.UpsertAsync(x.Id, x));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
Console.WriteLine("Total upserted: {0}", results.Length);
}
}
}
| apache-2.0 | C# |
c1766d8a411f1626255c1d74fbf0b634e7bc4610 | Add paused state | NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu | osu.Game/Online/Spectator/SpectatingUserState.cs | osu.Game/Online/Spectator/SpectatingUserState.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.Spectator
{
public enum SpectatingUserState
{
/// <summary>
/// The spectated user is not yet playing.
/// </summary>
Idle,
/// <summary>
/// The spectated user is currently playing.
/// </summary>
Playing,
/// <summary>
/// The spectated user is currently paused. Unused for the time being.
/// </summary>
Paused,
/// <summary>
/// The spectated user has passed gameplay.
/// </summary>
Passed,
/// <summary>
/// The spectator user has failed gameplay.
/// </summary>
Failed,
/// <summary>
/// The spectated user has quit gameplay.
/// </summary>
Quit
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.Spectator
{
public enum SpectatingUserState
{
/// <summary>
/// The spectated user is not yet playing.
/// </summary>
Idle,
/// <summary>
/// The spectated user is currently playing.
/// </summary>
Playing,
/// <summary>
/// The spectated user has passed gameplay.
/// </summary>
Passed,
/// <summary>
/// The spectator user has failed gameplay.
/// </summary>
Failed,
/// <summary>
/// The spectated user has quit gameplay.
/// </summary>
Quit
}
}
| mit | C# |
c3edf02b2f2c43cebc304cd29aea3a4ff42afb3f | Add a test to make sure the migrator adds columns | praeclarum/sqlite-net,ericsink/sqlite-net | tests/MigrationTest.cs | tests/MigrationTest.cs | using System.Linq;
using System.Text;
using SQLite;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
using System.IO;
namespace SQLite.Tests
{
[TestFixture]
public class MigrationTest
{
[Table ("Test")]
class LowerId {
public int Id { get; set; }
}
[Table ("Test")]
class UpperId {
public int ID { get; set; }
}
[Test]
public void UpperAndLowerColumnNames ()
{
using (var db = new TestDb (true) { Trace = true } ) {
db.CreateTable<LowerId> ();
db.CreateTable<UpperId> ();
var cols = db.GetTableInfo ("Test").ToList ();
Assert.AreEqual (1, cols.Count);
Assert.AreEqual ("Id", cols[0].Name);
}
}
[Table ("TestAdd")]
class TestAddBefore
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
[Table ("TestAdd")]
class TestAddAfter
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public int IntValue { get; set; }
public string StringValue { get; set; }
}
[Test]
public void AddColumns ()
{
//
// Init the DB
//
var path = "";
using (var db = new TestDb (true) { Trace = true }) {
path = db.DatabasePath;
db.CreateTable<TestAddBefore> ();
var cols = db.GetTableInfo ("TestAdd");
Assert.AreEqual (2, cols.Count);
var o = new TestAddBefore {
Name = "Foo",
};
db.Insert (o);
var oo = db.Table<TestAddBefore> ().First ();
Assert.AreEqual ("Foo", oo.Name);
}
//
// Migrate and use it
//
using (var db = new SQLiteConnection (path, true) { Trace = true }) {
db.CreateTable<TestAddAfter> ();
var cols = db.GetTableInfo ("TestAdd");
Assert.AreEqual (4, cols.Count);
var oo = db.Table<TestAddAfter> ().First ();
Assert.AreEqual ("Foo", oo.Name);
Assert.AreEqual (0, oo.IntValue);
Assert.AreEqual (null, oo.StringValue);
var o = new TestAddAfter {
Name = "Bar",
IntValue = 42,
StringValue = "Hello",
};
db.Insert (o);
var ooo = db.Get<TestAddAfter> (o.Id);
Assert.AreEqual ("Bar", ooo.Name);
Assert.AreEqual (42, ooo.IntValue);
Assert.AreEqual ("Hello", ooo.StringValue);
}
}
}
}
| using System.Linq;
using System.Text;
using SQLite;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
using System.IO;
namespace SQLite.Tests
{
[TestFixture]
public class MigrationTest
{
[Table ("Test")]
class LowerId {
public int Id { get; set; }
}
[Table ("Test")]
class UpperId {
public int ID { get; set; }
}
[Test]
public void UpperAndLowerColumnNames ()
{
using (var db = new TestDb (true) { Trace = true } ) {
db.CreateTable<LowerId> ();
db.CreateTable<UpperId> ();
var cols = db.GetTableInfo ("Test").ToList ();
Assert.AreEqual (1, cols.Count);
Assert.AreEqual ("Id", cols[0].Name);
}
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.