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 |
|---|---|---|---|---|---|---|---|---|
cb6b89a5f9b3e13d01c0ba0ba46032201b57ce28 | Handle FEZMod PreInitialize crashes. | AngelDE98/FEZMod,AngelDE98/FEZMod | FEZ.Mod.mm/FezGame/Program.cs | FEZ.Mod.mm/FezGame/Program.cs | using System;
using FezGame.Mod;
using FezGame.Mod;
namespace FezGame {
public class Program {
public static void orig_Main(string[] args) {
}
public static void Main(string[] args) {
try {
FEZMod.PreInitialize(args);
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZMod PreInitialize crash...");
ModLogger.Log("FEZMod", e.ToString());
FEZMod.HandleCrash(e);
}
ModLogger.Log("FEZMod", "Passing to FEZ...");
orig_Main(args);
}
private static void orig_MainInternal() {
}
private static void MainInternal() {
try {
orig_MainInternal();
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling FEZ crash...");
ModLogger.Log("FEZMod", e.ToString());
FEZMod.HandleCrash(e);
}
}
}
}
| using System;
using FezGame.Mod;
using FezGame.Mod;
namespace FezGame {
public class Program {
public static void orig_Main(string[] args) {
}
public static void Main(string[] args) {
FEZMod.PreInitialize(args);
ModLogger.Log("FEZMod", "Passing to FEZ...");
orig_Main(args);
}
private static void orig_MainInternal() {
}
private static void MainInternal() {
try {
orig_MainInternal();
} catch (Exception e) {
ModLogger.Log("FEZMod", "Handling crash...");
ModLogger.Log("FEZMod", e.ToString());
FEZMod.HandleCrash(e);
}
}
}
}
| mit | C# |
22b9d1ad1e8abb1b9eb55975c865f3c3ecb5327b | Fix path output for inputs | jefflinse/MSBuildTracer | MSBuildTracer/ImportTracer.cs | MSBuildTracer/ImportTracer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MBEV = Microsoft.Build.Evaluation;
using MBEX = Microsoft.Build.Execution;
namespace MSBuildTracer
{
class ImportTracer
{
private MBEV.Project project;
public ImportTracer(MBEV.Project project)
{
this.project = project;
}
public void Trace(MBEV.ResolvedImport import, int traceLevel = 0)
{
PrintImportInfo(import, traceLevel);
foreach (var childImport in project.Imports.Where(
i => string.Equals(i.ImportingElement.ContainingProject.FullPath,
project.ResolveAllProperties(import.ImportingElement.Project),
StringComparison.OrdinalIgnoreCase)))
{
Trace(childImport, traceLevel + 1);
}
}
private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount)
{
var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : "";
Console.WriteLine($"{indent}{import.ImportingElement.Location.Line}: {project.ResolveAllProperties(import.ImportedProject.Location.File)}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MBEV = Microsoft.Build.Evaluation;
using MBEX = Microsoft.Build.Execution;
namespace MSBuildTracer
{
class ImportTracer
{
private MBEV.Project project;
public ImportTracer(MBEV.Project project)
{
this.project = project;
}
public void Trace(MBEV.ResolvedImport import, int traceLevel = 0)
{
PrintImportInfo(import, traceLevel);
foreach (var childImport in project.Imports.Where(
i => string.Equals(i.ImportingElement.ContainingProject.FullPath,
project.ResolveAllProperties(import.ImportingElement.Project),
StringComparison.OrdinalIgnoreCase)))
{
Trace(childImport, traceLevel + 1);
}
}
private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount)
{
var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : "";
Console.WriteLine($"{indent}{import.ImportingElement.Location.Line}: {project.ResolveAllProperties(import.ImportingElement.Project)}");
}
}
}
| mit | C# |
5323e9c91e58b657d91605574a08a1019d766743 | Update EnumerableTests.cs | keith-hall/Extensions,keith-hall/Extensions | tests/EnumerableTests.cs | tests/EnumerableTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HallLibrary.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class EnumerableTests
{
[TestMethod]
public void TestCountExceeds()
{
var src = Enumerable.Range(1, 4).Concat(new[] { 0 }).Select(s => 1 / s);
// ReSharper disable once PossibleMultipleEnumeration
Assert.IsTrue(src.CountExceeds(3));
// just doing a Count would give a DivideByZero exception - this could also be demonstrated with the [ExpectedException(typeof(DivideByZeroException))] attribute on this method, but we want to test multiple conditions in a single method
try
{
// ReSharper disable once PossibleMultipleEnumeration
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (src.Count() > 3)
Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached.");
else
Assert.Fail("Count is greater than 3 so this line should never be reached.");
}
catch (DivideByZeroException)
{
}
catch (Exception)
{
Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached.");
}
src = Enumerable.Range(1, 2);
Assert.IsFalse(src.CountExceeds(2));
}
[TestMethod]
public void TestCountEquals()
{
var src = Enumerable.Range(1, 3).Concat(Enumerable.Range(0, 1).Select(s => 1 / s));
Assert.IsFalse(src.Distinct().CountEquals(2));
var src = Enumerable.Range(1, 3);
Assert.IsTrue(src.CountEquals(3));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HallLibrary.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class EnumerableTests
{
[TestMethod]
public void TestCountExceeds()
{
var src = Enumerable.Range(1, 4).Concat(new[] { 0 }).Select(s => 1 / s);
// ReSharper disable once PossibleMultipleEnumeration
Assert.AreEqual(src.CountExceeds(3), true);
// just doing a Count would give a DivideByZero exception - this could also be demonstrated with the [ExpectedException(typeof(DivideByZeroException))] attribute on this method, but we want to test multiple conditions in a single method
try
{
// ReSharper disable once PossibleMultipleEnumeration
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (src.Count() > 3)
Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached.");
else
Assert.Fail("Count is greater than 3 so this line should never be reached.");
}
catch (DivideByZeroException)
{
}
catch (Exception)
{
Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached.");
}
src = Enumerable.Range(1, 2);
Assert.IsFalse(src.CountExceeds(2));
}
}
}
| apache-2.0 | C# |
38e5d3a23f12a38315f53a77ae5182c821a69268 | make paging option defaults settable | Kukkimonsuta/Odachi | src/Odachi.Extensions.Collections/PagingOptions.cs | src/Odachi.Extensions.Collections/PagingOptions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Odachi.Extensions.Collections;
namespace Odachi.Extensions.Collections
{
/// <summary>
/// Holds information about requested paging.
/// </summary>
public class PagingOptions
{
public static int DefaultPageSize = 10;
public static bool DefaultAcquireTotal = true;
public static int DefaultOffset = 0;
public static int DefaultMaximumCount = 20;
public PagingOptions()
: this(0)
{
}
public PagingOptions(int number)
: this(number, DefaultPageSize, DefaultAcquireTotal, DefaultOffset, DefaultMaximumCount)
{
}
public PagingOptions(int number, int size)
: this(number, size, acquireTotal: DefaultAcquireTotal, offset: DefaultOffset, DefaultMaximumCount)
{
}
public PagingOptions(int number, int size, bool acquireTotal)
: this(number, size, acquireTotal: acquireTotal, offset: DefaultOffset, DefaultMaximumCount)
{
}
public PagingOptions(int number, int size, bool acquireTotal, int offset)
: this(number, size, acquireTotal: acquireTotal, offset: offset, DefaultMaximumCount)
{
}
public PagingOptions(int number, int size, bool acquireTotal, int offset, int? maximumCount)
{
Number = number;
Size = size;
AcquireTotal = acquireTotal;
Offset = offset;
MaximumCount = maximumCount;
}
private int _page;
private int _pageSize;
private int _offset;
private int? _maximumCount;
/// <summary>
/// Zero indexed number of requested page.
/// </summary>
public int Number
{
get { return _page; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Number must be more or equal to zero");
_page = value;
}
}
/// <summary>
/// Maximum size of page.
/// </summary>
public int Size
{
get { return _pageSize; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), "Size must be more than zero");
_pageSize = value;
}
}
/// <summary>
/// Acquire total number of items.
/// </summary>
public bool AcquireTotal { get; set; }
/// <summary>
/// Pretend there is number of items at the start of source collection.
/// </summary>
public int Offset
{
get { return _offset; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Offset must be greater than or equal to zero");
_offset = value;
}
}
/// <summary>
/// Maximum expected number of pages.
/// </summary>
public int? MaximumCount
{
get { return _maximumCount; }
set
{
if (value != null && value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), "MaximumCount must be greater than zero or null");
_maximumCount = value;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Odachi.Extensions.Collections;
namespace Odachi.Extensions.Collections
{
/// <summary>
/// Holds information about requested paging.
/// </summary>
public class PagingOptions
{
public const int DefaultPageSize = 10;
public const int DefaultMaximumCount = 20;
public PagingOptions()
: this(0)
{
}
public PagingOptions(int number, int size = DefaultPageSize, bool acquireTotal = true, int offset = 0, int? maximumCount = DefaultMaximumCount)
{
Number = number;
Size = size;
AcquireTotal = acquireTotal;
Offset = offset;
MaximumCount = maximumCount;
}
private int _page;
private int _pageSize;
private int _offset;
private int? _maximumCount;
/// <summary>
/// Zero indexed number of requested page.
/// </summary>
public int Number
{
get { return _page; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Page must be more or equal to zero");
_page = value;
}
}
/// <summary>
/// Maximum size of page.
/// </summary>
public int Size
{
get { return _pageSize; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), "PageSize must be more than zero");
_pageSize = value;
}
}
/// <summary>
/// Acquire total number of items.
/// </summary>
public bool AcquireTotal { get; set; }
/// <summary>
/// Pretend there is number of items at the start of source collection.
/// </summary>
public int Offset
{
get { return _offset; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Offset must be greater than or equal to zero");
_offset = value;
}
}
/// <summary>
/// Maximum expected number of pages.
/// </summary>
public int? MaximumCount
{
get { return _maximumCount; }
set
{
if (value != null && value <= 0)
throw new ArgumentOutOfRangeException("value", "MaxPageCount must be greater than zero or null");
_maximumCount = value;
}
}
}
}
| apache-2.0 | C# |
65a846de6946ff968c44af63d1ef3b18da897458 | Remove geometry us in RasterizingLayerSample | charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui | Samples/Mapsui.Samples.Common/Maps/Special/RasterizingLayerSample.cs | Samples/Mapsui.Samples.Common/Maps/Special/RasterizingLayerSample.cs | using System;
using System.Collections.Generic;
using Mapsui.Layers;
using Mapsui.Layers.Tiling;
using Mapsui.Providers;
using Mapsui.Styles;
using Mapsui.UI;
namespace Mapsui.Samples.Common.Maps
{
public class RasterizingLayerSample : ISample
{
public string Name => "Rasterizing Layer";
public string Category => "Special";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap(mapControl.PixelDensity);
}
public static Map CreateMap(float pixelDensity)
{
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer(), pixelDensity: pixelDensity));
map.Home = n => n.NavigateTo(map.Layers[1].Extent.Grow(map.Layers[1].Extent.Width * 0.1));
return map;
}
private static MemoryLayer CreateRandomPointLayer()
{
var rnd = new Random(3462); // Fix the random seed so the features don't move after a refresh
var features = new List<IFeature>();
for (var i = 0; i < 100; i++)
{
features.Add(new PointFeature(new MPoint(rnd.Next(0, 5000000), rnd.Next(0, 5000000))));
}
var provider = new MemoryProvider<IFeature>(features);
return new MemoryLayer
{
DataSource = provider,
Style = new SymbolStyle
{
SymbolType = SymbolType.Triangle,
Fill = new Brush(Color.Red)
}
};
}
}
} | using System;
using System.Collections.Generic;
using Mapsui.Layers;
using Mapsui.Layers.Tiling;
using Mapsui.Providers;
using Mapsui.Styles;
using Mapsui.UI;
namespace Mapsui.Samples.Common.Maps
{
public class RasterizingLayerSample : ISample
{
public string Name => "Rasterizing Layer";
public string Category => "Special";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap(mapControl.PixelDensity);
}
public static Map CreateMap(float pixelDensity)
{
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer(), pixelDensity: pixelDensity));
map.Home = n => n.NavigateTo(map.Layers[1].Extent.Grow(map.Layers[1].Extent.Width * 0.1));
return map;
}
private static MemoryLayer CreateRandomPointLayer()
{
var rnd = new Random(3462); // Fix the random seed so the features don't move after a refresh
var features = new List<IGeometryFeature>();
for (var i = 0; i < 100; i++)
{
var feature = new GeometryFeature
{
Geometry = new Geometries.Point(rnd.Next(0, 5000000), rnd.Next(0, 5000000))
};
features.Add(feature);
}
var provider = new MemoryProvider<IFeature>(features);
return new MemoryLayer
{
DataSource = provider,
Style = new SymbolStyle
{
SymbolType = SymbolType.Triangle,
Fill = new Brush(Color.Red)
}
};
}
}
} | mit | C# |
a8ace172ae67508fe7c20cc585496683b0c87f6d | improve the test method. | jwChung/Experimentalism,jwChung/Experimentalism | test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs | test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs | using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Jwc.Experiment;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(AutoDataTheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
[Theory]
[InlineData("AutoDataTheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesNugetTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
VerifyGenerateFile(origin, destination);
}
[Conditional("CI")]
private static void VerifyGenerateFile(string origin, string destination)
{
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
} | using System.IO;
using System.Linq;
using System.Text;
using Jwc.Experiment;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(AutoDataTheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
#if CI
[Theory]
#else
[Theory(Skip = "Run on CI server")]
#endif
[InlineData("AutoDataTheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
} | mit | C# |
fe4aed3dbe60c2aa63aaae50c11e4189132c438f | Allow using [Preserve] attributes at the assembly level | mono/maccore,cwensley/maccore | src/Foundation/PreserveAttribute.cs | src/Foundation/PreserveAttribute.cs | //
// PreserveAttribute.cs
//
// Authors:
// Jb Evain
//
// Copyright 2009-2010, Novell, Inc.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
namespace MonoMac.Foundation {
[AttributeUsage (
AttributeTargets.Assembly
| AttributeTargets.Class
| AttributeTargets.Struct
| AttributeTargets.Enum
| AttributeTargets.Constructor
| AttributeTargets.Method
| AttributeTargets.Property
| AttributeTargets.Field
| AttributeTargets.Event
| AttributeTargets.Interface
| AttributeTargets.Delegate)]
public sealed class PreserveAttribute : Attribute {
public bool AllMembers;
public bool Conditional;
public PreserveAttribute ()
{
}
}
}
| //
// PreserveAttribute.cs
//
// Authors:
// Jb Evain
//
// Copyright 2009, Novell, Inc.
// Copyright 2010, Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
namespace MonoMac.Foundation {
[AttributeUsage (
AttributeTargets.Class
| AttributeTargets.Struct
| AttributeTargets.Enum
| AttributeTargets.Constructor
| AttributeTargets.Method
| AttributeTargets.Property
| AttributeTargets.Field
| AttributeTargets.Event
| AttributeTargets.Interface
| AttributeTargets.Delegate)]
public sealed class PreserveAttribute : Attribute {
public bool AllMembers;
public bool Conditional;
public PreserveAttribute ()
{
}
}
}
| apache-2.0 | C# |
fb5e5a0736cc2631957427e9be588a935965c675 | Fix compilation error introduced with my previous fix | cwensley/maccore,beni55/maccore,mono/maccore,jorik041/maccore | src/Foundation/NSUrlConnection.cs | src/Foundation/NSUrlConnection.cs | //
// NSUrlConnection.cs:
// Author:
// Miguel de Icaza
//
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlConnection {
static Selector selSendSynchronousRequestReturningResponseError = new Selector ("sendSynchronousRequest:returningResponse:error:");
public unsafe static NSData SendSynchronousRequest (NSUrlRequest request, out NSUrlResponse response, out NSError error)
{
IntPtr responseStorage = IntPtr.Zero;
IntPtr errorStorage = IntPtr.Zero;
void *resp = &responseStorage;
void *errp = &errorStorage;
IntPtr rhandle = (IntPtr) resp;
IntPtr ehandle = (IntPtr) errp;
var res = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr (
class_ptr,
selSendSynchronousRequestReturningResponseError.Handle,
request.Handle,
rhandle,
ehandle);
if (responseStorage != IntPtr.Zero)
response = (NSUrlResponse) Runtime.GetNSObject (responseStorage);
else
response = null;
if (errorStorage != IntPtr.Zero)
error = (NSError) Runtime.GetNSObject (errorStorage);
else
error = null;
return (NSData) Runtime.GetNSObject (res);
}
}
}
| //
// NSUrlConnection.cs:
// Author:
// Miguel de Icaza
//
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlConnection {
static Selector selSendSynchronousRequestReturningResponseError = new Selector ("sendSynchronousRequest:returningResponse:error:");
unsafe static NSData SendSynchronousRequest (NSUrlRequest request, out NSUrlResponse response, out NSError error)
{
IntPtr responseStorage = IntPtr.Zero;
IntPtr errorStorage = IntPtr.Zero;
void *resp = &responseStorage;
void *errp = &errorStorage;
IntPtr rhandle = (IntPtr) resp;
IntPtr ehandle = (IntPtr) errp;
var res = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr (
class_ptr,
selSendSynchronousRequestReturningResponseError.Handle,
request.Handle,
rhandle,
ehandle);
if (responseStorage != IntPtr.Zero)
response = (NSUrlResponse) Runtime.GetNSObject (responseStorage);
else
response = null;
if (errorStorage != IntPtr.Zero)
error = (NSUrlResponse) Runtime.GetNSObject (errorStorage);
else
error = null;
return (NSData) Runtime.GetNSObject (res);
}
}
}
| apache-2.0 | C# |
49af8064160f9758b927b867d8a9852827ba507e | Update CanvasRenderTarget.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D.Screenshot/CanvasRenderTarget.cs | src/Core2D.Screenshot/CanvasRenderTarget.cs | using Avalonia;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Skia.Helpers;
using SkiaSharp;
namespace Core2D.Screenshot;
public class CanvasRenderTarget : IRenderTarget
{
private readonly SKCanvas _canvas;
private readonly double _dpi;
public CanvasRenderTarget(SKCanvas canvas, double dpi)
{
_canvas = canvas;
_dpi = dpi;
}
public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer? visualBrushRenderer)
{
return DrawingContextHelper.WrapSkiaCanvas(_canvas, new Vector(_dpi, _dpi), visualBrushRenderer);
}
public void Dispose()
{
}
}
| using Avalonia;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Skia.Helpers;
using SkiaSharp;
namespace Core2D.Screenshot;
public class CanvasRenderTarget : IRenderTarget
{
private readonly SKCanvas _canvas;
private readonly double _dpi;
public CanvasRenderTarget(SKCanvas canvas, double dpi)
{
_canvas = canvas;
_dpi = dpi;
}
public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer visualBrushRenderer)
{
return DrawingContextHelper.WrapSkiaCanvas(_canvas, new Vector(_dpi, _dpi), visualBrushRenderer);
}
public void Dispose()
{
}
}
| mit | C# |
b43ee2d61c20a20c9ff464b2a2a15c9ff0e23579 | Add descriptions to enum members | peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game/Beatmaps/CountdownType.cs | osu.Game/Beatmaps/CountdownType.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.ComponentModel;
namespace osu.Game.Beatmaps
{
/// <summary>
/// The type of countdown shown before the start of gameplay on a given beatmap.
/// </summary>
public enum CountdownType
{
None = 0,
[Description("Normal")]
Normal = 1,
[Description("Half speed")]
HalfSpeed = 2,
[Description("Double speed")]
DoubleSpeed = 3
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Beatmaps
{
/// <summary>
/// The type of countdown shown before the start of gameplay on a given beatmap.
/// </summary>
public enum CountdownType
{
None = 0,
Normal = 1,
HalfSpeed = 2,
DoubleSpeed = 3
}
}
| mit | C# |
bc881dd2e253706222c6444c33eecb426dd514ec | Update BinarySearch.cs | natalya-k/algorithms | search/BinarySearch.cs | search/BinarySearch.cs | namespace Algorithms
{
static class BinarySearch
{
public static int? Search(int[] array, int target)
{
int begin = 0;
int end = array.Length - 1;
int guess;
while (end >= begin)
{
//guess = (begin + end) / 2;
//этот вариант предотвращает переполнение стека при больших значениях begin и end
guess = begin + (end - begin) / 2;
if (array[guess] == target)
{
return guess;
}
if (array[guess] > target)
{
end = guess - 1;
}
else
{
begin = guess + 1;
}
}
return null;
}
}
}
| namespace Algorithms
{
class BinarySearch
{
public static int? Search(int[] array, int target)
{
int begin = 0;
int end = array.Length - 1;
int guess;
while (end >= begin)
{
//guess = (begin + end) / 2;
//этот вариант предотвращает переполнение стека при больших значениях begin и end
guess = begin + (end - begin) / 2;
if (array[guess] == target)
{
return guess;
}
else if (array[guess] > target)
{
end = guess - 1;
}
else
{
begin = guess + 1;
}
}
return null;
}
}
}
| mit | C# |
b3c65a0eafd4ca78d32bad735a14d7bf9bca48a4 | Return string response, not XML | Mozketo/TFSbot | Changesets/run.csx | Changesets/run.csx | #load "..\extensions\TfsEx.csx"
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
DateTime dFrom = DateTime.Now.Subtract(TimeSpan.FromDays(1));
string from = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "from", true) == 0)
.Value;
string notReviewed = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "not-reviewed", true) == 0)
.Value;
DateTime tryDate;
int tryDays = 0;
if (DateTime.TryParse(from, out tryDate))
{
dFrom = tryDate;
}
else if (int.TryParse(from, out tryDays))
{
dFrom = dFrom.Subtract(TimeSpan.FromDays(Math.Abs(tryDays)));
}
string tfsPath = ConfigurationManager.AppSettings["Tfs.Path"] ?? "$/";
var tickets = TfsEx.GetHistory(log, tfsPath, dFrom);
if (!string.IsNullOrWhiteSpace(notReviewed))
{
tickets = TfsEx.NotReviewed(log, tickets); // Filter for not reviewed items
}
string message = tickets.Count().ToString();
return Message(req, message);
}
static HttpResponseMessage Message(HttpRequestMessage req, string message)
{
var response = req.CreateResponse();
response.Content = new StringContent(message);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
//return req.CreateResponse(HttpStatusCode.OK, message);
} | #load "..\extensions\TfsEx.csx"
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
DateTime dFrom = DateTime.Now.Subtract(TimeSpan.FromDays(1));
string from = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "from", true) == 0)
.Value;
string notReviewed = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "not-reviewed", true) == 0)
.Value;
DateTime tryDate;
int tryDays = 0;
if (DateTime.TryParse(from, out tryDate))
{
dFrom = tryDate;
}
else if (int.TryParse(from, out tryDays))
{
dFrom = dFrom.Subtract(TimeSpan.FromDays(Math.Abs(tryDays)));
}
string tfsPath = ConfigurationManager.AppSettings["Tfs.Path"] ?? "$/";
var tickets = TfsEx.GetHistory(log, tfsPath, dFrom);
if (!string.IsNullOrWhiteSpace(notReviewed))
{
tickets = TfsEx.NotReviewed(log, tickets); // Filter for not reviewed items
}
string message = tickets.Count().ToString();
return Message(req, message);
}
static HttpResponseMessage Message(HttpRequestMessage req, string message)
{
return req.CreateResponse(HttpStatusCode.OK, message);
} | mit | C# |
1195c22a82f77abca5c35e6ca78c2225529454cd | Update to MouseInputState | bostelk/delta | Delta.Core/Input/States/MouseInputState.cs | Delta.Core/Input/States/MouseInputState.cs | using System;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
namespace Delta.Input.States
{
#if WINDOWS
public sealed class MouseInputState
{
public MouseState MouseState { get; private set; }
public Vector2 Position { get; private set; }
public Vector2 PositionDelta { get; private set; }
public Button LeftButton { get; private set; }
public Button RightButton { get; private set; }
public Button MiddleButton { get; private set; }
public Button XButton1 { get; private set; }
public Button XButton2 { get; private set; }
public int ScrollWheelValue { get; private set; }
public int ScrollWheelDelta { get; private set; }
internal void Update(DeltaTime time, ref MouseState mouseState)
{
MouseState = mouseState;
Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);
PositionDelta = mousePosition - Position;
Position = mousePosition;
ScrollWheelDelta = mouseState.ScrollWheelValue - ScrollWheelValue;
ScrollWheelValue = mouseState.ScrollWheelValue;
LeftButton.SetState(mouseState.LeftButton == ButtonState.Pressed, time);
RightButton.SetState(mouseState.RightButton == ButtonState.Pressed, time);
MiddleButton.SetState(mouseState.MiddleButton== ButtonState.Pressed, time);
XButton1.SetState(mouseState.XButton1 == ButtonState.Pressed, time);
XButton2.SetState(mouseState.XButton2 == ButtonState.Pressed, time);
}
}
#endif
}
| using System;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
namespace Delta.Input.States
{
#if WINDOWS
public sealed class MouseInputState
{
MouseState state;
Button _left;
Button _right;
Button _middle;
Button _x1;
Button _x2;
int _x;
int _y;
int _xDelta;
int _yDelta;
int _scroll;
int _scrollDelta;
public int X { get { return _x; } }
public int Y { get { return _y; } }
public int XDelta { get { return _xDelta; } }
public int YDelta { get { return _yDelta; } }
public Button LeftButton { get { return _left; } }
public Button RightButton { get { return _right; } }
public Button MiddleButton { get { return _middle; } }
public Button XButton1 { get { return _x2; } }
public Button XButton2 { get { return _x1; } }
public int ScrollWheelValue { get { return _scroll; } }
public int ScrollWheelDelta { get { return _scrollDelta; } }
public Vector2 Position { get { return new Vector2(X, Y); } }
internal void Update(DeltaTime time, ref MouseState mouseState)
{
state = mouseState;
_xDelta = state.X - _x;
_yDelta = state.Y - _y;
_x = state.X;
_y = state.Y;
_scrollDelta = state.ScrollWheelValue - _scroll;
_scroll = state.ScrollWheelValue;
_left.SetState(state.LeftButton == ButtonState.Pressed, time);
_right.SetState(state.RightButton == ButtonState.Pressed, time);
_middle.SetState(state.MiddleButton== ButtonState.Pressed, time);
_x1.SetState(state.XButton1 == ButtonState.Pressed, time);
_x2.SetState(state.XButton2 == ButtonState.Pressed, time);
}
public static implicit operator MouseState(MouseInputState input)
{
return input.state;
}
}
#endif
}
| mit | C# |
752e675559c93148b7c03c3aa7c7f4ecd2b682a9 | Add docs | mgoertz-msft/roslyn,bartdesmet/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,dotnet/roslyn,physhi/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,tmat/roslyn,mavasani/roslyn,tmat/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,mavasani/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,physhi/roslyn,AmadeusW/roslyn,eriawan/roslyn,physhi/roslyn,weltkante/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,bartdesmet/roslyn,wvdd007/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,tmat/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,tannergooding/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,wvdd007/roslyn,tannergooding/roslyn,KevinRansom/roslyn | src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs | src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Forwarders.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal sealed partial class SyntaxTreeIndex
{
public ImmutableArray<DeclaredSymbolInfo> DeclaredSymbolInfos => _declarationInfo.DeclaredSymbolInfos;
public ImmutableDictionary<string, ImmutableArray<int>> ReceiverTypeNameToExtensionMethodMap
=> _extensionMethodInfo.ReceiverTypeNameToExtensionMethodMap;
public bool ContainsExtensionMethod => _extensionMethodInfo.ContainsExtensionMethod;
public bool ProbablyContainsIdentifier(string identifier) => _identifierInfo.ProbablyContainsIdentifier(identifier);
public bool ProbablyContainsEscapedIdentifier(string identifier) => _identifierInfo.ProbablyContainsEscapedIdentifier(identifier);
public bool ContainsPredefinedType(PredefinedType type) => _contextInfo.ContainsPredefinedType(type);
public bool ContainsPredefinedOperator(PredefinedOperator op) => _contextInfo.ContainsPredefinedOperator(op);
public bool ProbablyContainsStringValue(string value) => _literalInfo.ProbablyContainsStringValue(value);
public bool ProbablyContainsInt64Value(long value) => _literalInfo.ProbablyContainsInt64Value(value);
public bool ContainsForEachStatement => _contextInfo.ContainsForEachStatement;
public bool ContainsDeconstruction => _contextInfo.ContainsDeconstruction;
public bool ContainsAwait => _contextInfo.ContainsAwait;
public bool ContainsImplicitObjectCreation => _contextInfo.ContainsImplicitObjectCreation;
public bool ContainsLockStatement => _contextInfo.ContainsLockStatement;
public bool ContainsUsingStatement => _contextInfo.ContainsUsingStatement;
public bool ContainsQueryExpression => _contextInfo.ContainsQueryExpression;
public bool ContainsThisConstructorInitializer => _contextInfo.ContainsThisConstructorInitializer;
public bool ContainsBaseConstructorInitializer => _contextInfo.ContainsBaseConstructorInitializer;
public bool ContainsElementAccessExpression => _contextInfo.ContainsElementAccessExpression;
public bool ContainsIndexerMemberCref => _contextInfo.ContainsIndexerMemberCref;
public bool ContainsTupleExpressionOrTupleType => _contextInfo.ContainsTupleExpressionOrTupleType;
public bool ContainsGlobalAttributes => _contextInfo.ContainsGlobalAttributes;
private HashSet<DeclaredSymbolInfo> _declaredSymbolInfoSet;
/// <summary>
/// Same as <see cref="DeclaredSymbolInfos"/>, just stored as a set for easy containment checks.
/// </summary>
public HashSet<DeclaredSymbolInfo> DeclaredSymbolInfoSet => _declaredSymbolInfoSet ??= new HashSet<DeclaredSymbolInfo>(DeclaredSymbolInfos);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal sealed partial class SyntaxTreeIndex
{
public ImmutableArray<DeclaredSymbolInfo> DeclaredSymbolInfos => _declarationInfo.DeclaredSymbolInfos;
public ImmutableDictionary<string, ImmutableArray<int>> ReceiverTypeNameToExtensionMethodMap
=> _extensionMethodInfo.ReceiverTypeNameToExtensionMethodMap;
public bool ContainsExtensionMethod => _extensionMethodInfo.ContainsExtensionMethod;
public bool ProbablyContainsIdentifier(string identifier) => _identifierInfo.ProbablyContainsIdentifier(identifier);
public bool ProbablyContainsEscapedIdentifier(string identifier) => _identifierInfo.ProbablyContainsEscapedIdentifier(identifier);
public bool ContainsPredefinedType(PredefinedType type) => _contextInfo.ContainsPredefinedType(type);
public bool ContainsPredefinedOperator(PredefinedOperator op) => _contextInfo.ContainsPredefinedOperator(op);
public bool ProbablyContainsStringValue(string value) => _literalInfo.ProbablyContainsStringValue(value);
public bool ProbablyContainsInt64Value(long value) => _literalInfo.ProbablyContainsInt64Value(value);
public bool ContainsForEachStatement => _contextInfo.ContainsForEachStatement;
public bool ContainsDeconstruction => _contextInfo.ContainsDeconstruction;
public bool ContainsAwait => _contextInfo.ContainsAwait;
public bool ContainsImplicitObjectCreation => _contextInfo.ContainsImplicitObjectCreation;
public bool ContainsLockStatement => _contextInfo.ContainsLockStatement;
public bool ContainsUsingStatement => _contextInfo.ContainsUsingStatement;
public bool ContainsQueryExpression => _contextInfo.ContainsQueryExpression;
public bool ContainsThisConstructorInitializer => _contextInfo.ContainsThisConstructorInitializer;
public bool ContainsBaseConstructorInitializer => _contextInfo.ContainsBaseConstructorInitializer;
public bool ContainsElementAccessExpression => _contextInfo.ContainsElementAccessExpression;
public bool ContainsIndexerMemberCref => _contextInfo.ContainsIndexerMemberCref;
public bool ContainsTupleExpressionOrTupleType => _contextInfo.ContainsTupleExpressionOrTupleType;
public bool ContainsGlobalAttributes => _contextInfo.ContainsGlobalAttributes;
private HashSet<DeclaredSymbolInfo> _declaredSymbolInfoSet;
public HashSet<DeclaredSymbolInfo> DeclaredSymbolInfoSet => _declaredSymbolInfoSet ??= new HashSet<DeclaredSymbolInfo>(DeclaredSymbolInfos);
}
}
| mit | C# |
f9bdb664ee7b8fd1c2a041f6d91b92fedca32d3b | Update diffcalc test | peppy/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu | osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.cs | osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
| // 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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3683365342338796d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
| mit | C# |
fe364dcf235b5a393903f2dfe0b7b95f437b7adf | Add comment about ParentPid check. | zacbrown/hiddentreasure-etw-demo | hiddentreasure-etw-demo/RemoteThreadInjection.cs | hiddentreasure-etw-demo/RemoteThreadInjection.cs | using System;
using O365.Security.ETW;
namespace hiddentreasure_etw_demo
{
public static class RemoteThreadInjection
{
public static UserTrace CreateTrace()
{
var filter = new EventFilter(Filter
.EventIdIs(3));
filter.OnEvent += (IEventRecord r) => {
var sourcePID = r.ProcessId;
var targetPID = r.GetUInt32("ProcessID");
if (sourcePID != targetPID)
{
// This is where you'd check that the target process's
// parent PID isn't the source PID. I've left it off for
// brevity since .NET doesn't provide an easy way to get
// parent PID :(.
var createdTID = r.GetUInt32("ThreadID");
var fmt = "Possible thread injection! - SourcePID: {0}, TargetPID: {1}, CreatedTID: {2}";
Console.WriteLine(fmt, sourcePID, targetPID, createdTID);
}
};
var provider = new Provider("Microsoft-Windows-Kernel-Process");
provider.AddFilter(filter);
var trace = new UserTrace();
trace.Enable(provider);
return trace;
}
}
}
| using System;
using O365.Security.ETW;
namespace hiddentreasure_etw_demo
{
public static class RemoteThreadInjection
{
public static UserTrace CreateTrace()
{
var filter = new EventFilter(Filter
.EventIdIs(3));
filter.OnEvent += (IEventRecord r) => {
var sourcePID = r.ProcessId;
var targetPID = r.GetUInt32("ProcessID");
if (sourcePID != targetPID)
{
var createdTID = r.GetUInt32("ThreadID");
var fmt = "Possible thread injection! - SourcePID: {0}, TargetPID: {1}, CreatedTID: {2}";
Console.WriteLine(fmt, sourcePID, targetPID, createdTID);
}
};
var provider = new Provider("Microsoft-Windows-Kernel-Process");
provider.AddFilter(filter);
var trace = new UserTrace();
trace.Enable(provider);
return trace;
}
}
}
| mit | C# |
7515d4942aeccd77f8bd62297fec711e8db65d1d | fix using | Fody/Resourcer | Resourcer.Fody/ResourceFinder.cs | Resourcer.Fody/ResourceFinder.cs | using System.IO;
using System.Linq;
using Fody;
using Mono.Cecil;
using Mono.Cecil.Cil;
public partial class ModuleWeaver
{
public Resource FindResource(string searchPath, string @namespace, string codeDirPath, Instruction instruction, MethodDefinition method)
{
var resources = ModuleDefinition.Resources;
//Fully qualified
var resource = resources.FirstOrDefault(x => x.Name == searchPath);
if (resource != null)
{
return resource;
}
//Relative based on namespace
var namespaceCombine = Path.Combine(@namespace.Replace("/", ".").Replace(@"\", "."), searchPath);
var resourceNameFromNamespace = namespaceCombine.Replace("/", ".").Replace(@"\", ".");
resource = resources.FirstOrDefault(x => x.Name == resourceNameFromNamespace);
if (resource != null)
{
return resource;
}
if (codeDirPath == null)
{
throw new WeavingException($"Could not find a relative path for `{method.FullName}`. Note that Resourcer requires debugs symbols to be enabled to derive paths.");
}
//Relative based on dir
var combine = Path.Combine(codeDirPath, searchPath);
var dirCombine = Path.GetFullPath(combine)
.Replace(Directory.GetCurrentDirectory(),"");
var suffix = dirCombine
.TrimStart(Path.DirectorySeparatorChar)
.Replace(Path.DirectorySeparatorChar, '.');
var resourceNameFromDir = $"{Path.GetFileNameWithoutExtension(ModuleDefinition.Name)}.{suffix}";
resource = resources.FirstOrDefault(x => x.Name == resourceNameFromDir);
if (resource != null)
{
return resource;
}
var message = $@"Could not find a resource.
CodeDirPath:'{codeDirPath}'
Tried:
searchPath:'{searchPath}'
resourceNameFromNamespace:'{resourceNameFromNamespace}'
resourceNameFromDir:'{resourceNameFromDir}'
";
LogErrorPoint(message, instruction.GetPreviousSequencePoint(method));
return null;
}
} | using System;
using System.IO;
using System.Linq;
using Fody;
using Mono.Cecil;
using Mono.Cecil.Cil;
public partial class ModuleWeaver
{
public Resource FindResource(string searchPath, string @namespace, string codeDirPath, Instruction instruction, MethodDefinition method)
{
var resources = ModuleDefinition.Resources;
//Fully qualified
var resource = resources.FirstOrDefault(x => x.Name == searchPath);
if (resource != null)
{
return resource;
}
//Relative based on namespace
var namespaceCombine = Path.Combine(@namespace.Replace("/", ".").Replace(@"\", "."), searchPath);
var resourceNameFromNamespace = namespaceCombine.Replace("/", ".").Replace(@"\", ".");
resource = resources.FirstOrDefault(x => x.Name == resourceNameFromNamespace);
if (resource != null)
{
return resource;
}
if (codeDirPath == null)
{
throw new WeavingException($"Could not find a relative path for `{method.FullName}`. Note that Resourcer requires debugs symbols to be enabled to derive paths.");
}
//Relative based on dir
var combine = Path.Combine(codeDirPath, searchPath);
var dirCombine = Path.GetFullPath(combine)
.Replace(Directory.GetCurrentDirectory(),"");
var suffix = dirCombine
.TrimStart(Path.DirectorySeparatorChar)
.Replace(Path.DirectorySeparatorChar, '.');
var resourceNameFromDir = $"{Path.GetFileNameWithoutExtension(ModuleDefinition.Name)}.{suffix}";
resource = resources.FirstOrDefault(x => x.Name == resourceNameFromDir);
if (resource != null)
{
return resource;
}
var message = $@"Could not find a resource.
CodeDirPath:'{codeDirPath}'
Tried:
searchPath:'{searchPath}'
resourceNameFromNamespace:'{resourceNameFromNamespace}'
resourceNameFromDir:'{resourceNameFromDir}'
";
LogErrorPoint(message, instruction.GetPreviousSequencePoint(method));
return null;
}
} | mit | C# |
cdfd95a3ccbb62417d4d1f786fb2d35eb617062a | Remove old code | pdelvo/Pdelvo.Minecraft.Proxy,pdelvo/Pdelvo.Minecraft.Proxy | Pdelvo.Minecraft.Proxy/Pdelvo.Minecraft.Proxy.Service/ProxyService.cs | Pdelvo.Minecraft.Proxy/Pdelvo.Minecraft.Proxy.Service/ProxyService.cs | using Pdelvo.Minecraft.Proxy.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Pdelvo.Minecraft.Proxy.Service
{
public partial class ProxyService : ServiceBase
{
IProxyServer _server;
public ProxyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
_server = new ProxyServer();
_server.Start();
}
protected override async void OnStop()
{
await _server.StopAsync();
base.OnStop();
}
}
}
| using Pdelvo.Minecraft.Proxy.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Pdelvo.Minecraft.Proxy.Service
{
public partial class ProxyService : ServiceBase
{
IProxyServer _server;
public ProxyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
_server = new ProxyServer();
_server.Start();
while (System.Console.ReadKey(true).Key != ConsoleKey.Q) { }
}
protected override async void OnStop()
{
await _server.StopAsync();
base.OnStop();
}
}
}
| mit | C# |
13aacb7d9a7d30540b24e2313db1f83b80d69bbf | Update MainWindowTests.cs | JohanLarsson/Gu.Wpf.Geometry | Gu.Wpf.Geometry.UiTests/MainWindowTests.cs | Gu.Wpf.Geometry.UiTests/MainWindowTests.cs | namespace Gu.Wpf.Geometry.UiTests
{
using Gu.Wpf.Geometry.UiTests.Helpers;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that we do not explode.
using (var app = Application.Launch(Info.ProcessStartInfo))
{
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
tabItem.Click();
}
}
}
}
}
| namespace Gu.Wpf.Geometry.UiTests
{
using Gu.Wpf.Geometry.UiTests.Helpers;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that everything builds.
using (var app = Application.Launch(Info.ProcessStartInfo))
{
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
tabItem.Click();
}
}
}
}
}
| mit | C# |
f8ebca60c44b6102cedc795c141adc219a5f3f63 | Fix date/time format in FileLogger | Seddryck/RsPackage | SsrsDeploy/Logging/FileLogger.cs | SsrsDeploy/Logging/FileLogger.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrsDeploy.Logging
{
class FileLogger : ILogger
{
private TextWriter writer;
private readonly string path;
public FileLogger(string path)
{
this.path = path;
}
public void WriteMessage(object sender, MessageEventArgs eventArgs)
{
if (writer == null)
BuildWriter();
writer.Write(eventArgs.Time.ToString("dd-MM-yyyy hh:mm:ss.fff"));
writer.Write('\t');
writer.Write(eventArgs.Level);
writer.Write('\t');
writer.WriteLine(eventArgs.Message);
writer.Flush();
}
private void BuildWriter()
{
writer = new StreamWriter(this.path);
}
public void Dispose()
{
writer.Close();
writer.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrsDeploy.Logging
{
class FileLogger : ILogger
{
private TextWriter writer;
private readonly string path;
public FileLogger(string path)
{
this.path = path;
}
public void WriteMessage(object sender, MessageEventArgs eventArgs)
{
if (writer == null)
BuildWriter();
writer.Write(eventArgs.Time);
writer.Write('\t');
writer.Write(eventArgs.Level);
writer.Write('\t');
writer.WriteLine(eventArgs.Message);
writer.Flush();
}
private void BuildWriter()
{
writer = new StreamWriter(this.path);
}
public void Dispose()
{
writer.Close();
writer.Dispose();
}
}
}
| apache-2.0 | C# |
671cc81bc95f458a8ec8c346c497cc8c33b53a82 | fix RemoveObjectTag writing | Alexx999/SwfSharp | SwfSharp/Tags/RemoveObjectTag.cs | SwfSharp/Tags/RemoveObjectTag.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class RemoveObjectTag : RemoveObject2Tag
{
public ushort CharacterId { get; set; }
public RemoveObjectTag(int size)
: base(TagType.RemoveObject, size)
{
}
internal override void FromStream(BitReader reader, byte swfVersion)
{
CharacterId = reader.ReadUI16();
base.FromStream(reader, swfVersion);
}
internal override void ToStream(BitWriter writer, byte swfVersion)
{
writer.WriteUI16(CharacterId);
base.ToStream(writer, swfVersion);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class RemoveObjectTag : RemoveObject2Tag
{
public ushort CharacterId { get; set; }
public RemoveObjectTag(int size)
: base(TagType.RemoveObject, size)
{
}
internal override void FromStream(BitReader reader, byte swfVersion)
{
CharacterId = reader.ReadUI16();
base.FromStream(reader, swfVersion);
}
}
}
| mit | C# |
9e68c9fb5b277905a417422b6d9eb9e63ef0dc6d | Update version | Yonom/MuffinFramework | MuffinFramework/Properties/AssemblyInfo.cs | MuffinFramework/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// 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("MuffinFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MuffinFramework")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
| using System.Reflection;
using System.Resources;
// 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("MuffinFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MuffinFramework")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
a252035deebcfdd1675c5fd291ac1dce7b28dc27 | Complete RequestHandler test coverage | Myslik/NArchitecture | NArchitecture.Tests/RequestHandlerTests.cs | NArchitecture.Tests/RequestHandlerTests.cs | using FakeItEasy;
using System;
using System.Threading.Tasks;
using Xunit;
namespace NArchitecture.Tests
{
public class RequestHandlerTests
{
private class Request : IRequest { }
private class RequestHandler : RequestHandler<Request>
{
protected override Task Handle(RequestHandlerContext context, Request request)
{
return Task.FromResult(0);
}
}
[Fact(DisplayName = "RequestHandler can confirm requests")]
public void CanHandleTest()
{
var request = new Request();
var handler = new RequestHandler();
Assert.True(handler.CanHandle(request));
}
[Fact(DisplayName = "RequestHandler can decline bad requests")]
public void CannotHandleTest()
{
var request = new RequestWithResponse();
var handler = new RequestHandler();
Assert.False(handler.CanHandle(request));
}
[Fact(DisplayName = "RequestHandler throws on bad request")]
public async Task ThrowsOnBadRequestTest()
{
var request = new RequestWithResponse();
var handler = new RequestHandler();
var context = A.Fake<RequestHandlerContext>();
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return handler.Handle(context, request);
});
}
private class RequestWithResponse : IRequest<int> { }
private class RequestWithResponseHandler : RequestHandler<RequestWithResponse, int>
{
protected override Task Handle(RequestHandlerContext<int> context, RequestWithResponse request)
{
return Task.FromResult(0);
}
}
[Fact(DisplayName = "RequestHandler<> can confirm correct requests")]
public void CanHandleWithResponseTest()
{
var request = new RequestWithResponse();
var handler = new RequestWithResponseHandler();
Assert.True(handler.CanHandle(request));
}
[Fact(DisplayName = "RequestHandler<> can decline bad requests")]
public void CannotHandleWithResponseTest()
{
var request = new Request();
var handler = new RequestWithResponseHandler();
Assert.False(handler.CanHandle(request));
}
[Fact(DisplayName = "RequestHandler<> throws on bad request")]
public async Task ThrowsOnBadRequestWithResponseTest()
{
var request = new Request();
var handler = new RequestWithResponseHandler();
var context = A.Fake<RequestHandlerContext>();
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return handler.Handle(context, request);
});
}
}
}
| using System.Threading.Tasks;
using Xunit;
namespace NArchitecture.Tests
{
public class RequestHandlerTests
{
private class RequestWithoutResponse : IRequest { }
private class RequestWithoutResponseHandler : RequestHandler<RequestWithoutResponse>
{
protected override Task Handle(RequestHandlerContext context, RequestWithoutResponse request)
{
return Task.FromResult(0);
}
}
[Fact(DisplayName = "RequestHandler can confirm requests that it handles")]
public void CanHandleTest()
{
var request = new RequestWithoutResponse();
var handler = new RequestWithoutResponseHandler();
Assert.True(handler.CanHandle(request));
}
private class RequestWithResponse : IRequest { }
private class RequestWithResponseHandler : RequestHandler<RequestWithResponse>
{
protected override Task Handle(RequestHandlerContext context, RequestWithResponse request)
{
return Task.FromResult(0);
}
}
[Fact(DisplayName = "RequestHandler can confirm requests with response that it handles")]
public void CanHandleWithResponseTest()
{
var request = new RequestWithResponse();
var handler = new RequestWithResponseHandler();
Assert.True(handler.CanHandle(request));
}
}
}
| mit | C# |
9d040ceb8acbca9c7878b4f6fea4ef49bfdc4faa | Add [STAThread] to Main for COM support if WIN32 | Carbenium/banshee,petejohanson/banshee,dufoli/banshee,allquixotic/banshee-gst-sharp-work,lamalex/Banshee,ixfalia/banshee,stsundermann/banshee,petejohanson/banshee,arfbtwn/banshee,arfbtwn/banshee,mono-soc-2011/banshee,allquixotic/banshee-gst-sharp-work,babycaseny/banshee,ixfalia/banshee,Carbenium/banshee,lamalex/Banshee,stsundermann/banshee,stsundermann/banshee,directhex/banshee-hacks,directhex/banshee-hacks,mono-soc-2011/banshee,ixfalia/banshee,arfbtwn/banshee,GNOME/banshee,Dynalon/banshee-osx,arfbtwn/banshee,directhex/banshee-hacks,Dynalon/banshee-osx,babycaseny/banshee,dufoli/banshee,dufoli/banshee,allquixotic/banshee-gst-sharp-work,arfbtwn/banshee,GNOME/banshee,babycaseny/banshee,GNOME/banshee,GNOME/banshee,GNOME/banshee,babycaseny/banshee,stsundermann/banshee,Carbenium/banshee,arfbtwn/banshee,Carbenium/banshee,GNOME/banshee,stsundermann/banshee,dufoli/banshee,lamalex/Banshee,lamalex/Banshee,mono-soc-2011/banshee,ixfalia/banshee,Dynalon/banshee-osx,eeejay/banshee,mono-soc-2011/banshee,ixfalia/banshee,GNOME/banshee,lamalex/Banshee,Dynalon/banshee-osx,lamalex/Banshee,dufoli/banshee,arfbtwn/banshee,ixfalia/banshee,babycaseny/banshee,mono-soc-2011/banshee,eeejay/banshee,Dynalon/banshee-osx,dufoli/banshee,dufoli/banshee,ixfalia/banshee,directhex/banshee-hacks,Dynalon/banshee-osx,petejohanson/banshee,GNOME/banshee,petejohanson/banshee,directhex/banshee-hacks,babycaseny/banshee,stsundermann/banshee,eeejay/banshee,petejohanson/banshee,eeejay/banshee,arfbtwn/banshee,allquixotic/banshee-gst-sharp-work,petejohanson/banshee,dufoli/banshee,stsundermann/banshee,Carbenium/banshee,Dynalon/banshee-osx,directhex/banshee-hacks,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,babycaseny/banshee,Carbenium/banshee,eeejay/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,babycaseny/banshee,mono-soc-2011/banshee,ixfalia/banshee,allquixotic/banshee-gst-sharp-work | src/Clients/Nereid/Nereid/Client.cs | src/Clients/Nereid/Nereid/Client.cs | //
// Client.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.CommandLine;
using Banshee.Base;
using Banshee.ServiceStack;
namespace Nereid
{
public class Client : Banshee.Gui.GtkBaseClient
{
#if WIN32
// Extracted from Scott's old windows-port branch. I believe this is needed
// for COM-interop needed by the notification-area widget.
[STAThread]
#endif
public static void Main (string [] args)
{
Startup<Nereid.Client> (args);
}
protected override void OnRegisterServices ()
{
ServiceManager.RegisterService<Nereid.PlayerInterface> ();
}
public override string ClientId {
get { return "nereid"; }
}
}
}
| //
// Client.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.CommandLine;
using Banshee.Base;
using Banshee.ServiceStack;
namespace Nereid
{
public class Client : Banshee.Gui.GtkBaseClient
{
public static void Main (string [] args)
{
Startup<Nereid.Client> (args);
}
protected override void OnRegisterServices ()
{
ServiceManager.RegisterService<Nereid.PlayerInterface> ();
}
public override string ClientId {
get { return "nereid"; }
}
}
}
| mit | C# |
305363587df444c7de1417c0ed6606d19bc88772 | refactor 'setupmess' test cases | amiralles/contest,amiralles/contest | src/Contest.Bugs/DuplicateSetups.cs | src/Contest.Bugs/DuplicateSetups.cs | using _ = System.Action<Contest.Core.Runner>;
using static System.Console;
class fixure_wide_setup_teardown {
_ before_each = test => { WriteLine(">>>> fixture setup"); };
_ after_each = test => { WriteLine(">>>> fixture teardown"); };
_ foo = assert => assert.Pass();
_ bar = assert => assert.Pass();
}
class case_specific_setup_teardown {
_ before_foo = test => { WriteLine(">>>> foo setup"); };
_ after_foo = test => { WriteLine(">>>> foo teardown"); };
_ foo = assert => assert.Pass();
_ baz = assert => assert.Pass();
_ bazzinga = assert => assert.Pass();
}
| using _ = System.Action<Contest.Core.Runner>;
using static System.Console;
class fix_one {
_ before_each = test => {
WriteLine(">>>> setup");
};
_ foo = assert => assert.Pass();
_ bar = assert => assert.Pass();
}
class fix_two {
_ baz = assert => assert.Pass();
_ bazzinga = assert => assert.Pass();
}
| mit | C# |
57adb34aa127c9555acfce2e4624b0f95f9f6729 | Update PathOp.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D/Model/Renderer/PathOp.cs | src/Core2D/Model/Renderer/PathOp.cs |
namespace Core2D.Renderer
{
/// <summary>
/// Specifies path op.
/// </summary>
public enum PathOp
{
/// <summary>
/// Difference.
/// </summary>
Difference = 0,
/// <summary>
/// Intersect.
/// </summary>
Intersect = 1,
/// <summary>
/// Union.
/// </summary>
Union = 2,
/// <summary>
/// Xor.
/// </summary>
Xor = 3,
/// <summary>
/// Reverse difference.
/// </summary>
ReverseDifference = 4
}
}
|
namespace Core2D.Renderer
{
/// <summary>
/// Specifies path op.
/// </summary>
public enum PathOp
{
/// <summary>
/// Difference.
/// </summary>
Difference = 0,
/// <summary>
/// Intersect.
/// </summary>
Intersect = 1,
/// <summary>
/// Union.
/// </summary>
Union = 2,
/// <summary>
/// Xor.
/// </summary>
Xor = 3,
/// <summary>
/// Reverse difference,
/// </summary>
ReverseDifference = 4
}
}
| mit | C# |
056235961cf4bb215eea646cee5d793e11c5ab86 | Add parameter to the public method | charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui | Mapsui/Utilities/OpenStreetMap.cs | Mapsui/Utilities/OpenStreetMap.cs | using BruTile.Predefined;
using BruTile.Web;
using Mapsui.Layers;
namespace Mapsui.Utilities
{
public static class OpenStreetMap
{
private const string DefaultUserAgent = "Default Mapsui user-agent";
private static readonly BruTile.Attribution OpenStreetMapAttribution = new BruTile.Attribution(
"© OpenStreetMap contributors", "https://www.openstreetmap.org/copyright");
public static TileLayer CreateTileLayer(string userAgent = DefaultUserAgent)
{
return new TileLayer(CreateTileSource(userAgent)) { Name = "OpenStreetMap" };
}
private static HttpTileSource CreateTileSource(string userAgent)
{
return new HttpTileSource(new GlobalSphericalMercator(),
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
new[] { "a", "b", "c" }, name: "OpenStreetMap",
attribution: OpenStreetMapAttribution, userAgent: userAgent);
}
}
} | using BruTile.Predefined;
using BruTile.Web;
using Mapsui.Layers;
namespace Mapsui.Utilities
{
public static class OpenStreetMap
{
private const string DefaultUserAgent = "Default Mapsui user-agent";
private static readonly BruTile.Attribution OpenStreetMapAttribution = new BruTile.Attribution(
"© OpenStreetMap contributors", "https://www.openstreetmap.org/copyright");
public static TileLayer CreateTileLayer()
{
return new TileLayer(CreateTileSource()) { Name = "OpenStreetMap" };
}
private static HttpTileSource CreateTileSource(string userAgent = DefaultUserAgent)
{
return new HttpTileSource(new GlobalSphericalMercator(),
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
new[] { "a", "b", "c" }, name: "OpenStreetMap",
attribution: OpenStreetMapAttribution, userAgent: userAgent);
}
}
} | mit | C# |
e38d453b1736764fbe860f9e9f5e76407ceea72e | Update Kernel.cs | zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos | Tests/Kernels/Cosmos.Compiler.Tests.MethodTests/Kernel.cs | Tests/Kernels/Cosmos.Compiler.Tests.MethodTests/Kernel.cs | using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.TestRunner;
using Sys = Cosmos.System;
namespace Cosmos.Compiler.Tests.MethodTests
{
public class Kernel : Sys.Kernel
{
protected override void BeforeRun()
{
Console.WriteLine("Cosmos booted successfully. Type a line of text to get it echoed back.");
}
public static void BranchStackCorruption2()
{
char c = 'l';
char c2 = (c <= 'Z' && c >= 'A') ? ((char)(c - 65 + 97)) : c;
c = 'L';
char c3 = (c <= 'Z' && c >= 'A') ? ((char)(c - 65 + 97)) : c;
}
public static void BranchStackCorruption()
{
bool flag1 = true;
bool flag2 = false;
bool flag3 = true;
if (flag1 && (flag2 || flag3))
{
return;
}
else
{
throw new Exception("This should not occur");
}
}
protected override void Run()
{
BranchStackCorruption();
BranchStackCorruption2();
try
{
ReturnTests.Execute();
TestController.Completed();
}
catch (Exception E)
{
Console.WriteLine("Exception");
Console.WriteLine(E.ToString());
}
DelegatesTest.Execute();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.TestRunner;
using Sys = Cosmos.System;
namespace Cosmos.Compiler.Tests.MethodTests
{
public class Kernel : Sys.Kernel
{
protected override void BeforeRun()
{
Console.WriteLine("Cosmos booted successfully. Type a line of text to get it echoed back.");
}
public static void BranchStackCorruption2()
{
char c = 'l';
char c2 = (c <= 'Z' && c >= 'A') ? ((char)(c - 65 + 97)) : c;
c = 'L';
char c3 = (c <= 'Z' && c >= 'A') ? ((char)(c - 65 + 97)) : c;
}
public static void BranchStackCorruption()
{
bool flag1 = true;
bool flag2 = false;
bool flag3 = true;
if (flag1 && (flag2 || flag3))
{
return;
}
else
{
throw new Exception("This should not occur");
}
}
protected override void Run()
{
BranchStackCorruption();
BranchStackCorruption2();
try
{
ReturnTests.Execute();
TestController.Completed();
}
catch (Exception E)
{
Console.WriteLine("Exception");
Console.WriteLine(E.ToString());
}
DelegatesTest.Execute();
}
}
}
| bsd-3-clause | C# |
65a32b8e2b19e842e70feee4eab04450da526825 | Improve performance for realtime API | kiyoaki/bitflyer-api-dotnet-client | src/BitFlyer.Apis/RealtimeApi.cs | src/BitFlyer.Apis/RealtimeApi.cs | using PubNubMessaging.Core;
using System;
using System.Text;
using Utf8Json;
namespace BitFlyer.Apis
{
public class RealtimeApi
{
private readonly Pubnub _pubnub;
public RealtimeApi()
{
_pubnub = new Pubnub("nopublishkey", BitFlyerConstants.SubscribeKey);
}
public void Subscribe<T>(string channel, Action<T> onReceive, Action<string> onConnect, Action<string, Exception> onError)
{
_pubnub.Subscribe(
channel,
s => OnReceiveMessage(s, onReceive, onError),
onConnect,
error =>
{
onError(error.Message, error.DetailedDotNetException);
});
}
private void OnReceiveMessage<T>(string result, Action<T> onReceive, Action<string, Exception> onError)
{
if (string.IsNullOrWhiteSpace(result))
{
return;
}
var reader = new JsonReader(Encoding.UTF8.GetBytes(result));
reader.ReadIsBeginArrayWithVerify();
T deserialized;
try
{
deserialized = JsonSerializer.Deserialize<T>(ref reader);
}
catch (Exception ex)
{
onError(ex.Message, ex);
return;
}
onReceive(deserialized);
}
}
}
| using PubNubMessaging.Core;
using System;
using Utf8Json;
namespace BitFlyer.Apis
{
public class RealtimeApi
{
private readonly Pubnub _pubnub;
public RealtimeApi()
{
_pubnub = new Pubnub("nopublishkey", BitFlyerConstants.SubscribeKey);
}
public void Subscribe<T>(string channel, Action<T> onReceive, Action<string> onConnect, Action<string, Exception> onError)
{
_pubnub.Subscribe(
channel,
s => OnReceiveMessage(s, onReceive, onError),
onConnect,
error =>
{
onError(error.Message, error.DetailedDotNetException);
});
}
private void OnReceiveMessage<T>(string result, Action<T> onReceive, Action<string, Exception> onError)
{
if (string.IsNullOrWhiteSpace(result))
{
return;
}
var deserializedMessage = _pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage == null || deserializedMessage.Count <= 0)
{
return;
}
var subscribedObject = deserializedMessage[0];
if (subscribedObject == null)
{
return;
}
var resultActualMessage = _pubnub.JsonPluggableLibrary.SerializeToJsonString(subscribedObject);
T deserialized;
try
{
deserialized = JsonSerializer.Deserialize<T>(resultActualMessage);
}
catch (Exception ex)
{
onError(ex.Message, ex);
return;
}
onReceive(deserialized);
}
}
}
| mit | C# |
3ffcf0299c01bb2b20a103a45b233c412b0ab284 | Fix stupid error from scafolding | slav40o/Poller,slav40o/Poller,slav40o/Poller | PollerWeb/Poller.Data/PollerDb.cs | PollerWeb/Poller.Data/PollerDb.cs | namespace Poller.Data
{
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using Migrations;
using System.Data.Entity;
public class PollerDb : IdentityDbContext<ApplicationUser>
{
public PollerDb()
: base("PollerD", throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PollerDb, Configuration>());
}
public static PollerDb Create()
{
return new PollerDb();
}
public IDbSet<Poll> Polls { get; set; }
public IDbSet<PollQuestion> PollQuestions { get; set; }
public IDbSet<PollAnswer> PollAnswers { get; set; }
}
}
| namespace Poller.Data
{
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using Migrations;
using System.Data.Entity;
public class PollerDb : IdentityDbContext<ApplicationUser>
{
public PollerDb()
: base("PollerDbConnection", throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PollerDb, Configuration>());
}
public static PollerDb Create()
{
return new PollerDb();
}
public IDbSet<Poll> Polls { get; set; }
public IDbSet<PollQuestion> PollQuestions { get; set; }
public IDbSet<PollAnswer> PollAnswers { get; set; }
public System.Data.Entity.DbSet<Poller.Models.ApplicationUser> ApplicationUsers { get; set; }
}
}
| mit | C# |
2860f5a5cdbee1deb8602ee07b11bdd95d6dcc98 | Revert "Fix D rank displaying as F" | DrabWeb/osu,naoey/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,EVAST9919/osu,ZLima12/osu,EVAST9919/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,naoey/osu,smoogipoo/osu,2yangk23/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Scoring/ScoreRank.cs | osu.Game/Scoring/ScoreRank.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"F")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"SPlus")]
SH,
[Description(@"SS")]
X,
[Description(@"SSPlus")]
XH,
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"D")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"SPlus")]
SH,
[Description(@"SS")]
X,
[Description(@"SSPlus")]
XH,
}
}
| mit | C# |
95f88a521dbb5a43dc7e991b024be6d3287489c1 | add AcceptsReturn, AcceptsTab | TakeAsh/cs-WpfUtility | WpfUtility/TextPrompt.xaml.cs | WpfUtility/TextPrompt.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WpfUtility {
/// <summary>
/// TextPrompt.xaml の相互作用ロジック
/// </summary>
public partial class TextPrompt :
Window {
public TextPrompt() {
InitializeComponent();
}
public string Message {
get { return textBlock_Message.Text; }
set { textBlock_Message.Text = value; }
}
public string InputText {
get { return textBox_Input.Text; }
set { textBox_Input.Text = value; }
}
public bool AcceptsReturn {
get { return textBox_Input.AcceptsReturn; }
set { textBox_Input.AcceptsReturn = value; }
}
public bool AcceptsTab {
get { return textBox_Input.AcceptsTab; }
set { textBox_Input.AcceptsTab = value; }
}
private void Window_Activated(object sender, EventArgs e) {
DialogResult = null;
}
private void button_OK_Click(object sender, RoutedEventArgs e) {
DialogResult = true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WpfUtility {
/// <summary>
/// TextPrompt.xaml の相互作用ロジック
/// </summary>
public partial class TextPrompt :
Window {
public TextPrompt() {
InitializeComponent();
}
public string Message {
get { return textBlock_Message.Text; }
set { textBlock_Message.Text = value; }
}
public string InputText {
get { return textBox_Input.Text; }
set { textBox_Input.Text = value; }
}
private void Window_Activated(object sender, EventArgs e) {
DialogResult = null;
}
private void button_OK_Click(object sender, RoutedEventArgs e) {
DialogResult = true;
}
}
}
| mit | C# |
643cfbf0b13af7574ce9f7027b4dd0c42cda0c8f | Update AssemblyVersion to 1.6 | alexguirre/RAGENativeUI,alexguirre/RAGENativeUI | Source/Properties/AssemblyInfo.cs | Source/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RAGENativeUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RAGENativeUI")]
[assembly: AssemblyCopyright("Copyright 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")]
[assembly: AssemblyVersion("1.6.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RAGENativeUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RAGENativeUI")]
[assembly: AssemblyCopyright("Copyright 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("f3e16ed9-dbf7-4e7b-b04b-9b24b11891d3")]
[assembly: AssemblyVersion("1.5.1.0")]
| mit | C# |
21f614bb2e7faeeafb694a99e633f109a368f9ee | disable app insights telemetry from core.all libs | bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core | src/Icons/Startup.cs | src/Icons/Startup.cs | using System;
using Bit.Icons.Services;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Icons
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Options
services.AddOptions();
// Settings
var iconsSettings = new IconsSettings();
ConfigurationBinder.Bind(Configuration.GetSection("IconsSettings"), iconsSettings);
services.AddSingleton(s => iconsSettings);
// Cache
services.AddMemoryCache(options =>
{
options.SizeLimit = iconsSettings.CacheSizeLimit;
});
services.AddResponseCaching();
// Services
services.AddSingleton<IDomainMappingService, DomainMappingService>();
// Mvc
services.AddMvc();
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
TelemetryConfiguration telemetry)
{
try
{
telemetry.DisableTelemetry = true;
}
catch { }
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseResponseCaching();
app.UseMvc();
}
}
}
| using System;
using Bit.Icons.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Icons
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Options
services.AddOptions();
// Settings
var iconsSettings = new IconsSettings();
ConfigurationBinder.Bind(Configuration.GetSection("IconsSettings"), iconsSettings);
services.AddSingleton(s => iconsSettings);
// Cache
services.AddMemoryCache(options =>
{
options.SizeLimit = iconsSettings.CacheSizeLimit;
});
services.AddResponseCaching();
// Services
services.AddSingleton<IDomainMappingService, DomainMappingService>();
// Mvc
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseResponseCaching();
app.UseMvc();
}
}
}
| agpl-3.0 | C# |
5a252f6b422e50bce64dfa7e68e955042fb384bd | Update PlayerMovement.cs | afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/PlayerMovement.cs | Real_Game/Assets/Scripts/PlayerMovement.cs | using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public GameManager manager;
public float moveSpeed;
private float maxSpeed = 5f;
public int deathCount;
public int killY = -1.5;
public GameObject deathParticals;
private Vector3 input;
private Vector3 spawn;
// Use this for initialization
void Start ()
{
spawn = transform.position;
manager = manager.GetComponent<GameManager>();
}
// Update is called once per frame
void FixedUpdate ()
{
input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if(rigidbody.velocity.magnitude < maxSpeed)
{
rigidbody.AddForce(input * moveSpeed);
}
if (transform.position.y < killY)
{
Die ();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
manager.CompleteLevel();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Enemy") {
Die ();
}
}
void Die() {
deathCount += 1;
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
}
| using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public GameManager manager;
public float moveSpeed;
private float maxSpeed = 5f;
public int deathCount;
public int killY = -2;
public GameObject deathParticals;
private Vector3 input;
private Vector3 spawn;
// Use this for initialization
void Start ()
{
spawn = transform.position;
manager = manager.GetComponent<GameManager>();
}
// Update is called once per frame
void FixedUpdate ()
{
input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if(rigidbody.velocity.magnitude < maxSpeed)
{
rigidbody.AddForce(input * moveSpeed);
}
if (transform.position.y < killY)
{
Die ();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
manager.CompleteLevel();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Enemy")
{
deathCount +=1;
Die ();
}
}
void Die()
{
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
}
| mit | C# |
5495d5e960a053d370b16a9ca5f34bbb5086a625 | Build and publish prerelease package | RockFramework/Rock.Encryption | Rock.Encryption/Properties/AssemblyInfo.cs | Rock.Encryption/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("Rock.Encryption")]
[assembly: AssemblyDescription("An easy-to-use crypto API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Encryption")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a4476f1b-671a-43d1-8bdb-5a275ef62995")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0")]
[assembly: AssemblyInformationalVersion("0.9.0-beta01")]
| 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("Rock.Encryption")]
[assembly: AssemblyDescription("An easy-to-use crypto API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Encryption")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a4476f1b-671a-43d1-8bdb-5a275ef62995")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0")]
[assembly: AssemblyInformationalVersion("0.9.0-alpha01")]
| mit | C# |
c6d7b247e8d895889ee0c273da8738637e0e5717 | Add Dev/Ino fields to Interop.Sys.FileStatus | botaberg/coreclr,AlexGhiondea/coreclr,yeaicc/coreclr,russellhadley/coreclr,gkhanna79/coreclr,AlexGhiondea/coreclr,yeaicc/coreclr,JosephTremoulet/coreclr,AlexGhiondea/coreclr,alexperovich/coreclr,wateret/coreclr,sagood/coreclr,pgavlin/coreclr,hseok-oh/coreclr,alexperovich/coreclr,YongseopKim/coreclr,YongseopKim/coreclr,cydhaselton/coreclr,poizan42/coreclr,botaberg/coreclr,parjong/coreclr,poizan42/coreclr,gkhanna79/coreclr,pgavlin/coreclr,wtgodbe/coreclr,mskvortsov/coreclr,poizan42/coreclr,krytarowski/coreclr,James-Ko/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,krk/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,rartemev/coreclr,russellhadley/coreclr,mskvortsov/coreclr,mmitche/coreclr,gkhanna79/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,dpodder/coreclr,cmckinsey/coreclr,yeaicc/coreclr,JosephTremoulet/coreclr,alexperovich/coreclr,ragmani/coreclr,pgavlin/coreclr,poizan42/coreclr,sagood/coreclr,ragmani/coreclr,cmckinsey/coreclr,ruben-ayrapetyan/coreclr,yizhang82/coreclr,AlexGhiondea/coreclr,yizhang82/coreclr,parjong/coreclr,cmckinsey/coreclr,yizhang82/coreclr,jamesqo/coreclr,cydhaselton/coreclr,sagood/coreclr,krytarowski/coreclr,ruben-ayrapetyan/coreclr,wateret/coreclr,cshung/coreclr,poizan42/coreclr,russellhadley/coreclr,krk/coreclr,jamesqo/coreclr,dpodder/coreclr,krytarowski/coreclr,mskvortsov/coreclr,parjong/coreclr,parjong/coreclr,ragmani/coreclr,tijoytom/coreclr,dpodder/coreclr,dpodder/coreclr,rartemev/coreclr,rartemev/coreclr,gkhanna79/coreclr,JonHanna/coreclr,JonHanna/coreclr,James-Ko/coreclr,tijoytom/coreclr,ragmani/coreclr,AlexGhiondea/coreclr,wateret/coreclr,kyulee1/coreclr,James-Ko/coreclr,AlexGhiondea/coreclr,dpodder/coreclr,JosephTremoulet/coreclr,tijoytom/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,mmitche/coreclr,JonHanna/coreclr,yizhang82/coreclr,kyulee1/coreclr,tijoytom/coreclr,sagood/coreclr,pgavlin/coreclr,sagood/coreclr,cshung/coreclr,cydhaselton/coreclr,russellhadley/coreclr,JonHanna/coreclr,wateret/coreclr,alexperovich/coreclr,wtgodbe/coreclr,YongseopKim/coreclr,hseok-oh/coreclr,ruben-ayrapetyan/coreclr,ragmani/coreclr,wateret/coreclr,yeaicc/coreclr,cydhaselton/coreclr,poizan42/coreclr,dpodder/coreclr,cydhaselton/coreclr,yeaicc/coreclr,qiudesong/coreclr,rartemev/coreclr,russellhadley/coreclr,mmitche/coreclr,JonHanna/coreclr,hseok-oh/coreclr,jamesqo/coreclr,mskvortsov/coreclr,krk/coreclr,JonHanna/coreclr,ragmani/coreclr,cydhaselton/coreclr,yeaicc/coreclr,cshung/coreclr,cmckinsey/coreclr,mskvortsov/coreclr,kyulee1/coreclr,yeaicc/coreclr,cmckinsey/coreclr,qiudesong/coreclr,cmckinsey/coreclr,James-Ko/coreclr,wateret/coreclr,russellhadley/coreclr,James-Ko/coreclr,alexperovich/coreclr,sagood/coreclr,JosephTremoulet/coreclr,jamesqo/coreclr,qiudesong/coreclr,wtgodbe/coreclr,botaberg/coreclr,hseok-oh/coreclr,tijoytom/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,alexperovich/coreclr,cmckinsey/coreclr,kyulee1/coreclr,krk/coreclr,jamesqo/coreclr,yizhang82/coreclr,mmitche/coreclr,kyulee1/coreclr,cshung/coreclr,krk/coreclr,kyulee1/coreclr,rartemev/coreclr,parjong/coreclr,pgavlin/coreclr,YongseopKim/coreclr,qiudesong/coreclr,krk/coreclr,James-Ko/coreclr,parjong/coreclr,qiudesong/coreclr,botaberg/coreclr,qiudesong/coreclr,hseok-oh/coreclr,botaberg/coreclr,rartemev/coreclr,yizhang82/coreclr,gkhanna79/coreclr,tijoytom/coreclr,gkhanna79/coreclr,krytarowski/coreclr,mskvortsov/coreclr,hseok-oh/coreclr,pgavlin/coreclr,botaberg/coreclr,JosephTremoulet/coreclr,YongseopKim/coreclr,cshung/coreclr,krytarowski/coreclr,YongseopKim/coreclr,krytarowski/coreclr,jamesqo/coreclr | src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs | src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Sys
{
// Even though csc will by default use a sequential layout, a CS0649 warning as error
// is produced for un-assigned fields when no StructLayout is specified.
//
// Explicitly saying Sequential disables that warning/error for consumers which only
// use Stat in debug builds.
[StructLayout(LayoutKind.Sequential)]
internal struct FileStatus
{
internal FileStatusFlags Flags;
internal int Mode;
internal uint Uid;
internal uint Gid;
internal long Size;
internal long ATime;
internal long MTime;
internal long CTime;
internal long BirthTime;
internal long Dev;
internal long Ino;
}
internal static class FileTypes
{
internal const int S_IFMT = 0xF000;
internal const int S_IFIFO = 0x1000;
internal const int S_IFCHR = 0x2000;
internal const int S_IFDIR = 0x4000;
internal const int S_IFREG = 0x8000;
internal const int S_IFLNK = 0xA000;
internal const int S_IFSOCK = 0xC000;
}
[Flags]
internal enum FileStatusFlags
{
None = 0,
HasBirthTime = 1,
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)]
internal static extern int FStat(SafeFileHandle fd, out FileStatus output);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
internal static extern int Stat(string path, out FileStatus output);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", SetLastError = true)]
internal static extern int LStat(string path, out FileStatus output);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Sys
{
// Even though csc will by default use a sequential layout, a CS0649 warning as error
// is produced for un-assigned fields when no StructLayout is specified.
//
// Explicitly saying Sequential disables that warning/error for consumers which only
// use Stat in debug builds.
[StructLayout(LayoutKind.Sequential)]
internal struct FileStatus
{
internal FileStatusFlags Flags;
internal int Mode;
internal uint Uid;
internal uint Gid;
internal long Size;
internal long ATime;
internal long MTime;
internal long CTime;
internal long BirthTime;
}
internal static class FileTypes
{
internal const int S_IFMT = 0xF000;
internal const int S_IFIFO = 0x1000;
internal const int S_IFCHR = 0x2000;
internal const int S_IFDIR = 0x4000;
internal const int S_IFREG = 0x8000;
internal const int S_IFLNK = 0xA000;
internal const int S_IFSOCK = 0xC000;
}
[Flags]
internal enum FileStatusFlags
{
None = 0,
HasBirthTime = 1,
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)]
internal static extern int FStat(SafeFileHandle fd, out FileStatus output);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
internal static extern int Stat(string path, out FileStatus output);
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", SetLastError = true)]
internal static extern int LStat(string path, out FileStatus output);
}
}
| mit | C# |
9fbbede027f76880e4649631f189a5c08eb03d8c | Fix spacing | EVAST9919/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,ZLima12/osu,UselessToucan/osu,ZLima12/osu,johnneijzen/osu,UselessToucan/osu,ppy/osu,peppy/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game.Tournament/Screens/Ladder/Components/DrawableMatchPairing.cs | osu.Game.Tournament/Screens/Ladder/Components/DrawableMatchPairing.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using OpenTK;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class DrawableMatchPairing : CompositeDrawable
{
private readonly MatchPairing pairing;
private readonly FillFlowContainer<DrawableMatchTeam> flow;
public DrawableMatchPairing(MatchPairing pairing)
{
this.pairing = pairing;
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding(5);
InternalChild = flow = new FillFlowContainer<DrawableMatchTeam>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(2)
};
pairing.Team1.BindValueChanged(_ => updateTeams());
pairing.Team2.BindValueChanged(_ => updateTeams());
updateTeams();
}
private void updateTeams()
{
// todo: teams may need to be bindable for transitions at a later point.
flow.Children = new[]
{
new DrawableMatchTeam(pairing.Team1, pairing),
new DrawableMatchTeam(pairing.Team2, pairing)
};
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class DrawableMatchPairing : CompositeDrawable
{
private readonly MatchPairing pairing;
private readonly FillFlowContainer<DrawableMatchTeam> flow;
public DrawableMatchPairing(MatchPairing pairing)
{
this.pairing = pairing;
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding(5);
InternalChild = flow = new FillFlowContainer<DrawableMatchTeam>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
};
pairing.Team1.BindValueChanged(_ => updateTeams());
pairing.Team2.BindValueChanged(_ => updateTeams());
updateTeams();
}
private void updateTeams()
{
// todo: teams may need to be bindable for transitions at a later point.
flow.Children = new[]
{
new DrawableMatchTeam(pairing.Team1, pairing),
new DrawableMatchTeam(pairing.Team2, pairing)
};
}
}
}
| mit | C# |
c38abf4841a7c7514423eb09a63de8a6e2517518 | Update ValuesController.cs | cayodonatti/TopGearApi | TopGearApi/Controllers/ValuesController.cs | TopGearApi/Controllers/ValuesController.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace TopGearApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("Test")]
public IHttpActionResult Obter()
{
/*var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " });
return base.Json(content);*/
// Then I return the list
return new JsonResult { Data = new { ab = "teste1", cd = "teste2 " } };
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace TopGearApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
[System.Web.Http.HttpGet]
[Route("Test")]
public IHttpActionResult Obter()
{
/*var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " });
return base.Json(content);*/
// Then I return the list
return new JsonResult { Data = new { ab = "teste1", cd = "teste2 " } };
}
}
}
| mit | C# |
c532cb553de9bbe4d4fd673a3a27909c2deb2c7f | Fix CodeFactor | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Nito/AsyncEx/TaskRemembler.cs | WalletWasabi/Nito/AsyncEx/TaskRemembler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WalletWasabi.Nito.AsyncEx
{
/// <summary>
/// To remember tasks those were fired to forget and so wait for them during dispose.
/// </summary>
public class TaskRemembler
{
private HashSet<Task> Tasks { get; } = new HashSet<Task>();
private object Lock { get; } = new object();
/// <summary>
/// Adds tasks and clears completed ones atomically.
/// </summary>
public void AddAndClearCompleted(params Task[] tasks)
{
lock (Lock)
{
AddNoLock(tasks);
ClearCompletedNoLock();
}
}
/// <summary>
/// Wait for all tasks to complete.
/// </summary>
public async Task WhenAllAsync()
{
do
{
Task[] tasks;
lock (Lock)
{
// 1. Clear all the completed tasks.
ClearCompletedNoLock();
tasks = Tasks.ToArray();
// 2. If all tasks cleared, then break.
if (!tasks.Any())
{
break;
}
}
// 3. Wait for all tasks to complete.
await Task.WhenAll(tasks).ConfigureAwait(false);
}
while (true);
}
private void AddNoLock(params Task[] tasks)
{
foreach (var t in tasks)
{
Tasks.Add(t);
}
}
private void ClearCompletedNoLock()
{
var toRemove = new List<Task>();
foreach (var t in Tasks)
{
if (t.IsCompleted)
{
toRemove.Add(t);
}
}
foreach (var t in toRemove)
{
Tasks.Remove(t);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WalletWasabi.Nito.AsyncEx
{
/// <summary>
/// To remember tasks those were fired to forget and so wait for them during dispose.
/// </summary>
public class TaskRemembler
{
private HashSet<Task> Tasks { get; } = new HashSet<Task>();
private object Lock { get; } = new object();
/// <summary>
/// Adds tasks and clears completed ones atomically.
/// </summary>
public void AddAndClearCompleted(params Task[] tasks)
{
lock (Lock)
{
AddNoLock(tasks);
ClearCompletedNoLock();
}
}
/// <summary>
/// Wait for all tasks to complete.
/// </summary>
public async Task WhenAllAsync()
{
do
{
Task[] tasks;
lock (Lock)
{
// 1. Clear all the completed tasks.
ClearCompletedNoLock();
tasks = Tasks.ToArray();
// 2. If all tasks cleared, then break.
if (!tasks.Any())
{
break;
}
}
// 3. Wait for all tasks to complete.
await Task.WhenAll(tasks).ConfigureAwait(false);
} while (true);
}
private void AddNoLock(params Task[] tasks)
{
foreach (var t in tasks)
{
Tasks.Add(t);
}
}
private void ClearCompletedNoLock()
{
var toRemove = new List<Task>();
foreach (var t in Tasks)
{
if (t.IsCompleted)
{
toRemove.Add(t);
}
}
foreach (var t in toRemove)
{
Tasks.Remove(t);
}
}
}
}
| mit | C# |
431c696332c0ccd112c61b7065be03522a3d8945 | Fix small codacy issue | themehrdad/NetTelebot,vertigra/NetTelebot-2.0 | NetTelebot.Tests/MockServerObject/ResponseString.cs | NetTelebot.Tests/MockServerObject/ResponseString.cs | namespace NetTelebot.Tests.MockServerObject
{
internal static class ResponseString
{
internal const string mExpectedBodyForSendMessageResult =
@"{ ok: ""true"", result: { message_id: 123, date: 0, chat: { id: 123, type: ""private"" }}}";
internal const string mExpectedBodyForGetUserProfilePhotos =
@"{ ok: ""true"", result: { total_count: 1, photos: [[ { file_id: ""123"", width: 123, height: 123 }, { file_id: ""456"", width: 456, height: 456 } ]] }}";
internal const string mExpectedBodyForGetMe =
@"{ ok: ""true"", result: { id: ""123"", first_name: ""FirstName"", username: ""username"" }}";
internal const string mExpectedBodyForBooleanResult = @"{ ok: ""true"", result: ""true"" }";
internal const string mExpectedBodyForBadResponse = @"{ ok: ""false"", error_code: 401, description: ""Unauthorized"")";
}
}
| namespace NetTelebot.Tests.MockServerObject
{
internal static class ResponseString
{
internal static readonly string mExpectedBodyForSendMessageResult =
@"{ ok: ""true"", result: { message_id: 123, date: 0, chat: { id: 123, type: ""private"" }}}";
internal static readonly string mExpectedBodyForGetUserProfilePhotos =
@"{ ok: ""true"", result: { total_count: 1, photos: [[ { file_id: ""123"", width: 123, height: 123 }, { file_id: ""456"", width: 456, height: 456 } ]] }}";
internal static readonly string mExpectedBodyForGetMe =
@"{ ok: ""true"", result: { id: ""123"", first_name: ""FirstName"", username: ""username"" }}";
internal static readonly string mExpectedBodyForBooleanResult = @"{ ok: ""true"", result: ""true"" }";
internal static readonly string mExpectedBodyForBadResponse = @"{ ok: ""false"", error_code: 401, description: ""Unauthorized"")";
}
}
| mit | C# |
57b4953123f8fd8f9e1393b93a1133d7ed3c2c1e | Add spec for RemoveHostnameCommand | appharbor/appharbor-cli | src/AppHarbor.Tests/Commands/RemoveHostnameCommandTest.cs | src/AppHarbor.Tests/Commands/RemoveHostnameCommandTest.cs | using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class RemoveHostnameCommandTest
{
[Theory, AutoCommandData]
public void ShouldThrowIfNoArguments(RemoveHostnameCommand command)
{
Assert.Throws<CommandException>(() => command.Execute(new string[0]));
}
[Theory]
[InlineAutoCommandData("example.com")]
public void ShouldRemoveHostname(string hostname,
[Frozen]Mock<IApplicationConfiguration> applicationConfiguration,
[Frozen]Mock<IAppHarborClient> client,
RemoveHostnameCommand command, string applicationId)
{
applicationConfiguration.Setup(x => x.GetApplicationId()).Returns(applicationId);
command.Execute(new string[] { hostname });
client.Verify(x => x.RemoveHostname(applicationId, hostname));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AppHarbor.Tests.Commands
{
public class RemoveHostnameCommandTest
{
}
}
| mit | C# |
334a73fd03b18e0fc9634bb797498f099482a72b | Rename FromUtf8Bytes => ToUtf8String | dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard | src/Novell.Directory.Ldap.NETStandard/ExtensionMethods.cs | src/Novell.Directory.Ldap.NETStandard/ExtensionMethods.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Novell.Directory.Ldap
{
internal static partial class ExtensionMethods
{
/// <summary>
/// Shortcut for <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsEmpty(this string input) => string.IsNullOrEmpty(input);
/// <summary>
/// Shortcut for negative <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsNotEmpty(this string input) => !IsEmpty(input);
/// <summary>
/// Is the given collection null, or Empty (0 elements)?
/// </summary>
internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0;
/// <summary>
/// Is the given collection not null, and has at least 1 element?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="coll"></param>
/// <returns></returns>
internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetBytes"/>
/// </summary>
internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetString"/>
/// Will return an empty string if <paramref name="input"/> is null or empty.
/// </summary>
internal static string ToUtf8String(this byte[] input)
=> input.IsNotEmpty() ? Encoding.UTF8.GetString(input) : string.Empty;
/// <summary>
/// Compare two strings using <see cref="StringComparison.Ordinal"/>
/// </summary>
internal static bool EqualsOrdinal(this string input, string other) => string.Equals(input, other, StringComparison.Ordinal);
/// <summary>
/// Compare two strings using <see cref="StringComparison.OrdinalIgnoreCase"/>
/// </summary>
internal static bool EqualsOrdinalCI(this string input, string other) => string.Equals(input, other, StringComparison.OrdinalIgnoreCase);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Novell.Directory.Ldap
{
internal static partial class ExtensionMethods
{
/// <summary>
/// Shortcut for <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsEmpty(this string input) => string.IsNullOrEmpty(input);
/// <summary>
/// Shortcut for negative <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsNotEmpty(this string input) => !IsEmpty(input);
/// <summary>
/// Is the given collection null, or Empty (0 elements)?
/// </summary>
internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0;
/// <summary>
/// Is the given collection not null, and has at least 1 element?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="coll"></param>
/// <returns></returns>
internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetBytes"/>
/// </summary>
internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetString"/>
/// Will return an empty string if <paramref name="input"/> is null or empty.
/// </summary>
internal static string FromUtf8Bytes(this byte[] input)
=> input.IsNotEmpty() ? Encoding.UTF8.GetString(input) : string.Empty;
/// <summary>
/// Compare two strings using <see cref="StringComparison.Ordinal"/>
/// </summary>
internal static bool EqualsOrdinal(this string input, string other) => string.Equals(input, other, StringComparison.Ordinal);
/// <summary>
/// Compare two strings using <see cref="StringComparison.OrdinalIgnoreCase"/>
/// </summary>
internal static bool EqualsOrdinalCI(this string input, string other) => string.Equals(input, other, StringComparison.OrdinalIgnoreCase);
}
}
| mit | C# |
8ee1704ca0cc1d16f07a5d19239c5aa95951af8e | Fix summary of NoRawValueLayoutRendererWrapper class (#3532) | sean-gilliam/NLog,304NotModified/NLog,UgurAldanmaz/NLog,snakefoot/NLog,NLog/NLog,luigiberrettini/NLog,BrutalCode/NLog,BrutalCode/NLog,UgurAldanmaz/NLog,luigiberrettini/NLog | src/NLog/LayoutRenderers/Wrappers/NoRawValueLayoutRendererWrapper.cs | src/NLog/LayoutRenderers/Wrappers/NoRawValueLayoutRendererWrapper.cs | //
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers.Wrappers
{
using System;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Render the non-raw value of an object.
/// </summary>
/// <remarks>For performance and/or full (formatted) control of the output.</remarks>
[LayoutRenderer("norawvalue")]
[AmbientProperty("NoRawValue")]
[AppDomainFixedOutput]
[ThreadAgnostic]
[ThreadSafe]
public sealed class NoRawValueLayoutRendererWrapper : WrapperLayoutRendererBase
{
/// <summary>
/// Gets or sets a value indicating whether to disable the IRawValue-interface
/// </summary>
/// <value>A value of <c>true</c> if IRawValue-interface should be ignored; otherwise, <c>false</c>.</value>
/// <docgen category='Transformation Options' order='10' />
[DefaultValue(true)]
public bool NoRawValue { get; set; } = true;
/// <inheritdoc/>
protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength)
{
Inner?.RenderAppendBuilder(logEvent, builder);
}
/// <inheritdoc/>
protected override string Transform(string text)
{
throw new NotSupportedException();
}
}
}
| //
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers.Wrappers
{
using System;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Left part of a text
/// </summary>
[LayoutRenderer("norawvalue")]
[AmbientProperty("NoRawValue")]
[AppDomainFixedOutput]
[ThreadAgnostic]
[ThreadSafe]
public sealed class NoRawValueLayoutRendererWrapper : WrapperLayoutRendererBase
{
/// <summary>
/// Gets or sets a value indicating whether to disable the IRawValue-interface
/// </summary>
/// <value>A value of <c>true</c> if IRawValue-interface should be ignored; otherwise, <c>false</c>.</value>
/// <docgen category='Transformation Options' order='10' />
[DefaultValue(true)]
public bool NoRawValue { get; set; } = true;
/// <inheritdoc/>
protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength)
{
Inner?.RenderAppendBuilder(logEvent, builder);
}
/// <inheritdoc/>
protected override string Transform(string text)
{
throw new NotSupportedException();
}
}
}
| bsd-3-clause | C# |
dd7fe8003bb69fb3f81ba98a535980a1c840e8b8 | edit by index.cshtml | emksaz/testgit2,emksaz/testgit2,emksaz/testgit2 | testgit23/testgit23/Views/Home/Index.cshtml | testgit23/testgit23/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="jumbotron">
<h1>ASP.NET -david.z</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</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>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</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>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</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>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</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>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</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# |
df540fbda33fb849e1191f0e0724e4ae1315b203 | Update Index.cshtml | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: December 8, 2020<br /><br />
<strong>Please Note Holiday Closure Information:</strong><br /><br />
The Lab will be closed from December 24 - January 1<br />
Please arrange sample deliveries by noon on December 23 if possible.<br />
We will reopen with normal business hours on Monday, January 4.<br /><br />
<strong>Also Note:</strong><br /><br />
The emergency arrangement for wine testing has concluded and we are no longer accepting samples for smoke taint analysis.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| mit | C# |
b8f647f061b243de2047c8885b7f7ab0c7e324cf | add subcommand test | hakomikan/CommandUtility | CommandInterfaceTest/SpikeTest.cs | CommandInterfaceTest/SpikeTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.IO;
using System.Reflection;
using CommandInterface;
using static CommandInterfaceTest.CommandRunner;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace CommandInterfaceTest
{
public class CommandRunner
{
public static int RunCommand(string commandName, params string[] parameters)
{
return 1;
}
}
[TestClass]
public class SpikeTest : CommandInterfaceTestBase
{
[TestMethod]
public async Task TestMethod1()
{
Assert.AreEqual(await CSharpScript.EvaluateAsync<int>("1 + 2"), 3);
}
[TestMethod]
public void InterfaceTest()
{
RunCommand("create", "new-command");
RunCommand("edit", "new-command");
RunCommand("list", "new-command");
RunCommand("delete", "new-command");
}
[TestMethod]
public void SubCommandTest()
{
Assert.AreEqual(333, RunCommand("TestScript"));
Assert.AreEqual(666, RunCommand("TestScript2"));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.IO;
using System.Reflection;
using CommandInterface;
using static CommandInterfaceTest.CommandRunner;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace CommandInterfaceTest
{
public class CommandRunner
{
public static void RunCommand(string commandName, params string[] parameters)
{
}
}
[TestClass]
public class SpikeTest
{
[TestMethod]
public async Task TestMethod1()
{
Assert.AreEqual(await CSharpScript.EvaluateAsync<int>("1 + 2"), 3);
}
[TestMethod]
public void InterfaceTest()
{
RunCommand("create", "new-command");
RunCommand("edit", "new-command");
RunCommand("list", "new-command");
RunCommand("delete", "new-command");
}
}
}
| bsd-2-clause | C# |
adad3c36556a207401613253e0a288bbb4c5551f | Fix DI bug | ErikEJ/EntityFramework7.SqlServerCompact,ErikEJ/EntityFramework.SqlServerCompact | src/Provider40/Query/ExpressionVisitors/SqlCeTranslatingExpressionVisitorFactory.cs | src/Provider40/Query/ExpressionVisitors/SqlCeTranslatingExpressionVisitorFactory.cs | using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors
{
/// <summary>
/// A factory for creating instances of <see cref="SqlCeTranslatingExpressionVisitor" />.
/// </summary>
public class SqlCeTranslatingExpressionVisitorFactory : ISqlTranslatingExpressionVisitorFactory
{
private readonly SqlTranslatingExpressionVisitorDependencies _dependencies;
private readonly IDbContextOptions _contextOptions;
/// <summary>
/// Creates a new instance of <see cref="SqlTranslatingExpressionVisitorFactory" />.
/// </summary>
/// <param name="dependencies"> The relational annotation provider. </param>
/// <param name="contextOptions">DbContext options</param>
public SqlCeTranslatingExpressionVisitorFactory(
[NotNull] SqlTranslatingExpressionVisitorDependencies dependencies,
IDbContextOptions contextOptions)
{
Check.NotNull(dependencies, nameof(dependencies));
_dependencies = dependencies;
_contextOptions = contextOptions;
}
/// <summary>
/// Creates a new SqlTranslatingExpressionVisitor.
/// </summary>
/// <param name="queryModelVisitor"> The query model visitor. </param>
/// <param name="targetSelectExpression"> The target select expression. </param>
/// <param name="topLevelPredicate"> The top level predicate. </param>
/// <param name="inProjection"> true if we are translating a projection. </param>
/// <returns>
/// A SqlTranslatingExpressionVisitor.
/// </returns>
public virtual SqlTranslatingExpressionVisitor Create(
RelationalQueryModelVisitor queryModelVisitor,
SelectExpression targetSelectExpression = null,
Expression topLevelPredicate = null,
bool inProjection = false)
=> new SqlCeTranslatingExpressionVisitor(
_dependencies,
_contextOptions,
Check.NotNull(queryModelVisitor, nameof(queryModelVisitor)),
targetSelectExpression,
topLevelPredicate,
inProjection);
}
} | using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors
{
/// <summary>
/// A factory for creating instances of <see cref="SqlCeTranslatingExpressionVisitor" />.
/// </summary>
public class SqlCeTranslatingExpressionVisitorFactory : ISqlTranslatingExpressionVisitorFactory
{
private readonly SqlTranslatingExpressionVisitorDependencies _dependencies;
private readonly IDbContextOptions _contextOptions;
/// <summary>
/// Creates a new instance of <see cref="SqlTranslatingExpressionVisitorFactory" />.
/// </summary>
/// <param name="dependencies"> The relational annotation provider. </param>
/// <param name="contextOptions">DbContext options</param>
public SqlCeTranslatingExpressionVisitorFactory(
[NotNull] SqlTranslatingExpressionVisitorDependencies dependencies,
[NotNull] IDbContextOptions contextOptions)
{
Check.NotNull(dependencies, nameof(dependencies));
_dependencies = dependencies;
_contextOptions = contextOptions;
}
/// <summary>
/// Creates a new SqlTranslatingExpressionVisitor.
/// </summary>
/// <param name="queryModelVisitor"> The query model visitor. </param>
/// <param name="targetSelectExpression"> The target select expression. </param>
/// <param name="topLevelPredicate"> The top level predicate. </param>
/// <param name="inProjection"> true if we are translating a projection. </param>
/// <returns>
/// A SqlTranslatingExpressionVisitor.
/// </returns>
public virtual SqlTranslatingExpressionVisitor Create(
RelationalQueryModelVisitor queryModelVisitor,
SelectExpression targetSelectExpression = null,
Expression topLevelPredicate = null,
bool inProjection = false)
=> new SqlCeTranslatingExpressionVisitor(
_dependencies,
_contextOptions,
Check.NotNull(queryModelVisitor, nameof(queryModelVisitor)),
targetSelectExpression,
topLevelPredicate,
inProjection);
}
} | apache-2.0 | C# |
cf2c887e966fc3ca59e5524de9fc9ac419634e08 | fix formatting | Recognos/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET | Src/Metrics/PerfCounters/PerformanceCounterGauge.cs | Src/Metrics/PerfCounters/PerformanceCounterGauge.cs | using System;
using System.Diagnostics;
namespace Metrics.PerfCounters
{
public class PerformanceCounterGauge : Gauge
{
private static readonly Func<float, string> DefaultFormat = f => f.ToString("F");
private readonly Func<float, string> format;
private readonly PerformanceCounter performanceCounter;
public PerformanceCounterGauge(string category, string counter)
: this(category, counter, instance: null)
{ }
public PerformanceCounterGauge(string category, string counter, Func<float, string> format)
: this(category, counter, instance: null, format: format)
{ }
public PerformanceCounterGauge(string category, string counter, string instance)
: this(category, counter, instance, DefaultFormat)
{ }
public PerformanceCounterGauge(string category, string counter, string instance, Func<float, string> format)
{
this.format = format;
this.performanceCounter = instance == null ?
new PerformanceCounter(category, counter, true) :
new PerformanceCounter(category, counter, instance, true);
}
public GaugeValue Value
{
get
{
return new GaugeValue(format(this.performanceCounter.NextValue()));
}
}
}
}
| using System;
using System.Diagnostics;
namespace Metrics.PerfCounters
{
public class PerformanceCounterGauge : Gauge
{
private static readonly Func<float, string> DefaultFormat = f => f.ToString("F");
private readonly Func<float, string> format;
private readonly PerformanceCounter performanceCounter;
public PerformanceCounterGauge(string category, string counter)
: this(category, counter, instance: null)
{ }
public PerformanceCounterGauge(string category, string counter, Func<float, string> format)
: this(category, counter, instance: null, format: format)
{ }
public PerformanceCounterGauge(string category, string counter, string instance)
: this(category, counter, instance, DefaultFormat)
{ }
public PerformanceCounterGauge(string category, string counter, string instance, Func<float, string> format)
{
this.format = format;
this.performanceCounter = instance == null?
new PerformanceCounter(category, counter, true):
new PerformanceCounter(category, counter, instance, true);
}
public GaugeValue Value
{
get
{
return new GaugeValue(format(this.performanceCounter.NextValue()));
}
}
}
}
| apache-2.0 | C# |
45d77f28cbe04a3952b81c7929f7e3ceda0bf370 | fix typo in MagicScaler benchmark method name | bleroy/core-imaging-playground | NetCore/LoadResizeSaveParallel.cs | NetCore/LoadResizeSaveParallel.cs | using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace ImageProcessing
{
public class LoadResizeSaveParallel : LoadResizeSave
{
[Benchmark(Baseline = true, Description = "System.Drawing Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SystemDrawingBenchmarkParallel()
{
Parallel.ForEach(Images, SystemDrawingResize);
}
[Benchmark(Description = "ImageSharp Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void ImageSharpBenchmarkParallel()
{
Parallel.ForEach(Images, ImageSharpResize);
}
[Benchmark(Description = "ImageMagick Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void MagickBenchmarkParallel()
{
Parallel.ForEach(Images, MagickResize);
}
[Benchmark(Description = "ImageFree Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void FreeImageBenchmarkParallel()
{
Parallel.ForEach(Images, FreeImageResize);
}
[Benchmark(Description = "MagicScaler Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void MagicScalerBenchmarkParallel()
{
Parallel.ForEach(Images, MagicScalerResize);
}
[Benchmark(Description = "SkiaSharp Canvas Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SkiaCanvasBenchmarkParallel()
{
Parallel.ForEach(Images, SkiaCanvasResize);
}
[Benchmark(Description = "SkiaSharp Bitmap Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SkiaBitmapBenchmarkParallel()
{
Parallel.ForEach(Images, SkiaBitmapResize);
}
[Benchmark(Description = "NetVips Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void NetVipsBenchmarkParallel()
{
Parallel.ForEach(Images, NetVipsResize);
}
}
} | using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace ImageProcessing
{
public class LoadResizeSaveParallel : LoadResizeSave
{
[Benchmark(Baseline = true, Description = "System.Drawing Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SystemDrawingBenchmarkParallel()
{
Parallel.ForEach(Images, SystemDrawingResize);
}
[Benchmark(Description = "ImageSharp Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void ImageSharpBenchmarkParallel()
{
Parallel.ForEach(Images, ImageSharpResize);
}
[Benchmark(Description = "ImageMagick Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void MagickBenchmarkParallel()
{
Parallel.ForEach(Images, MagickResize);
}
[Benchmark(Description = "ImageFree Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void FreeImageBenchmarkParallel()
{
Parallel.ForEach(Images, FreeImageResize);
}
[Benchmark(Description = "MagicScaler Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void MagicScalerBenchmarkParallel()
{
Parallel.ForEach(Images, MagickResize);
}
[Benchmark(Description = "SkiaSharp Canvas Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SkiaCanvasBenchmarkParallel()
{
Parallel.ForEach(Images, SkiaCanvasResize);
}
[Benchmark(Description = "SkiaSharp Bitmap Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void SkiaBitmapBenchmarkParallel()
{
Parallel.ForEach(Images, SkiaBitmapResize);
}
[Benchmark(Description = "NetVips Load, Resize, Save - Parallel"/*,
OperationsPerInvoke = ImagesCount*/)]
public void NetVipsBenchmarkParallel()
{
Parallel.ForEach(Images, NetVipsResize);
}
}
} | mit | C# |
0353fd55dcf1934b05d823877f7f3cab82157e5f | Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | autofac/Autofac.Multitenant | Properties/VersionAssemblyInfo.cs | Properties/VersionAssemblyInfo.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
| mit | C# |
8264e2b0132a0cf11addd0ba12e2a18ec412992c | Update AssemblyInfo.cs | paragmeshram/Focusr | Focusr/Properties/AssemblyInfo.cs | Focusr/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("Focusr")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Focusr")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97883cb8-019d-4a13-90fe-c6c1e665ba1f")]
// 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")]
| 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("Focusr")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Focusr")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97883cb8-019d-4a13-90fe-c6c1e665ba1f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit | C# |
4c601d288180efbdcdba4d97e854353f048e818a | Add test data seeder to DbContext. | derrickcreamer/NoteFolder,derrickcreamer/NoteFolder | NoteFolder/Models/File.cs | NoteFolder/Models/File.cs | using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NoteFolder.Models {
public class FileTestInit : DropCreateDatabaseAlways<FileDbContext> {
protected override void Seed(FileDbContext db) {
var docs = new File { Name = "Documents", Description = "", IsFolder = true };
var proj = new File { Name = "Projects", Description = "", IsFolder = true };
var nf = new File { Name = "NoteFolder", Description = "Note organization", IsFolder = true };
var sln = new File { Name = "NoteFolder.sln", Description = "", IsFolder = false, Text = "<Solution text>" };
var source = new File { Name = "Source", Description = "", IsFolder = true };
var cs = new File { Name = "NoteFolder.cs", Description = "", IsFolder = false, Text = "<Source code>" };
proj.SetParent(docs);
nf.SetParent(proj);
sln.SetParent(nf);
source.SetParent(nf);
cs.SetParent(source);
db.Files.AddRange(new File[] {docs, proj, nf, sln, source, cs });
base.Seed(db);
}
}
public static class FileDebugExtensions {
public static void SetParent(this File f, File parent) {
f.Parent = parent;
parent.Children.Add(f);
}
}
public class FileDbContext : DbContext {
public DbSet<File> Files { get; set; }
public FileDbContext() {
Database.SetInitializer(new FileTestInit());
}
}
public class File {
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Text { get; set; }
public bool IsFolder { get; set; }
public DateTime TimeCreated {get; set; }
public DateTime TimeLastEdited { get; set; }
public virtual File Parent { get; set; }
public virtual ICollection<File> Children { get; set; }
}
}
| using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NoteFolder.Models {
public class FileDbContext : DbContext {
public DbSet<File> Files { get; set; }
}
public class File {
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Text { get; set; }
public bool IsFolder { get; set; }
public DateTime TimeCreated {get; set; }
public DateTime TimeLastEdited { get; set; }
public virtual File Parent { get; set; }
public virtual ICollection<File> Children { get; set; }
}
}
| mit | C# |
6f306bc1c2684825ff3cb11a73da5dbc8a2e9143 | Reduce default bucket count for HTTP request duration to 16 | andrasm/prometheus-net | Prometheus.AspNetCore/HttpMetrics/HttpRequestDurationOptions.cs | Prometheus.AspNetCore/HttpMetrics/HttpRequestDurationOptions.cs | namespace Prometheus.HttpMetrics
{
public sealed class HttpRequestDurationOptions : HttpMetricsOptionsBase
{
private const string DefaultName = "http_request_duration_seconds";
private const string DefaultHelp =
"Provides the duration in seconds of HTTP requests from an ASP.NET application.";
public Histogram Histogram { get; set; } = Metrics.CreateHistogram(DefaultName, DefaultHelp,
new HistogramConfiguration
{
Buckets = Histogram.ExponentialBuckets(0.001, 2, 16),
LabelNames = HttpRequestLabelNames.All
});
}
} | namespace Prometheus.HttpMetrics
{
public sealed class HttpRequestDurationOptions : HttpMetricsOptionsBase
{
private const string DefaultName = "http_request_duration_seconds";
private const string DefaultHelp =
"Provides the duration in seconds of HTTP requests from an ASP.NET application.";
public Histogram Histogram { get; set; } = Metrics.CreateHistogram(DefaultName, DefaultHelp,
new HistogramConfiguration
{
Buckets = Histogram.ExponentialBuckets(0.0001, 1.5, 36),
LabelNames = HttpRequestLabelNames.All
});
}
} | mit | C# |
aa481e944b2ee3a901f6c8ac24dd386832fc93da | Add the ChatComponent to the Index page. | jamesmontemagno/MotzCodesLive,jamesmontemagno/MotzCodesLive,jamesmontemagno/MotzCodesLive | Twitch-SignalRSaturdays/XamChat.BlazorClient/Pages/Index.cshtml | Twitch-SignalRSaturdays/XamChat.BlazorClient/Pages/Index.cshtml | @page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<ChatComponent/> | @page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
| mit | C# |
c68eed129d6c42bd81e8d427edb440356a237f04 | Update SingleEntryCurrencyConversionCompositionStrategy.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs | TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TIKSN.Finance.Helpers;
namespace TIKSN.Finance
{
public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy
{
public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters,
CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency,
counterCurrency, asOn, cancellationToken);
var converter = filteredConverters.Single();
return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken);
}
public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair,
DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken);
var converter = filteredConverters.Single();
return await converter.GetExchangeRateAsync(pair, asOn, cancellationToken);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TIKSN.Finance.Helpers;
namespace TIKSN.Finance
{
public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy
{
public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken);
var converter = filteredConverters.Single();
return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken);
}
public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken);
var converter = filteredConverters.Single();
return await converter.GetExchangeRateAsync(pair, asOn, cancellationToken);
}
}
} | mit | C# |
8d095b68eb054d6a823bc8c98d6e4ed24f056beb | optimize file cache provider | tinohager/Nager.PublicSuffix,tinohager/Nager.PublicSuffix,tinohager/Nager.PublicSuffix | src/Nager.PublicSuffix/FileCacheProvider.cs | src/Nager.PublicSuffix/FileCacheProvider.cs | using System;
using System.IO;
using System.Threading.Tasks;
namespace Nager.PublicSuffix
{
public class FileCacheProvider : ICacheProvider
{
private readonly string _cacheFilePath;
private readonly TimeSpan _timeToLive;
public FileCacheProvider(string cacheFileName = "publicsuffixcache.dat", TimeSpan? cacheTimeToLive = null)
{
if (cacheTimeToLive.HasValue)
{
this._timeToLive = cacheTimeToLive.Value;
}
else
{
this._timeToLive = TimeSpan.FromDays(1);
}
var tempPath = Path.GetTempPath();
this._cacheFilePath = Path.Combine(tempPath, cacheFileName);
}
public bool IsCacheValid()
{
var cacheInvalid = true;
var fileInfo = new FileInfo(this._cacheFilePath);
if (fileInfo.Exists)
{
if (fileInfo.LastWriteTimeUtc > DateTime.UtcNow.Subtract(this._timeToLive))
{
cacheInvalid = false;
}
}
return !cacheInvalid;
}
public Task<string> GetValueAsync()
{
if (!this.IsCacheValid())
{
return Task.FromResult<string>(null);
}
return Task.FromResult(File.ReadAllText(this._cacheFilePath));
}
public async Task SetValueAsync(string val)
{
using (var streamWriter = File.CreateText(this._cacheFilePath))
{
await streamWriter.WriteAsync(val).ConfigureAwait(false);
}
}
}
}
| using System;
using System.IO;
using System.Threading.Tasks;
namespace Nager.PublicSuffix
{
public class FileCacheProvider : ICacheProvider
{
private readonly string _cacheName;
private readonly TimeSpan _timeToLive;
public FileCacheProvider(string fileCacheName = "publicsuffixcache.dat", TimeSpan? cacheTimeToLive = null)
{
if (cacheTimeToLive.HasValue)
{
this._timeToLive = cacheTimeToLive.Value;
}
else
{
this._timeToLive = TimeSpan.FromDays(1);
}
this._cacheName = fileCacheName;
}
public bool IsCacheValid()
{
var cacheInvalid = true;
var fileInfo = new FileInfo(this._cacheName);
if (fileInfo.Exists)
{
if (fileInfo.LastWriteTimeUtc > DateTime.UtcNow.Subtract(this._timeToLive))
{
cacheInvalid = false;
}
}
return !cacheInvalid;
}
public Task<string> GetValueAsync()
{
if (!this.IsCacheValid())
{
return Task.FromResult<string>(null);
}
return Task.FromResult(File.ReadAllText(this._cacheName));
}
public async Task SetValueAsync(string val)
{
using (var streamWriter = File.CreateText(this._cacheName))
{
await streamWriter.WriteAsync(val).ConfigureAwait(false);
}
}
}
}
| mit | C# |
87a86c521ad308773dd852ed3d81a6f8b7df3289 | Make all actor's protected methods public | OrleansContrib/Orleankka,yevhen/Orleankka,mhertis/Orleankka,pkese/Orleankka,mhertis/Orleankka,pkese/Orleankka,AntyaDev/Orleankka,AntyaDev/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka | Source/Orleankka/Actor.cs | Source/Orleankka/Actor.cs | using System;
using System.Threading.Tasks;
using Orleans;
namespace Orleankka
{
using Core;
using Services;
using Utility;
public interface IActor
{}
public abstract class Actor : IActor
{
ActorRef self;
protected Actor()
{}
protected Actor(string id, IActorRuntime runtime)
{
Requires.NotNull(runtime, nameof(runtime));
Requires.NotNullOrWhitespace(id, nameof(id));
Id = id;
Runtime = runtime;
}
internal void Initialize(string id, IActorRuntime runtime, ActorPrototype prototype)
{
Id = id;
Runtime = runtime;
Prototype = prototype;
}
public string Id
{
get; private set;
}
public IActorRuntime Runtime
{
get; set;
}
internal ActorPrototype Prototype
{
get; set;
}
public ActorRef Self => self ?? (self = System.ActorOf(GetType(), Id));
public IActorSystem System => Runtime.System;
public IActivationService Activation => Runtime.Activation;
public IReminderService Reminders => Runtime.Reminders;
public ITimerService Timers => Runtime.Timers;
public virtual Task OnActivate() => TaskDone.Done;
public virtual Task OnDeactivate() => TaskDone.Done;
public virtual Task OnReminder(string id)
{
var message = $"Override {"OnReminder"}() method in class {GetType()} to implement corresponding behavior";
throw new NotImplementedException(message);
}
public virtual Task<object> OnReceive(object message)
{
return Dispatch(message);
}
public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null)
{
return (TResult)await Dispatch(message, fallback);
}
public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null)
{
Requires.NotNull(message, nameof(message));
return Prototype.Dispatch(this, message, fallback);
}
}
} | using System;
using System.Threading.Tasks;
using Orleans;
namespace Orleankka
{
using Core;
using Services;
using Utility;
public interface IActor
{}
public abstract class Actor : IActor
{
ActorRef self;
protected Actor()
{}
protected Actor(string id, IActorRuntime runtime)
{
Requires.NotNull(runtime, nameof(runtime));
Requires.NotNullOrWhitespace(id, nameof(id));
Id = id;
Runtime = runtime;
}
internal void Initialize(string id, IActorRuntime runtime, ActorPrototype prototype)
{
Id = id;
Runtime = runtime;
Prototype = prototype;
}
protected string Id
{
get; private set;
}
private IActorRuntime Runtime
{
get; set;
}
internal ActorPrototype Prototype
{
get; set;
}
protected ActorRef Self => self ?? (self = System.ActorOf(GetType(), Id));
protected IActorSystem System => Runtime.System;
protected IActivationService Activation => Runtime.Activation;
protected IReminderService Reminders => Runtime.Reminders;
protected ITimerService Timers => Runtime.Timers;
public virtual Task OnActivate() => TaskDone.Done;
public virtual Task OnDeactivate() => TaskDone.Done;
public virtual Task OnReminder(string id)
{
var message = $"Override {"OnReminder"}() method in class {GetType()} to implement corresponding behavior";
throw new NotImplementedException(message);
}
public virtual Task<object> OnReceive(object message)
{
return Dispatch(message);
}
public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null)
{
return (TResult)await Dispatch(message, fallback);
}
public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null)
{
Requires.NotNull(message, nameof(message));
return Prototype.Dispatch(this, message, fallback);
}
}
} | apache-2.0 | C# |
8722681a428fb24922c236e6a45a9aa1c650d210 | Reduce contributors to work for cloud tests. | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | backend/tools/TestSuite/TestSuite.Shared/Fixtures/CreatedAppFixture.cs | backend/tools/TestSuite/TestSuite.Shared/Fixtures/CreatedAppFixture.cs | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.ClientLibrary.Management;
namespace TestSuite.Fixtures
{
public class CreatedAppFixture : ClientFixture
{
private static readonly string[] Contributors =
{
"hello@squidex.io"
};
private static bool isCreated;
public CreatedAppFixture()
{
if (!isCreated)
{
Task.Run(async () =>
{
try
{
await Apps.PostAppAsync(new CreateAppDto { Name = AppName });
}
catch (SquidexManagementException ex)
{
if (ex.StatusCode != 400)
{
throw;
}
}
var invite = new AssignContributorDto { Invite = true, Role = "Owner" };
foreach (var contributor in Contributors)
{
invite.ContributorId = contributor;
await Apps.PostContributorAsync(AppName, invite);
}
}).Wait();
isCreated = true;
}
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.ClientLibrary.Management;
namespace TestSuite.Fixtures
{
public class CreatedAppFixture : ClientFixture
{
private static readonly string[] Contributors =
{
"sebastian@squidex.io",
"hello1@squidex.io",
"hello2@squidex.io",
};
private static bool isCreated;
public CreatedAppFixture()
{
if (!isCreated)
{
Task.Run(async () =>
{
try
{
await Apps.PostAppAsync(new CreateAppDto { Name = AppName });
}
catch (SquidexManagementException ex)
{
if (ex.StatusCode != 400)
{
throw;
}
}
var invite = new AssignContributorDto { Invite = true, Role = "Owner" };
foreach (var contributor in Contributors)
{
invite.ContributorId = contributor;
await Apps.PostContributorAsync(AppName, invite);
}
}).Wait();
isCreated = true;
}
}
}
}
| mit | C# |
b7899440a6bb987a502abc2a353f8fb7e588ea2d | fix Automate not serialising object types as strings | Pathoschild/StardewMods | Automate/Framework/Models/ModConfigObject.cs | Automate/Framework/Models/ModConfigObject.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Pathoschild.Stardew.Automate.Framework.Models
{
/// <summary>An object identifier.</summary>
internal class ModConfigObject
{
/// <summary>The object type.</summary>
[JsonConverter(typeof(StringEnumConverter))]
public ObjectType Type { get; set; }
/// <summary>The object ID.</summary>
public int ID { get; set; }
}
}
| namespace Pathoschild.Stardew.Automate.Framework.Models
{
/// <summary>An object identifier.</summary>
internal class ModConfigObject
{
/// <summary>The object type.</summary>
public ObjectType Type { get; set; }
/// <summary>The object ID.</summary>
public int ID { get; set; }
}
}
| mit | C# |
aba71fbf4bcaec669994dac25d87c9a97efa93a6 | Use boxenterprise.net when viewing file of folder from Acumatica | Acumatica/acumatica-boxstorageprovider,Acumatica/acumatica-boxstorageprovider | BoxStorageProvider/Pages/SM/SM202670.aspx.cs | BoxStorageProvider/Pages/SM/SM202670.aspx.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PX.Data;
using PX.SM.BoxStorageProvider;
using PX.Common;
public partial class Pages_SM_SM202670 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string folderID = Request.QueryString["FolderID"];
string fileID = Request.QueryString["FileID"];
if (!String.IsNullOrEmpty(folderID) && !String.IsNullOrEmpty(fileID))
{
fraContent.Attributes["src"] = "https://boxenterprise.net/embed_widget/000000000000/files/0/f/" + folderID + "/1/f_" + fileID;
}
else if (!String.IsNullOrEmpty(folderID))
{
fraContent.Attributes["src"] = "https://boxenterprise.net/embed_widget/000000000000/files/0/f/" + folderID;
}
else
{
Response.Write("Error. Missing FolderID/FileID Parameters.");
return;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PX.Data;
using PX.SM.BoxStorageProvider;
using PX.Common;
public partial class Pages_SM_SM202670 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string folderID = Request.QueryString["FolderID"];
string fileID = Request.QueryString["FileID"];
if (!String.IsNullOrEmpty(folderID) && !String.IsNullOrEmpty(fileID))
{
fraContent.Attributes["src"] = "https://box.com/embed_widget/000000000000/files/0/f/" + folderID + "/1/f_" + fileID;
}
else if (!String.IsNullOrEmpty(folderID))
{
fraContent.Attributes["src"] = "https://box.com/embed_widget/000000000000/files/0/f/" + folderID;
}
else
{
Response.Write("Error. Missing FolderID/FileID Parameters.");
return;
}
}
} | mit | C# |
a88f450c750fac814913acae6ec0c3b679868733 | Remove unused delegate | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Models/Delegates.cs | R7.University/Models/Delegates.cs | using R7.University.Models;
namespace R7.University
{
public delegate string GetDocumentTitle (IDocument document);
}
| using R7.University.Models;
namespace R7.University
{
public delegate string LocalizeHandler (string resourceKey);
public delegate string GetDocumentTitle (IDocument document);
}
| agpl-3.0 | C# |
ef264bf29f85232006f863ca99d5672a3f29ecfe | Allow control over references being added | andrewdavey/cassette,damiensawyer/cassette,damiensawyer/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,honestegg/cassette,andrewdavey/cassette | src/Cassette/BundleProcessing/ParseReferences.cs | src/Cassette/BundleProcessing/ParseReferences.cs | using System.IO;
namespace Cassette.BundleProcessing
{
public abstract class ParseReferences<T> : IBundleProcessor<T>
where T : Bundle
{
public void Process(T bundle)
{
foreach (var asset in bundle.Assets)
{
if (ShouldParseAsset(asset))
{
ParseAssetReferences(asset);
}
}
}
protected virtual bool ShouldParseAsset(IAsset asset)
{
return true;
}
protected virtual bool ShouldAddReference(string referencePath)
{
return true;
}
void ParseAssetReferences(IAsset asset)
{
string code;
using (var reader = new StreamReader(asset.OpenStream()))
{
code = reader.ReadToEnd();
}
var commentParser = CreateCommentParser();
var referenceParser = CreateReferenceParser(commentParser);
var references = referenceParser.Parse(code, asset);
foreach (var reference in references)
{
if (ShouldAddReference(reference.Path))
{
asset.AddReference(reference.Path, reference.LineNumber);
}
}
}
internal virtual ReferenceParser CreateReferenceParser(ICommentParser commentParser)
{
return new ReferenceParser(commentParser);
}
protected abstract ICommentParser CreateCommentParser();
}
} | using System.IO;
namespace Cassette.BundleProcessing
{
public abstract class ParseReferences<T> : IBundleProcessor<T>
where T : Bundle
{
public void Process(T bundle)
{
foreach (var asset in bundle.Assets)
{
if (ShouldParseAsset(asset))
{
ParseAssetReferences(asset);
}
}
}
protected virtual bool ShouldParseAsset(IAsset asset)
{
return true;
}
void ParseAssetReferences(IAsset asset)
{
string code;
using (var reader = new StreamReader(asset.OpenStream()))
{
code = reader.ReadToEnd();
}
var commentParser = CreateCommentParser();
var referenceParser = CreateReferenceParser(commentParser);
var references = referenceParser.Parse(code, asset);
foreach (var reference in references)
{
asset.AddReference(reference.Path, reference.LineNumber);
}
}
internal virtual ReferenceParser CreateReferenceParser(ICommentParser commentParser)
{
return new ReferenceParser(commentParser);
}
protected abstract ICommentParser CreateCommentParser();
}
} | mit | C# |
f882ab8586cfe5fff215802dbe6afb1ff112cdad | allow to use args to set url address More here: https://stackoverflow.com/q/45710570/2833802 | ORuban/aspnet-core-experimentarium,ORuban/aspnet-core-experimentarium | src/Experimentarium.AspNetCore.WebApi/Program.cs | src/Experimentarium.AspNetCore.WebApi/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Experimentarium.AspNetCore.WebApi
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
// The ConfigureAppConfiguration was intended to configure the IConfiguration in the application services
// whereas UseConfiguration is intended to configure the settings of the WebHostBuilder.
// Since the url address is a setting on the WebHostBuilder only UseConfiguration will work here.
// More here https://github.com/aspnet/Hosting/issues/1148
var argsConfig = new ConfigurationBuilder().AddCommandLine(args).Build();
var webHost = WebHost.CreateDefaultBuilder(args)
.UseConfiguration(argsConfig)
.ConfigureAppConfiguration((builderContext, config) =>
{
IHostingEnvironment env = builderContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>()
.Build();
return webHost;
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Experimentarium.AspNetCore.WebApi
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((builderContext, config) =>
{
IHostingEnvironment env = builderContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>()
.Build();
}
}
| mit | C# |
66b02f9312ea616b7e210fa225754126867693e9 | Switch to allow system bus monitoring | tmds/Tmds.DBus | Monitor.cs | Monitor.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main (string[] args)
{
string addr = Address.SessionBus;
if (args.Length == 1) {
string arg = args[0];
switch (arg)
{
case "--system":
addr = Address.SystemBus;
break;
case "--session":
addr = Address.SessionBus;
break;
default:
Console.Error.WriteLine ("Usage: monitor.exe [--system | --session]");
return;
}
}
Connection conn = new Connection (false);
conn.Open (addr);
conn.Authenticate ();
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
Bus bus = conn.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
bus.Hello ();
//hack to process the NameAcquired signal synchronously
conn.HandleSignal (conn.ReadMessage ());
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
while (true) {
Message msg = conn.ReadMessage ();
Console.WriteLine ("Message:");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t" + field.Key + ": " + field.Value);
if (msg.Body != null) {
Console.WriteLine ("\tBody:");
//System.IO.MemoryStream ms = new System.IO.MemoryStream (msg.Body);
//System.IO.MemoryStream ms = msg.Body;
//TODO: this needs to be done more intelligently
try {
foreach (DType dtype in msg.Signature.Data) {
if (dtype == DType.Invalid)
continue;
object arg;
Message.GetValue (msg.Body, dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
} catch {
Console.WriteLine ("\t\tmonitor is too dumb to decode message body");
}
}
Console.WriteLine ();
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main (string[] args)
{
//TODO: allow selection of bus
if (args.Length == 1) {
string arg = args[1];
switch (arg)
{
case "--system":
break;
case "--session":
break;
default:
break;
}
}
Connection conn = new Connection ();
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
Bus bus = conn.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
bus.Hello ();
//hack to process the NameAcquired signal synchronously
conn.HandleSignal (conn.ReadMessage ());
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
while (true) {
Message msg = conn.ReadMessage ();
Console.WriteLine ("Message:");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t" + field.Key + ": " + field.Value);
if (msg.Body != null) {
Console.WriteLine ("\tBody:");
//System.IO.MemoryStream ms = new System.IO.MemoryStream (msg.Body);
//System.IO.MemoryStream ms = msg.Body;
//TODO: this needs to be done more intelligently
try {
foreach (DType dtype in msg.Signature.Data) {
if (dtype == DType.Invalid)
continue;
object arg;
Message.GetValue (msg.Body, dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
} catch {
Console.WriteLine ("\t\tmonitor is too dumb to decode message body");
}
}
Console.WriteLine ();
}
}
}
| mit | C# |
402d77c907905c47ff416cc29f6defc9bd209213 | allow binding type to be set in constructor | alexrster/SAML2,elerch/SAML2 | src/SAML2.Core/Config/ServiceProviderEndpoint.cs | src/SAML2.Core/Config/ServiceProviderEndpoint.cs | using System.Configuration;
namespace SAML2.Config
{
/// <summary>
/// Service Provider Endpoint configuration element.
/// </summary>
public class ServiceProviderEndpoint
{
public ServiceProviderEndpoint() { }
public ServiceProviderEndpoint(EndpointType type, string localPath, string redirectUrl = null, BindingType bindingType = BindingType.NotSet) : this()
{
Type = type;
LocalPath = localPath;
RedirectUrl = redirectUrl;
Binding = bindingType;
}
/// <summary>
/// Gets or sets the binding.
/// </summary>
/// <value>The binding.</value>
public BindingType Binding { get; set; }
/// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
public int Index { get; set; }
/// <summary>
/// Gets or sets the local path.
/// </summary>
/// <value>The local path.</value>
public string LocalPath { get; set; }
/// <summary>
/// Gets or sets the redirect URL.
/// </summary>
/// <value>The redirect URL.</value>
public string RedirectUrl { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public EndpointType Type { get; set; }
}
}
| using System.Configuration;
namespace SAML2.Config
{
/// <summary>
/// Service Provider Endpoint configuration element.
/// </summary>
public class ServiceProviderEndpoint
{
public ServiceProviderEndpoint() { }
public ServiceProviderEndpoint(EndpointType type, string localPath, string redirectUrl = null) : this()
{
Type = type;
LocalPath = localPath;
RedirectUrl = redirectUrl;
}
/// <summary>
/// Gets or sets the binding.
/// </summary>
/// <value>The binding.</value>
public BindingType Binding { get; set; }
/// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
public int Index { get; set; }
/// <summary>
/// Gets or sets the local path.
/// </summary>
/// <value>The local path.</value>
public string LocalPath { get; set; }
/// <summary>
/// Gets or sets the redirect URL.
/// </summary>
/// <value>The redirect URL.</value>
public string RedirectUrl { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public EndpointType Type { get; set; }
}
}
| mpl-2.0 | C# |
93e618e52b4c41ef48a1b6ba865cdcf103c9e241 | Update control and move management | Sparox/GGJ_2015 | Game/Assets/Scripts/Character2DController.cs | Game/Assets/Scripts/Character2DController.cs | using UnityEngine;
using System.Collections;
using UnitySampleAssets._2D;
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Character2DController : MonoBehaviour {
private bool jump;
public KeyCode actionKey;
public KeyCode leftKey;
public KeyCode rightKey;
private PlatformerCharacter2D character;
public Transform BlocPrefab;
private bool canCreateBlock = true;
private enum actionType
{
Jump
};
private actionType type;
private float direction = 0f;
private void Awake()
{
character = GetComponent<PlatformerCharacter2D> ();
type = actionType.Jump;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(leftKey))
{
direction = -1f;
}
if (Input.GetKey(rightKey))
{
direction = 1f;
}
if (!Input.GetKey(leftKey) && !Input.GetKey(rightKey))
{
direction = 0f;
}
if (Input.GetKey(leftKey) && Input.GetKey(rightKey))
{
direction = 0f;
}
if(Input.GetKeyDown(actionKey))
{
switch (type) {
case actionType.Jump:
jump = true;
break;
default:
break;
}
}
}
private void GenerateCube()
{
var posNewBloc = new Vector3 (this.transform.position.x, this.transform.localPosition.y - 2, this.transform.position.z);
//var newBloc = Instantiate (BlocPrefab, posNewBloc, Quaternion.identity);
}
private void FixedUpdate()
{
// Read the inputs.
float h = direction;
// Pass all parameters to the character control script.
character.Move(h, false, jump);
jump = false;
/*if(!canCreateBlock && character.IsGrounded())
{
canCreateBlock = true;
}*/
}
}
| using UnityEngine;
using System.Collections;
using UnitySampleAssets._2D;
[RequireComponent(typeof (PlatformerCharacter2D))]
public class Character2DController : MonoBehaviour {
private bool jump;
public KeyCode actionKey;
public KeyCode leftKey;
public KeyCode rightKey;
private PlatformerCharacter2D character;
public Transform BlocPrefab;
private bool canCreateBlock = true;
private enum actionType
{
Jump
};
private actionType type;
private float direction = 0f;
private void Awake()
{
character = GetComponent<PlatformerCharacter2D> ();
type = actionType.Jump;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(leftKey))
{
direction = -1f;
}
else if (Input.GetKey(rightKey))
{
direction = 1f;
}
else
{
direction = 0f;
}
if(Input.GetKeyDown(actionKey))
{
switch (type) {
case actionType.Jump:
jump = true;
break;
default:
break;
}
}
}
private void GenerateCube()
{
var posNewBloc = new Vector3 (this.transform.position.x, this.transform.localPosition.y - 2, this.transform.position.z);
//var newBloc = Instantiate (BlocPrefab, posNewBloc, Quaternion.identity);
}
private void FixedUpdate()
{
// Read the inputs.
float h = direction;
// Pass all parameters to the character control script.
character.Move(h, false, jump);
jump = false;
/*if(!canCreateBlock && character.IsGrounded())
{
canCreateBlock = true;
}*/
}
}
| mit | C# |
fc9f39d0cb5ec10903dba933df30694ba3e13150 | Add RegisterExpensesAsync for IExpenseService. | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey.ExpenseServices/IExpenseService.cs | client/BlueMonkey/BlueMonkey.ExpenseServices/IExpenseService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlueMonkey.Business;
namespace BlueMonkey.ExpenseServices
{
public interface IExpenseService
{
Task<IEnumerable<Expense>> GetExpensesAsync();
Task<IEnumerable<Expense>> GetExpensesFromReportIdAsync(string reportId);
Task<IEnumerable<Expense>> GetUnregisteredExpensesAsync();
Task<IEnumerable<Report>> GetReportsAsync();
Task<Report> GetReportAsync(string reportId);
Task RegisterReport(Report report, IEnumerable<Expense> expenses);
Task RegisterExpensesAsync(Expense expense, IEnumerable<ExpenseReceipt> expenseReceipts);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlueMonkey.Business;
namespace BlueMonkey.ExpenseServices
{
public interface IExpenseService
{
Task<IEnumerable<Expense>> GetExpensesAsync();
Task<IEnumerable<Expense>> GetExpensesFromReportIdAsync(string reportId);
Task<IEnumerable<Expense>> GetUnregisteredExpensesAsync();
Task<IEnumerable<Report>> GetReportsAsync();
Task<Report> GetReportAsync(string reportId);
Task RegisterReport(Report report, IEnumerable<Expense> expenses);
}
}
| mit | C# |
82dfbed59bc66276c0669787e976b0190e6f6783 | Revert "chore(Quartz): change scheduler start time (#35)" | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Scheduler/QuartzScheduler.cs | src/StockportWebapp/Scheduler/QuartzScheduler.cs | using System;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using StockportWebapp.FeatureToggling;
using StockportWebapp.Models;
using StockportWebapp.Repositories;
using StockportWebapp.Services;
using StockportWebapp.Utils;
using Microsoft.Extensions.Logging;
namespace StockportWebapp.Scheduler
{
public class QuartzScheduler
{
private readonly ShortUrlRedirects _shortShortUrlRedirects;
private readonly LegacyUrlRedirects _legacyUrlRedirects;
private readonly IRepository _repository;
private readonly ILogger<QuartzJob> _logger;
public QuartzScheduler(ShortUrlRedirects shortShortUrlRedirects, LegacyUrlRedirects legacyUrlRedirects, IRepository repository, ILogger<QuartzJob> logger)
{
_shortShortUrlRedirects = shortShortUrlRedirects;
_legacyUrlRedirects = legacyUrlRedirects;
_repository = repository;
_logger = logger;
}
public async Task Start()
{
var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
await scheduler.Start();
scheduler.JobFactory = new QuartzJobFactory(_shortShortUrlRedirects, _legacyUrlRedirects, _repository, _logger);
var job = JobBuilder.Create<QuartzJob>().Build();
var trigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(RedirectTimeout.RedirectsTimeout)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);
}
}
}
| using System;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using StockportWebapp.FeatureToggling;
using StockportWebapp.Models;
using StockportWebapp.Repositories;
using StockportWebapp.Services;
using StockportWebapp.Utils;
using Microsoft.Extensions.Logging;
namespace StockportWebapp.Scheduler
{
public class QuartzScheduler
{
private readonly ShortUrlRedirects _shortShortUrlRedirects;
private readonly LegacyUrlRedirects _legacyUrlRedirects;
private readonly IRepository _repository;
private readonly ILogger<QuartzJob> _logger;
public QuartzScheduler(ShortUrlRedirects shortShortUrlRedirects, LegacyUrlRedirects legacyUrlRedirects, IRepository repository, ILogger<QuartzJob> logger)
{
_shortShortUrlRedirects = shortShortUrlRedirects;
_legacyUrlRedirects = legacyUrlRedirects;
_repository = repository;
_logger = logger;
}
public async Task Start()
{
var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
await scheduler.Start();
scheduler.JobFactory = new QuartzJobFactory(_shortShortUrlRedirects, _legacyUrlRedirects, _repository, _logger);
var job = JobBuilder.Create<QuartzJob>().Build();
var trigger = TriggerBuilder.Create()
.StartAt(DateTime.Now.AddSeconds(5))
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(RedirectTimeout.RedirectsTimeout)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);
}
}
}
| mit | C# |
a29549389d5ccce13a2989639353674f8856b2a3 | Rename and make the PastaPricer first acceptance test more readable. | dupdob/Michonne,dupdob/Michonne,dupdob/Michonne | PastaPricer.Tests/Acceptance/PastaPricerAcceptanceTests.cs | PastaPricer.Tests/Acceptance/PastaPricerAcceptanceTests.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="PastaPricerAcceptanceTests.cs" company="No lock... no deadlock" product="Michonne">
// Copyright 2014 Cyrille DUPUYDAUBY (@Cyrdup), Thomas PIERRAIN (@tpierrain)
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace PastaPricer.Tests.Acceptance
{
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class PastaPricerAcceptanceTests
{
[Test]
public void Should_Publish_Price_Once_Started_And_When_MarketData_Is_Available()
{
// Mock and dependencies setup
var publisher = Substitute.For<IPastaPricerPublisher>();
var marketDataProvider = new MarketDataProvider();
var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher);
CheckThatNoPriceHasBeenPublished(publisher);
pastaPricer.Start();
CheckThatNoPriceHasBeenPublished(publisher);
// Turns on market data
marketDataProvider.Start();
// It has publish a price now!
publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0);
}
private static void CheckThatNoPriceHasBeenPublished(IPastaPricerPublisher publisher)
{
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="PastaPricerAcceptanceTests.cs" company="No lock... no deadlock" product="Michonne">
// Copyright 2014 Cyrille DUPUYDAUBY (@Cyrdup), Thomas PIERRAIN (@tpierrain)
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace PastaPricer.Tests.Acceptance
{
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class PastaPricerAcceptanceTests
{
[Test]
public void Should_Publish_Pasta_Price_Once_Started_And_When_MarketData_Is_Available()
{
// Mock and dependencies setup
var publisher = Substitute.For<IPastaPricerPublisher>();
var marketDataProvider = new MarketDataProvider();
var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher);
CheckThatNoPriceHasBeenPublished(publisher);
pastaPricer.Start();
CheckThatNoPriceHasBeenPublished(publisher);
// Turns on market data
marketDataProvider.Start();
// It has publish a price now!
publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0);
}
private static void CheckThatNoPriceHasBeenPublished(IPastaPricerPublisher publisher)
{
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
}
}
} | apache-2.0 | C# |
671cbd0e9e60118bc67add465b38ad06ffb45f71 | Comment was in the wrong place | UnityTechnologies/PlaygroundProject,UnityTechnologies/PlaygroundProject | PlaygroundProject/Assets/Scripts/Movement/PickUpAndHold.cs | PlaygroundProject/Assets/Scripts/Movement/PickUpAndHold.cs | using UnityEngine;
public class PickUpAndHold : MonoBehaviour
{
public KeyCode pickUpKey = KeyCode.B;
public KeyCode dropKey = KeyCode.N;
// An object need to closer than this distance to be picked up.
public float pickUpDistance = 1f;
private Transform carriedObject = null;
private int pickupLayer = 0;
private void Update()
{
if( Input.GetKeyDown(pickUpKey) ) // Define it in the input manager
{
if( carriedObject != null )
{
// Do Nothing
}
else
{
// Nothing in hand, we check if something is around and pick it up.
PickUp();
}
}
if (Input.GetKeyDown(dropKey))
{
if( carriedObject != null )
{
// We're holding something already, we drop
Drop();
}
else
{
// Do nothing
}
}
}
private void Drop()
{
carriedObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
// Unparenting
carriedObject.parent = null;
// Hands are free again
carriedObject = null;
}
private void PickUp()
{
// Get the layer bitmask from the layer name
pickupLayer = 1 << LayerMask.NameToLayer( "Pickup" );
// Collect every Pickup around. Make sure they have a collider and the layer Pickup
Collider2D[] pickups = Physics2D.OverlapCircleAll(Utils.GetVector2FromVector3(transform.position), pickUpDistance, pickupLayer );
// Find the closest
float dist = Mathf.Infinity;
for( int i = 0; i < pickups.Length; i++ )
{
float newDist = (transform.position - pickups[i].transform.position).sqrMagnitude;
if( newDist < dist )
{
carriedObject = pickups[i].transform;
dist = newDist;
}
}
// Check if we found something
if( carriedObject != null )
{
// Set the box in front of character
carriedObject.parent = gameObject.transform;
// Set to Kinematic so it will move with the Player
carriedObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
}
}
} | using UnityEngine;
public class PickUpAndHold : MonoBehaviour
{
// An object need to closer than that distance to be picked up.
public KeyCode pickUpKey = KeyCode.B;
public KeyCode dropKey = KeyCode.N;
public float pickUpDistance = 1f;
private Transform carriedObject = null;
private int pickupLayer = 0;
private void Update()
{
if( Input.GetKeyDown(pickUpKey) ) // Define it in the input manager
{
if( carriedObject != null )
{
// Do Nothing
}
else
{
// Nothing in hand, we check if something is around and pick it up.
PickUp();
}
}
if (Input.GetKeyDown(dropKey))
{
if( carriedObject != null )
{
// We're holding something already, we drop
Drop();
}
else
{
// Do nothing
}
}
}
private void Drop()
{
carriedObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
// Unparenting
carriedObject.parent = null;
// Hands are free again
carriedObject = null;
}
private void PickUp()
{
// Get the layer bitmask from the layer name
pickupLayer = 1 << LayerMask.NameToLayer( "Pickup" );
// Collect every Pickup around. Make sure they have a collider and the layer Pickup
Collider2D[] pickups = Physics2D.OverlapCircleAll(Utils.GetVector2FromVector3(transform.position), pickUpDistance, pickupLayer );
// Find the closest
float dist = Mathf.Infinity;
for( int i = 0; i < pickups.Length; i++ )
{
float newDist = (transform.position - pickups[i].transform.position).sqrMagnitude;
if( newDist < dist )
{
carriedObject = pickups[i].transform;
dist = newDist;
}
}
// Check if we found something
if( carriedObject != null )
{
// Set the box in front of character
carriedObject.parent = gameObject.transform;
// Set to Kinematic so it will move with the Player
carriedObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
}
}
} | mit | C# |
23c7132c4fdc452ab2e3b1b7d60fd179f0ea4082 | Add missing license header | peppy/osu,2yangk23/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,ppy/osu,ppy/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu | osu.Game/Rulesets/Objects/PathControlPoint.cs | osu.Game/Rulesets/Objects/PathControlPoint.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Objects.Types;
using osuTK;
namespace osu.Game.Rulesets.Objects
{
public class PathControlPoint : IEquatable<PathControlPoint>
{
/// <summary>
/// The position of this <see cref="PathControlPoint"/>.
/// </summary>
public readonly Bindable<Vector2> Position = new Bindable<Vector2>();
/// <summary>
/// The type of path segment starting at this <see cref="PathControlPoint"/>.
/// If null, this <see cref="PathControlPoint"/> will be a part of the previous path segment.
/// </summary>
public readonly Bindable<PathType?> Type = new Bindable<PathType?>();
/// <summary>
/// Invoked when any property of this <see cref="PathControlPoint"/> is changed.
/// </summary>
internal event Action Changed;
public PathControlPoint()
{
Position.ValueChanged += _ => Changed?.Invoke();
Type.ValueChanged += _ => Changed?.Invoke();
}
public bool Equals(PathControlPoint other) => Position.Value == other.Position.Value && Type.Value == other.Type.Value;
}
}
| using System;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Objects.Types;
using osuTK;
namespace osu.Game.Rulesets.Objects
{
public class PathControlPoint : IEquatable<PathControlPoint>
{
/// <summary>
/// The position of this <see cref="PathControlPoint"/>.
/// </summary>
public readonly Bindable<Vector2> Position = new Bindable<Vector2>();
/// <summary>
/// The type of path segment starting at this <see cref="PathControlPoint"/>.
/// If null, this <see cref="PathControlPoint"/> will be a part of the previous path segment.
/// </summary>
public readonly Bindable<PathType?> Type = new Bindable<PathType?>();
/// <summary>
/// Invoked when any property of this <see cref="PathControlPoint"/> is changed.
/// </summary>
internal event Action Changed;
public PathControlPoint()
{
Position.ValueChanged += _ => Changed?.Invoke();
Type.ValueChanged += _ => Changed?.Invoke();
}
public bool Equals(PathControlPoint other) => Position.Value == other.Position.Value && Type.Value == other.Type.Value;
}
}
| mit | C# |
6ba1bc381c07d68d7af35d3e631dbe6cac7b9b93 | Add version value to the DefaultSkinConfiguration dictionary | NeoAdonis/osu,peppy/osu-new,ppy/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu | osu.Game/Skinning/DefaultSkinConfiguration.cs | osu.Game/Skinning/DefaultSkinConfiguration.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 osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// A skin configuration pre-populated with sane defaults.
/// </summary>
public class DefaultSkinConfiguration : SkinConfiguration
{
public DefaultSkinConfiguration()
{
ComboColours.AddRange(new[]
{
new Color4(17, 136, 170, 255),
new Color4(102, 136, 0, 255),
new Color4(204, 102, 0, 255),
new Color4(121, 9, 13, 255)
});
ConfigDictionary.Add(@"Version", "latest");
}
}
}
| // 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 osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// A skin configuration pre-populated with sane defaults.
/// </summary>
public class DefaultSkinConfiguration : SkinConfiguration
{
public DefaultSkinConfiguration()
{
ComboColours.AddRange(new[]
{
new Color4(17, 136, 170, 255),
new Color4(102, 136, 0, 255),
new Color4(204, 102, 0, 255),
new Color4(121, 9, 13, 255)
});
}
}
}
| mit | C# |
dd8a338ce7704079594b1762e02b08e28f7e24ee | Bump version to 0.1.0.1 | nicolaiarocci/Eve.NET | Eve.NET/Properties/AssemblyInfo.cs | Eve.NET/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Eve.NET")]
[assembly: AssemblyDescription("Simple portable HTTP and REST Client for Humans™")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicola Iarocci")]
[assembly: AssemblyProduct("Eve.NET")]
[assembly: AssemblyCopyright("Copyright © Nicola Iarocci and CIR2000 - 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.1")]
[assembly: AssemblyFileVersion("0.1.0.1")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Eve.NET")]
[assembly: AssemblyDescription("Simple portable HTTP and REST Client for Humans™")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicola Iarocci")]
[assembly: AssemblyProduct("Eve.NET")]
[assembly: AssemblyCopyright("Copyright © Nicola Iarocci and CIR2000 - 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| bsd-3-clause | C# |
5506f26d22cde3ce168dfbfd8d163ab52685549b | Fix sleep time | isudzumi/playSound | playSound/CommonFunction.cs | playSound/CommonFunction.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace playSound
{
public static class CommonFunction
{
private const Int32 SLEEP_TIME = 1800000;
public static DateTime playTime { get; set; } = DateTime.Now;
public static string FileName { get; set; } = "";
public static System.Media.SoundPlayer playSound = null;
private static void LoadWavFile()
{
if (FileName == "")
{
string currentDirectory = Directory.GetCurrentDirectory();
var dir = new DirectoryInfo(currentDirectory);
var wavFiles = dir.EnumerateFiles("*.wav", SearchOption.AllDirectories);
var wavFile = wavFiles.First();
FileName = wavFile.FullName;
}
}
public static void PlayAudioFile()
{
if (FileName != "")
{
playSound = new System.Media.SoundPlayer(FileName);
playSound.Play();
}
}
public static void StopAudioFile()
{
if (playSound != null)
{
playSound.Stop();
playSound.Dispose();
playSound = null;
}
}
public static async Task<bool> PlayAudioAsync()
{
LoadWavFile();
for (int i = 0; i < 3; i++)
{
await Task.Run(() => {
PlayAudioFile();
if (i < 2)
{
Thread.Sleep(SLEEP_TIME);
}
});
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace playSound
{
public static class CommonFunction
{
private const Int32 SLEEP_TIME = 240000;//1800000;
public static DateTime playTime { get; set; } = DateTime.Now;
public static string FileName { get; set; } = "";
public static System.Media.SoundPlayer playSound = null;
private static void LoadWavFile()
{
if (FileName == "")
{
string currentDirectory = Directory.GetCurrentDirectory();
var dir = new DirectoryInfo(currentDirectory);
var wavFiles = dir.EnumerateFiles("*.wav", SearchOption.AllDirectories);
var wavFile = wavFiles.First();
FileName = wavFile.FullName;
}
}
public static void PlayAudioFile()
{
if (FileName != "")
{
playSound = new System.Media.SoundPlayer(FileName);
playSound.Play();
}
}
public static void StopAudioFile()
{
if (playSound != null)
{
playSound.Stop();
playSound.Dispose();
playSound = null;
}
}
public static async Task<bool> PlayAudioAsync()
{
LoadWavFile();
for (int i = 0; i < 3; i++)
{
await Task.Run(() => {
PlayAudioFile();
if (i < 2)
{
Thread.Sleep(SLEEP_TIME);
}
});
}
return true;
}
}
}
| mit | C# |
887efa6bcfaae0dd052004ae87f7b458a041c189 | Fix camera flicker. | adurdin/ggj2015 | Alcove/Assets/Player/FollowCursor.cs | Alcove/Assets/Player/FollowCursor.cs | using UnityEngine;
using System.Collections;
public class FollowCursor : MonoBehaviour {
new private Camera camera;
private Transform cameraTransform;
public Transform cursorTransform;
public const float viewportMargin = 0.05f;
public void Start () {
camera = GetComponent<Camera>();
cameraTransform = camera.transform;
}
public void LateUpdate () {
Vector3 cameraPosition = cameraTransform.position;
Vector3 cursorPosition = cursorTransform.position;
// Find the min world space X and Y for the cursor that will keep it inside the viewport margin.
const float halfCursorHeight = 1.0f;
Vector3 cursorBottom = camera.WorldToViewportPoint(cursorPosition + Vector3.down * halfCursorHeight);
Vector3 cursorTop = camera.WorldToViewportPoint(cursorPosition + Vector3.up * halfCursorHeight);
cursorBottom.y = Mathf.Clamp(cursorBottom.y, viewportMargin, 1.0f - viewportMargin);
cursorBottom.z = -cameraPosition.z;
cursorTop.y = Mathf.Clamp(cursorTop.y, viewportMargin, 1.0f - viewportMargin);
cursorTop.z = -cameraPosition.z;
float minY = camera.ViewportToWorldPoint(cursorBottom).y;
float maxY = camera.ViewportToWorldPoint(cursorTop).y;
// Lerp the camera to the desired position if possible, yet clamp to ensure it is always on screen.
Vector3 idealCameraPosition = new Vector3(cursorPosition.x, cursorPosition.y, cameraPosition.z);
Vector3 lerpedCameraPosition = Vector3.Lerp(cameraPosition, idealCameraPosition, Time.deltaTime);
lerpedCameraPosition.y = Mathf.Clamp(lerpedCameraPosition.y, minY, maxY);
// Force the camera to never go too low
lerpedCameraPosition.y = Mathf.Max(lerpedCameraPosition.y, 3.5f);
camera.transform.position = lerpedCameraPosition;
}
}
| using UnityEngine;
using System.Collections;
public class FollowCursor : MonoBehaviour {
new private Camera camera;
private Transform cameraTransform;
public Transform cursorTransform;
public const float viewportMargin = 0.05f;
public void Start () {
camera = GetComponent<Camera>();
cameraTransform = camera.transform;
}
public void Update () {
Vector3 cameraPosition = cameraTransform.position;
Vector3 cursorPosition = cursorTransform.position;
// Find the min world space X and Y for the cursor that will keep it inside the viewport margin.
const float halfCursorHeight = 1.0f;
Vector3 cursorBottom = camera.WorldToViewportPoint(cursorPosition + Vector3.down * halfCursorHeight);
Vector3 cursorTop = camera.WorldToViewportPoint(cursorPosition + Vector3.up * halfCursorHeight);
cursorBottom.y = Mathf.Clamp(cursorBottom.y, viewportMargin, 1.0f - viewportMargin);
cursorBottom.z = -cameraPosition.z;
cursorTop.y = Mathf.Clamp(cursorTop.y, viewportMargin, 1.0f - viewportMargin);
cursorTop.z = -cameraPosition.z;
float minY = camera.ViewportToWorldPoint(cursorBottom).y;
float maxY = camera.ViewportToWorldPoint(cursorTop).y;
minY = Mathf.Max(minY, 3.5f);
// Lerp the camera to the desired position if possible, yet clamp to ensure it is always on screen.
Vector3 idealCameraPosition = new Vector3(cursorPosition.x, cursorPosition.y, cameraPosition.z);
Vector3 lerpedCameraPosition = Vector3.Lerp(cameraPosition, idealCameraPosition, Time.deltaTime);
lerpedCameraPosition.y = Mathf.Clamp(lerpedCameraPosition.y, minY, maxY);
camera.transform.position = lerpedCameraPosition;
}
}
| mit | C# |
1a8cc0f9234bda02d10b64822d9ecab6013b8319 | Range function: added yield versions. More checks are also done and it now throws exceptions if one arg is incorrect | julsam/VineScript | VineScript/Utils.cs | VineScript/Utils.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VineScript.Core;
namespace VineScript
{
public class Utils
{
public static List<int> Range(int stop)
{
return Range(0, stop);
}
public static List<int> Range(int start, int stop)
{
var list = new List<int>();
foreach (int i in YieldRange(start, stop)) {
list.Add(i);
}
return list;
}
public static List<int> Range(int start, int stop, int step)
{
var list = new List<int>();
foreach (int i in YieldRange(start, stop, step)) {
list.Add(i);
}
return list;
}
public static IEnumerable<int> YieldRange(int end)
{
return YieldRange(0, end);
}
public static IEnumerable<int> YieldRange(int start, int stop)
{
if (start < stop) {
return YieldRange(start, stop, 1);
} else {
return YieldRange(start, stop, -1);
}
}
public static IEnumerable<int> YieldRange(int start, int stop, int step)
{
if (step == 0) {
throw new ArgumentOutOfRangeException("step can't be equal to 0");
}
if (start < stop)
{
if (step < 0) {
throw new ArgumentOutOfRangeException(
"step can't be inferior to 0 when start < stop"
);
}
for (int i = start; i < stop; i += step) {
yield return i;
}
}
else if (start > stop)
{
if (step > 0) {
throw new ArgumentOutOfRangeException(
"step can't be superior to 0 when start > stop"
);
}
for (int i = start; i > stop; i += step) {
yield return i;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VineScript.Core;
namespace VineScript
{
class Utils
{
public static List<int> Range(int end)
{
return Range(0, end);
}
public static List<int> Range(int start, int end, int steps=1)
{
var range = new List<int>();
var step = 1;
if (start > end)
{
var i = start;
while (i > end) {
range.Add(i);
i -= step;
}
}
else
{
var i = start;
while (i < end) {
range.Add(i);
i += step;
}
}
return range;
}
}
}
| mit | C# |
280d83449abc6bbedc6da4ea5284c49901b3e661 | Add Load Project Test | geaz/coreDox,geaz/coreDox,geaz/coreDox | tests/coreDox.Core.Tests/Project/ProjectTests.cs | tests/coreDox.Core.Tests/Project/ProjectTests.cs | using coreDox.Core.Project;
using coreDox.Core.Project.Config;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace coreDox.Core.Tests.Projects
{
[TestClass]
public class ProjectTests
{
private string _tmpPath = Path.Combine(Path.GetTempPath(), "testProject");
[TestCleanup]
public void TestCleanUp()
{
if(Directory.Exists(_tmpPath)) Directory.Delete(_tmpPath, true);
}
[TestMethod]
public void ShouldCreateDefaultProjectSuccessfully()
{
//Arrange
var project = new DoxProject();
//Act
project.Create(_tmpPath);
//Assert
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.AssetFolderName)));
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.LayoutFolderName)));
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.PagesFolderName)));
Assert.IsTrue(File.Exists(Path.Combine(_tmpPath, DoxProjectConfig.ConfigFileName)));
}
[TestMethod]
public void ShouldLoadProjectSuccessfully()
{
//Arrange
var project = new DoxProject();
var projectPath = Path.Combine(
Path.GetDirectoryName(typeof(ProjectTests).Assembly.Location),
"..", "..", "..", "..", "..", "doc", "testDoc");
//Act
project.Load(projectPath);
//Assert
Assert.IsTrue(project.RootProjectDirectory.Exists);
}
}
}
| using coreDox.Core.Project;
using coreDox.Core.Project.Config;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace coreDox.Core.Tests.Projects
{
[TestClass]
public class ProjectTests
{
private string _tmpPath = Path.Combine(Path.GetTempPath(), "testProject");
[TestCleanup]
public void TestCleanUp()
{
if(Directory.Exists(_tmpPath)) Directory.Delete(_tmpPath, true);
}
[TestMethod]
public void ShouldCreateDefaultProjectSuccessfully()
{
//Arrange
var project = new DoxProject();
//Act
project.Create(_tmpPath);
//Assert
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.AssetFolderName)));
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.LayoutFolderName)));
Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.PagesFolderName)));
Assert.IsTrue(File.Exists(Path.Combine(_tmpPath, DoxProjectConfig.ConfigFileName)));
}
}
}
| mit | C# |
1c89aeb602695c98f6a71b479bdbdfe01af83b62 | Update Tests to reflect attribute move | simo9000/Consola,simo9000/Consola,simo9000/Consola | Consola.Tests/Scriptables/Progeny.cs | Consola.Tests/Scriptables/Progeny.cs | using Consola.Library;
using Consola.Library.util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Scriptables
{
public class Progeny : Scriptable
{
[Description("Simple Name Field")]
public string Name { get; set; }
}
}
| using Consola.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Scriptables
{
public class Progeny : Scriptable
{
[Description("Simple Name Field")]
public string Name { get; set; }
}
}
| mit | C# |
52be0d5af887be80a9793dead235522004e72268 | Set thread count to 1 in kestrel options. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Program.cs | src/CompetitionPlatform/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace CompetitionPlatform
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel(opts => opts.ThreadCount = 1)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace CompetitionPlatform
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| mit | C# |
820089abc29a655fe459f219a373021d6e554ca2 | Remove whitespace | MindscapeHQ/NLog.Raygun,MindscapeHQ/NLog.Raygun,MindscapeHQ/NLog.Raygun | src/NLog.Raygun/RaygunException.cs | src/NLog.Raygun/RaygunException.cs | using System;
namespace NLog.Raygun
{
public class RaygunException : Exception
{
public RaygunException(string message)
: base(message)
{
}
public RaygunException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | using System;
namespace NLog.Raygun
{
public class RaygunException : Exception
{
public RaygunException(string message)
: base(message)
{
}
public RaygunException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | mit | C# |
1c597534c5d0275965cd841dff344fdd416ef03a | Bump version | kamil-mrzyglod/Oxygenize | Oxygenize/Properties/AssemblyInfo.cs | Oxygenize/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("Oxygenize")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Oxygenize")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("78a5cd71-2e0f-47a3-b553-d7109704dfe5")]
// 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.6.0")]
[assembly: AssemblyFileVersion("1.0.6.0")]
[assembly: InternalsVisibleTo("Oxygenize.Test")] | 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("Oxygenize")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Oxygenize")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("78a5cd71-2e0f-47a3-b553-d7109704dfe5")]
// 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.5.0")]
[assembly: AssemblyFileVersion("1.0.5.0")]
[assembly: InternalsVisibleTo("Oxygenize.Test")] | mit | C# |
b03d6914cfc6d0e81d5deeb61eac472f91c689fd | test git3-v1 | emksaz/testgit2,emksaz/testgit2,emksaz/testgit2 | testgit23/testgit23/Views/Home/Index.cshtml | testgit23/testgit23/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="jumbotron">
<h1>ASP.NET -david.z 1655</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</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>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</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>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="jumbotron">
<h1>ASP.NET -david.z</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</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>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</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>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</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# |
e9cb628f820ba7226cce379a601b9867053eef76 | Improve formatting | SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia | src/Avalonia.Controls/Converters/CornerRadiusFilterConverter.cs | src/Avalonia.Controls/Converters/CornerRadiusFilterConverter.cs | using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace Avalonia.Controls.Converters
{
/// <summary>
/// Converts an existing CornerRadius struct to a new CornerRadius struct,
/// with filters applied to extract only the specified corners, leaving the others set to 0.
/// </summary>
public class CornerRadiusFilterConverter : IValueConverter
{
/// <summary>
/// Gets or sets the corners to filter by.
/// Only the specified corners will be included in the converted <see cref="CornerRadius"/>.
/// </summary>
public Corners Filter { get; set; }
/// <summary>
/// Gets or sets the scale multiplier applied uniformly to each corner.
/// </summary>
public double Scale { get; set; } = 1;
/// <inheritdoc/>
public object? Convert(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
if (!(value is CornerRadius radius))
{
return value;
}
return new CornerRadius(
Filter.HasAllFlags(Corners.TopLeft) ? radius.TopLeft * Scale : 0,
Filter.HasAllFlags(Corners.TopRight) ? radius.TopRight * Scale : 0,
Filter.HasAllFlags(Corners.BottomRight) ? radius.BottomRight * Scale : 0,
Filter.HasAllFlags(Corners.BottomLeft) ? radius.BottomLeft * Scale : 0);
}
/// <inheritdoc/>
public object? ConvertBack(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace Avalonia.Controls.Converters
{
/// <summary>
/// Converts an existing CornerRadius struct to a new CornerRadius struct,
/// with filters applied to extract only the specified corners, leaving the others set to 0.
/// </summary>
public class CornerRadiusFilterConverter : IValueConverter
{
/// <summary>
/// Gets or sets the corners to filter by.
/// Only the specified corners will be included in the converted <see cref="CornerRadius"/>.
/// </summary>
public Corners Filter { get; set; }
/// <summary>
/// Gets or sets the scale multiplier applied uniformly to each corner.
/// </summary>
public double Scale { get; set; } = 1;
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (!(value is CornerRadius radius))
{
return value;
}
return new CornerRadius(
Filter.HasAllFlags(Corners.TopLeft) ? radius.TopLeft * Scale : 0,
Filter.HasAllFlags(Corners.TopRight) ? radius.TopRight * Scale : 0,
Filter.HasAllFlags(Corners.BottomRight) ? radius.BottomRight * Scale : 0,
Filter.HasAllFlags(Corners.BottomLeft) ? radius.BottomLeft * Scale : 0);
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
cb34a0e28073a71294b3e851376075e730d82383 | Fix unique control name for WPF | blebougge/Catel | src/Catel.MVVM/Catel.MVVM.Shared/Extensions/StringExtensions.cs | src/Catel.MVVM/Catel.MVVM.Shared/Extensions/StringExtensions.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StringExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel
{
using System;
/// <summary>
/// String extensions.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Gets the a unique name for a control. This is sometimes required in some frameworks.
/// <para />
/// The name is made unique by appending a unique guid.
/// </summary>
/// <param name="controlName">Name of the control.</param>
/// <returns>System.String.</returns>
public static string GetUniqueControlName(this string controlName)
{
var random = Guid.NewGuid().ToString();
random = random.Replace("-", string.Empty);
var name = string.Format("{0}_{1}", controlName, random);
return name;
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StringExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel
{
using System;
/// <summary>
/// String extensions.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Gets the a unique name for a control. This is sometimes required in some frameworks.
/// <para />
/// The name is made unique by appending a unique guid.
/// </summary>
/// <param name="controlName">Name of the control.</param>
/// <returns>System.String.</returns>
public static string GetUniqueControlName(this string controlName)
{
var name = string.Format("{0}_{1}", controlName, Guid.NewGuid());
return name;
}
}
} | mit | C# |
43daa7c7c09463acac11095bc93f304e1c20ae83 | Use `Colour2` of orange theme for explicit pill | NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game/Overlays/BeatmapSet/ExplicitBeatmapPill.cs | osu.Game/Overlays/BeatmapSet/ExplicitBeatmapPill.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Overlays.BeatmapSet
{
public class ExplicitBeatmapPill : CompositeDrawable
{
public ExplicitBeatmapPill()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(true)]
private void load(OsuColour colours, OverlayColourProvider colourProvider)
{
InternalChild = new CircularContainer
{
Masking = true,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider?.Background5 ?? colours.Gray2,
},
new OsuSpriteText
{
Margin = new MarginPadding { Horizontal = 10f, Vertical = 2f },
Text = "EXPLICIT",
Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold),
Colour = OverlayColourProvider.Orange.Colour2,
}
}
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.BeatmapSet
{
public class ExplicitBeatmapPill : CompositeDrawable
{
public ExplicitBeatmapPill()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(true)]
private void load(OsuColour colours, OverlayColourProvider colourProvider)
{
InternalChild = new CircularContainer
{
Masking = true,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider?.Background5 ?? colours.Gray2,
},
new OsuSpriteText
{
Margin = new MarginPadding { Horizontal = 10f, Vertical = 2f },
Text = "EXPLICIT",
Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold),
// todo: this is --hsl-orange-2 from the new palette in https://github.com/ppy/osu-web/blob/8ceb46f/resources/assets/less/colors.less#L128-L151,
// should probably take the whole palette from there onto OsuColour for a nicer look in code.
Colour = Color4.FromHsl(new Vector4(45f / 360, 0.8f, 0.6f, 1f)),
}
}
};
}
}
}
| mit | C# |
92347692d45ecd52e1698d7fac01a3cdcd612983 | Implement timer functionality | eightlittlebits/elbgb | elbgb.gameboy/Timer.cs | elbgb.gameboy/Timer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy
{
class Timer : ClockedComponent
{
public static class Registers
{
public const ushort DIV = 0xFF04;
public const ushort TIMA = 0xFF05;
public const ushort TMA = 0xFF06;
public const ushort TAC = 0xFF07;
}
// divider
private ushort _divider;
// timer
private bool _timerEnabled;
private uint _timerInterval;
private uint _timerCounter;
private byte _tima, _tma, _tac;
public Timer(GameBoy gameBoy)
: base(gameBoy)
{
}
public byte ReadByte(ushort address)
{
SynchroniseWithSystemClock();
switch (address)
{
// the divider is the upper 8 bits of the 16-bit counter that counts the
// basic clock frequency (f). f = 4.194304 MHz
case Registers.DIV: return (byte)(_divider >> 8);
// timer counter
case Registers.TIMA:
return _tima;
// timer modulo
case Registers.TMA:
return _tma;
// timer controller
case Registers.TAC:
return (byte)(_tac & 0x07);
default:
throw new ArgumentOutOfRangeException("address");
}
}
public void WriteByte(ushort address, byte value)
{
SynchroniseWithSystemClock();
switch (address)
{
// a write always clears the upper 8 bits of DIV, regardless of value
case Registers.DIV: _divider &= 0x00FF; break;
// timer counter
case Registers.TIMA:
_tima = value; break;
// timer modulo
case Registers.TMA:
_tma = value; break;
// timer controller
case Registers.TAC:
_tac = (byte)(value & 0x07);
// update enabled state from bit 2
_timerEnabled = (value & 0x04) == 0x04;
// bits 0/1 specify timer frequency, set interval
switch (value & 0x03)
{
// 00 - f/2^10 (4.096 KHz)
case 0x00: _timerInterval = SystemClock.ClockFrequency / 1024; break;
// 01 - f/2^4 (262.144 KHz)
case 0x01: _timerInterval = SystemClock.ClockFrequency / 16; break;
// 10 - f/2^6 (65.436 KHz)
case 0x10: _timerInterval = SystemClock.ClockFrequency / 64; break;
// 11 - f/2^8 (16.384 KHz)
case 0x11: _timerInterval = SystemClock.ClockFrequency / 256; break;
}
break;
default:
throw new ArgumentOutOfRangeException("address");
}
}
public override void Update(ulong cycleCount)
{
UpdateDivider(cycleCount);
UpdateTimer(cycleCount);
}
private void UpdateDivider(ulong cycleCount)
{
_divider += (ushort)cycleCount;
}
private void UpdateTimer(ulong cycleCount)
{
if (_timerEnabled)
{
_timerCounter += (uint)cycleCount;
while (_timerCounter >= _timerInterval)
{
_tima++;
_timerCounter -= _timerInterval;
if (_tima == 0)
{
_tima = _tma;
// TODO(david): request timer overflow interrupt
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy
{
class Timer : ClockedComponent
{
public static class Registers
{
public const ushort DIV = 0xFF04;
public const ushort TIMA = 0xFF05;
public const ushort TMA = 0xFF06;
public const ushort TAC = 0xFF07;
}
private ushort _div;
public Timer(GameBoy gameBoy)
: base(gameBoy)
{
}
public byte ReadByte(ushort address)
{
SynchroniseWithSystemClock();
switch (address)
{
case Registers.DIV: return (byte)(_div >> 8);
default:
throw new ArgumentOutOfRangeException("address");
}
}
public void WriteByte(ushort address, byte value)
{
SynchroniseWithSystemClock();
switch (address)
{
// a write always clears the upper 8 bits of DIV, regardless of value
case Registers.DIV: _div &= 0x00FF; break;
default:
throw new ArgumentOutOfRangeException("address");
}
}
public override void Update(ulong cycleCount)
{
UpdateDivider(cycleCount);
}
private void UpdateDivider(ulong cycleCount)
{
_div += (ushort)cycleCount;
}
}
}
| mit | C# |
8d81ccaf00133736e2a1c361b74131643d9a0495 | make some easy tests green first | ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian | src/Obsidian.Persistence/Repositories/PermissionScopeMongoRepository.cs | src/Obsidian.Persistence/Repositories/PermissionScopeMongoRepository.cs | using Obsidian.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Obsidian.Domain;
using MongoDB.Driver;
namespace Obsidian.Persistence.Repositories
{
public class PermissionScopeMongoRepository : IPermissionScopeRepository
{
private readonly IMongoCollection<PermissionScope> _collection;
public PermissionScopeMongoRepository(IMongoDatabase database)
{
_collection = database.GetCollection<PermissionScope>("PermissionScope");
}
public Task AddAsync(PermissionScope aggregate)
{
if (aggregate == null) throw new ArgumentNullException(nameof(aggregate));
if (aggregate.Id == Guid.Empty) throw new ArgumentException("", nameof(aggregate));
if (_collection.Find(s => s.Id == aggregate.Id).SingleOrDefault() != null) throw new InvalidOperationException();
return _collection.InsertOneAsync(aggregate);
}
public Task DeleteAsync(PermissionScope aggregate)
{
if (aggregate == null) throw new ArgumentNullException(nameof(aggregate));
if (aggregate.Id == Guid.Empty) throw new ArgumentException("", nameof(aggregate));
return _collection.DeleteOneAsync(s => s.Id == aggregate.Id);
}
public Task<PermissionScope> FindByIdAsync(Guid id)
{
if (id == Guid.Empty) throw new ArgumentNullException(nameof(id));
return _collection.Find(s => s.Id == id).SingleOrDefaultAsync();
}
public Task<PermissionScope> FindByScopeNameAsync(string scopeName)
{
if (string.IsNullOrWhiteSpace(scopeName)) throw new ArgumentNullException(nameof(scopeName));
return _collection.Find(s => s.ScopeName == scopeName).SingleOrDefaultAsync();
}
public Task<IQueryable<PermissionScope>> QueryAllAsync() => Task.FromResult<IQueryable<PermissionScope>>(_collection.AsQueryable());
public Task SaveAsync(PermissionScope aggregate)
{
if (aggregate == null) throw new ArgumentNullException(nameof(aggregate));
if (aggregate.Id == Guid.Empty) throw new ArgumentException("", nameof(aggregate));
if (_collection.Find(s => s.Id == aggregate.Id).SingleOrDefault() == null) throw new InvalidOperationException();
return _collection.ReplaceOneAsync(s => s.Id == aggregate.Id, aggregate);
}
}
}
| using Obsidian.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Obsidian.Domain;
using MongoDB.Driver;
namespace Obsidian.Persistence.Repositories
{
public class PermissionScopeMongoRepository : IPermissionScopeRepository
{
public PermissionScopeMongoRepository(IMongoDatabase database)
{
}
public Task AddAsync(PermissionScope aggregate)
{
throw new NotImplementedException();
}
public Task DeleteAsync(PermissionScope aggregate)
{
throw new NotImplementedException();
}
public Task<PermissionScope> FindByIdAsync(Guid id)
{
throw new NotImplementedException();
}
public Task<PermissionScope> FindByScopeNameAsync(string scopeName)
{
throw new NotImplementedException();
}
public Task<IQueryable<PermissionScope>> QueryAllAsync()
{
throw new NotImplementedException();
}
public Task SaveAsync(PermissionScope aggregate)
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
3603aab4abed866204bd4c08c40f495240a77cd7 | Add admin menu item for events #1899 | HTBox/allReady,BillWagner/allReady,binaryjanitor/allReady,BillWagner/allReady,stevejgordon/allReady,dpaquette/allReady,stevejgordon/allReady,HamidMosalla/allReady,HTBox/allReady,c0g1t8/allReady,stevejgordon/allReady,dpaquette/allReady,HamidMosalla/allReady,mgmccarthy/allReady,HTBox/allReady,dpaquette/allReady,binaryjanitor/allReady,gitChuckD/allReady,stevejgordon/allReady,gitChuckD/allReady,BillWagner/allReady,HTBox/allReady,mgmccarthy/allReady,HamidMosalla/allReady,c0g1t8/allReady,gitChuckD/allReady,HamidMosalla/allReady,c0g1t8/allReady,BillWagner/allReady,c0g1t8/allReady,gitChuckD/allReady,binaryjanitor/allReady,mgmccarthy/allReady,mgmccarthy/allReady,binaryjanitor/allReady,dpaquette/allReady | AllReadyApp/Web-App/AllReady/Views/Shared/_AdminNavigationPartial.cshtml | AllReadyApp/Web-App/AllReady/Views/Shared/_AdminNavigationPartial.cshtml | @using AllReady.Constants
@using AllReady.Security
@if (User.IsUserType(UserType.SiteAdmin) || User.IsUserType(UserType.OrgAdmin))
{
//var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor;
//var areaName = descriptor.RouteValues["area"]; // there must be a better way to get the area name!
//var controllerName = descriptor.ControllerName;
//var isAdmin = areaName == AreaNames.Admin;
<li class="dropdown dropdown-admin">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Admin <span class="caret"></span>
</a>
<ul class="dropdown-menu">
@if (User.IsUserType(UserType.SiteAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="Organization" asp-action="Index">Organizations</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Campaign" asp-action="Index">Campaigns</a></li>
@if (User.IsUserType(UserType.OrgAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="UnlinkedRequest" asp-action="List">Unlinked Requests</a></li>
<li><a asp-area="Admin" asp-controller="Invite" asp-action="Index">Invites</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Event" asp-action="Lister">Events</a></li>
<li><a asp-area="@AreaNames.Admin" asp-controller="Skill" asp-action="Index">Skills</a></li>
@if (User.IsUserType(UserType.SiteAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="Site" asp-action="Index">Site Admin</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Import" asp-action="Index">Import Data</a></li>
</ul>
</li>
}
| @using AllReady.Constants
@using AllReady.Security
@if (User.IsUserType(UserType.SiteAdmin) || User.IsUserType(UserType.OrgAdmin))
{
//var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor;
//var areaName = descriptor.RouteValues["area"]; // there must be a better way to get the area name!
//var controllerName = descriptor.ControllerName;
//var isAdmin = areaName == AreaNames.Admin;
<li class="dropdown dropdown-admin">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Admin <span class="caret"></span>
</a>
<ul class="dropdown-menu">
@if (User.IsUserType(UserType.SiteAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="Organization" asp-action="Index">Organizations</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Campaign" asp-action="Index">Campaigns</a></li>
@if (User.IsUserType(UserType.OrgAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="UnlinkedRequest" asp-action="List">Unlinked Requests</a></li>
<li><a asp-area="Admin" asp-controller="Invite" asp-action="Index">Invites</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Skill" asp-action="Index">Skills</a></li>
@if (User.IsUserType(UserType.SiteAdmin))
{
<li><a asp-area="@AreaNames.Admin" asp-controller="Site" asp-action="Index">Site Admin</a></li>
}
<li><a asp-area="@AreaNames.Admin" asp-controller="Import" asp-action="Index">Import Data</a></li>
</ul>
</li>
}
| mit | C# |
fca6abd7af50ef27f879e226f8bc5fdf1ea49dd8 | Use ExceptionMessageResult (ErrorMEssageResult instead?) | dotJEM/web-host,dotJEM/web-host,dotJEM/web-host | DotJEM.Web.Host/Diagnostics/ExceptionHandlers/WebHostExceptionHandler.cs | DotJEM.Web.Host/Diagnostics/ExceptionHandlers/WebHostExceptionHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Results;
using DotJEM.Web.Host.Providers.Pipeline;
namespace DotJEM.Web.Host.Diagnostics.ExceptionHandlers
{
public class WebHostExceptionHandler : ExceptionHandler
{
private readonly Dictionary<Type, IWebHostExceptionHandler> map;
public event EventHandler<WebHostUnhandledExceptionArgs> UnhandledException;
public WebHostExceptionHandler(IWebHostExceptionHandler[] handlers)
{
map = handlers.ToDictionary(handler => handler.ExceptionType);
}
private IWebHostExceptionHandler LookupHandler(Type exceptionType)
{
IWebHostExceptionHandler handler;
if (map.TryGetValue(exceptionType, out handler))
return handler;
return exceptionType != typeof(Exception)
? LookupHandler(exceptionType.BaseType)
: null;
}
private IHttpActionResult ByHandlers(ExceptionHandlerContext context)
{
IWebHostExceptionHandler handler = LookupHandler(context.Exception.GetType());
return handler != null ? handler.Handle(context) : null;
}
private IHttpActionResult ByDefault(ExceptionHandlerContext context)
{
HttpResponseMessage message = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError,context.Exception.Message, context.Exception);
return new ExceptionMessageResult(message);
}
private IHttpActionResult ByEvent(ExceptionHandlerContext context)
{
WebHostUnhandledExceptionArgs args = OnUnhandledException(new WebHostUnhandledExceptionArgs(context));
return args.Result;
}
public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
context.Result = ByHandlers(context) ?? ByEvent(context) ?? ByDefault(context);
}, cancellationToken);
}
private WebHostUnhandledExceptionArgs OnUnhandledException(WebHostUnhandledExceptionArgs args)
{
var handler = UnhandledException;
if (handler != null)
{
handler(this, args);
}
return args;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using DotJEM.Web.Host.Providers.Pipeline;
namespace DotJEM.Web.Host.Diagnostics.ExceptionHandlers
{
public class WebHostExceptionHandler : ExceptionHandler
{
private readonly Dictionary<Type, IWebHostExceptionHandler> map;
public event EventHandler<WebHostUnhandledExceptionArgs> UnhandledException;
public WebHostExceptionHandler(IWebHostExceptionHandler[] handlers)
{
map = handlers.ToDictionary(handler => handler.ExceptionType);
}
private IWebHostExceptionHandler LookupHandler(Type exceptionType)
{
IWebHostExceptionHandler handler;
if (map.TryGetValue(exceptionType, out handler))
return handler;
return exceptionType != typeof(Exception)
? LookupHandler(exceptionType.BaseType)
: null;
}
private IHttpActionResult ByHandlers(ExceptionHandlerContext context)
{
IWebHostExceptionHandler handler = LookupHandler(context.Exception.GetType());
return handler != null ? handler.Handle(context) : null;
}
private IHttpActionResult ByDefault(ExceptionHandlerContext context)
{
HttpResponseMessage message = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception);
return new ExceptionMessageResult(message);
}
private IHttpActionResult ByEvent(ExceptionHandlerContext context)
{
WebHostUnhandledExceptionArgs args = OnUnhandledException(new WebHostUnhandledExceptionArgs(context));
return args.Result;
}
public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
context.Result = ByHandlers(context) ?? ByEvent(context) ?? ByDefault(context);
}, cancellationToken);
}
private WebHostUnhandledExceptionArgs OnUnhandledException(WebHostUnhandledExceptionArgs args)
{
var handler = UnhandledException;
if (handler != null)
{
handler(this, args);
}
return args;
}
}
}
| mit | C# |
3a7310094e91eb87e56e45a0e6324b63bcb612e4 | Add exemplo de botao | IgorFachini/Projeto01_TDP2,IgorFachini/Projeto01_TDP2,IgorFachini/Projeto01_TDP2 | Supermercado/Views/Home/About.cshtml | Supermercado/Views/Home/About.cshtml | @using Resources
@{
ViewBag.Title = "About";
}
<h1>Sobre nos ...</h1>
<p>@Resources.Site.Texto</p>
<p>
<a href="~/Home/Ingles">Ingles - Estados Unidos</a></p>
<p>
<a href="~/Home/Portugues">Portugues - Brasil</a>
</p>
<p>
<a href="~/Home/Portugues" class="btn btn-primary">
<span class="glyphicon glyphicon-bitcoin" aria-hidden="true"></span>
Portugues
</a>
</p>
<p>
<a href="~/Home/Ingles" class="btn btn-default">
<span class="glyphicon glyphicon-apple" aria-hidden="true"></span>
Ingles
</a>
</p>
| @using Resources
@{
ViewBag.Title = "About";
}
<h1>Sobre nos ...</h1>
<p>@Resources.Site.Texto</p>
<p>
<a href="~/Home/Ingles">Ingles - Estados Unidos</a></p>
<p>
<a href="~/Home/Portugues">Portugues - Brasil</a>
</p>
| mit | C# |
77c0ad34d6fc7a9c6124299833b733f39165bb35 | Add missing ErrorCode values from zmq.h. | jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq | src/proj/ZeroMQ/Proxy/ErrorCode.cs | src/proj/ZeroMQ/Proxy/ErrorCode.cs | namespace ZeroMQ.Proxy
{
internal enum ErrorCode
{
Eperm = 1,
Enoent = 2,
Esrch = 3,
Eintr = 4,
Eio = 5,
Enxio = 6,
E2Big = 7,
Enoexec = 8,
Ebadf = 9,
Echild = 10,
Eagain = 11,
Enomem = 12,
Eacces = 13,
Efault = 14,
Ebusy = 16,
Eexist = 17,
Exdev = 18,
Enodev = 19,
Enotdir = 20,
Eisdir = 21,
Enfile = 23,
Emfile = 24,
Enotty = 25,
Efbig = 27,
Enospc = 28,
Espipe = 29,
Erofs = 30,
Emlink = 31,
Epipe = 32,
Edom = 33,
Edeadlk = 36,
Enametoolong = 38,
Enolck = 39,
Enosys = 40,
Enotempty = 41,
ZmqHausNumero = 156384712,
// Some of the standard POSIX errnos are not defined on Windows
Enotsup = ZmqHausNumero + 1,
Eprotonosupport = ZmqHausNumero + 2,
Enobufs = ZmqHausNumero + 3,
Enetdown = ZmqHausNumero + 4,
Eaddrinuse = ZmqHausNumero + 5,
Eaddrnotavail = ZmqHausNumero + 6,
Econnrefused = ZmqHausNumero + 7,
Einprogress = ZmqHausNumero + 8,
Enotsock = ZmqHausNumero + 9,
// Native 0MQ error codes
Efsm = ZmqHausNumero + 51,
Enocompatproto = ZmqHausNumero + 52,
Eterm = ZmqHausNumero + 53,
Emthread = ZmqHausNumero + 54,
}
}
| namespace ZeroMQ.Proxy
{
internal enum ErrorCode
{
Eperm = 1,
Enoent = 2,
Esrch = 3,
Eintr = 4,
Eio = 5,
Enxio = 6,
E2Big = 7,
Enoexec = 8,
Ebadf = 9,
Echild = 10,
Eagain = 11,
Enomem = 12,
Eacces = 13,
Efault = 14,
Ebusy = 16,
Eexist = 17,
Exdev = 18,
Enodev = 19,
Enotdir = 20,
Eisdir = 21,
Enfile = 23,
Emfile = 24,
Enotty = 25,
Efbig = 27,
Enospc = 28,
Espipe = 29,
Erofs = 30,
Emlink = 31,
Epipe = 32,
Edom = 33,
Edeadlk = 36,
Enametoolong = 38,
Enolck = 39,
Enosys = 40,
Enotempty = 41,
}
}
| apache-2.0 | C# |
76379cbedfc019021ed97e1a661ac14628ea4dd7 | Update Environment Repository | RichardSlater/CheckyChatbot,RichardSlater/CheckyChatbot,RichardSlater/CheckyChatbot,RichardSlater/CheckyChatbot | src/Common/Healthbot/EnvironmentRepository.cs | src/Common/Healthbot/EnvironmentRepository.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.Azure.Documents.Client;
namespace Healthbot {
public class EnvironmentRepository {
private readonly Dictionary<string, string> _context;
private readonly DocumentClient _client;
private readonly Uri _environmentsCollection;
private readonly FeedOptions _feedOptions;
public EnvironmentRepository() {
var configuration = ConfigurationManager.ConnectionStrings;
var datasource = configuration["Datasource"];
var connectionString = datasource == null
? System.Environment.GetEnvironmentVariable("CONNECTIONSTRING_Datasource")
: datasource.ConnectionString;
if (connectionString == null) {
throw new ConfigurationErrorsException("Unable to get connection string for DocumentDB.");
}
_context =
connectionString.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.ToDictionary(key => key.Split('=')[0], value => value.Split(new[] {'='}, 2)[1]);
_client = new DocumentClient(new Uri(_context["AccountEndpoint"]), _context["AccountKey"]);
_feedOptions = new FeedOptions {
MaxItemCount = 1
};
_environmentsCollection = UriFactory.CreateDocumentCollectionUri(_context["Database"],
_context["Collection"]);
}
public Environment Get(string environment) {
var collection = _client.CreateDocumentQuery<Environment>(_environmentsCollection, _feedOptions);
return collection
.AsEnumerable()
.SingleOrDefault(x => string.Equals(x.Id, environment, StringComparison.InvariantCultureIgnoreCase));
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.Azure.Documents.Client;
namespace Healthbot {
public class EnvironmentRepository {
private readonly Dictionary<string, string> _context;
private readonly DocumentClient _client;
private readonly Uri _environmentsCollection;
private readonly FeedOptions _feedOptions;
public EnvironmentRepository() {
var configuration = ConfigurationManager.ConnectionStrings;
var datasource = configuration["Datasource"];
var connectionString = datasource == null ? System.Environment.GetEnvironmentVariable("CONNECTIONSTRING_Datasource") : datasource.ConnectionString;
if (connectionString == null) {
throw new ConfigurationErrorsException("Unable to get connection string for DocumentDB.");
}
_context = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToDictionary(key => key.Split('=')[0], value => value.Split(new[] { '=' }, 2)[1]);
_client = new DocumentClient(new Uri(_context["AccountEndpoint"]), _context["AccountKey"]);
_feedOptions = new FeedOptions {
MaxItemCount = 1
};
_environmentsCollection = UriFactory.CreateDocumentCollectionUri(_context["Database"],
_context["Collection"]);
}
public Environment Get(string environment) {
var collection = _client.CreateDocumentQuery<Environment>(_environmentsCollection, _feedOptions);
return collection
.AsEnumerable()
.SingleOrDefault(x => string.Equals(x.Id, environment, StringComparison.InvariantCultureIgnoreCase));
}
}
} | apache-2.0 | C# |
08fcdc8ee46748eee4c8d66d5842b57f16d9d896 | Update difficulty calculator tests with floating point differences | NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs | osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.9311451172574934d, "diffcalc-test")]
[TestCase(1.0736586907780401d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.6228371119271454d, "diffcalc-test")]
[TestCase(1.2864585280364178d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
| // 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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.9311451172608853d, "diffcalc-test")]
[TestCase(1.0736587013228804d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.6228371119393064d, "diffcalc-test")]
[TestCase(1.2864585434597433d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
| mit | C# |
55d057c8cda2715bb33a8a43776d6d985eb8ce44 | disable sensitive data logging | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | src/FilterLists.Services/DependencyInjection/Extensions/ConfigureServicesCollection.cs | src/FilterLists.Services/DependencyInjection/Extensions/ConfigureServicesCollection.cs | using AutoMapper;
using FilterLists.Data;
using FilterLists.Services.FilterList;
using FilterLists.Services.Seed;
using FilterLists.Services.Snapshot;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace FilterLists.Services.DependencyInjection.Extensions
{
public static class ConfigureServicesCollection
{
public static void AddFilterListsApiServices(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton(c => config);
services.AddEntityFrameworkMySql()
.AddDbContextPool<FilterListsDbContext>(opts =>
opts.UseMySql(config.GetConnectionString("FilterListsConnection"),
x => x.MigrationsAssembly("FilterLists.Api")));
services.TryAddScoped<FilterListService>();
services.TryAddScoped<RuleService>();
services.TryAddScoped<SeedService>();
services.AddAutoMapper();
}
public static void AddFilterListsAgentServices(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton(c => config);
services.AddEntityFrameworkMySql()
.AddDbContextPool<FilterListsDbContext>(opts =>
opts.UseMySql(config.GetConnectionString("FilterListsConnection"),
x => x.MigrationsAssembly("FilterLists.Api")));
services.TryAddScoped<SnapshotService>();
services.TryAddScoped<EmailService>();
services.AddAutoMapper();
}
}
} | using AutoMapper;
using FilterLists.Data;
using FilterLists.Services.FilterList;
using FilterLists.Services.Seed;
using FilterLists.Services.Snapshot;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace FilterLists.Services.DependencyInjection.Extensions
{
public static class ConfigureServicesCollection
{
public static void AddFilterListsApiServices(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton(c => config);
services.AddEntityFrameworkMySql()
.AddDbContextPool<FilterListsDbContext>(opts =>
opts.UseMySql(config.GetConnectionString("FilterListsConnection"),
x => x.MigrationsAssembly("FilterLists.Api"))
.EnableSensitiveDataLogging());
services.TryAddScoped<FilterListService>();
services.TryAddScoped<RuleService>();
services.TryAddScoped<SeedService>();
services.AddAutoMapper();
}
public static void AddFilterListsAgentServices(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton(c => config);
services.AddEntityFrameworkMySql()
.AddDbContextPool<FilterListsDbContext>(opts =>
opts.UseMySql(config.GetConnectionString("FilterListsConnection"),
x => x.MigrationsAssembly("FilterLists.Api"))
.EnableSensitiveDataLogging());
services.TryAddScoped<SnapshotService>();
services.TryAddScoped<EmailService>();
services.AddAutoMapper();
}
}
} | mit | C# |
293f97286aa215eb3a4a4321f88976759739eb9a | Add route to support children | peasy/Samples,peasy/Samples,ahanusa/Peasy.NET,peasy/Peasy.NET,ahanusa/facile.net,peasy/Samples | Orders.com.Web.Api/App_Start/WebApiConfig.cs | Orders.com.Web.Api/App_Start/WebApiConfig.cs | using Orders.com.Web.Api.Filters;
using System.Web.Http;
namespace Orders.com.Web.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "children",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| using Orders.com.Web.Api.Filters;
using System.Web.Http;
namespace Orders.com.Web.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit | C# |
94fae2f9beb77e368d3c35f0b60063cfa228f27c | Enforce token type. | Brightspace/D2L.Security.OAuth2 | D2L.Security.OAuth2/Validation/D2L.Security.AuthTokenValidation/TokenValidation/Default/JWTValidator.cs | D2L.Security.OAuth2/Validation/D2L.Security.AuthTokenValidation/TokenValidation/Default/JWTValidator.cs | using System;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using D2L.Security.AuthTokenValidation.PublicKeys;
namespace D2L.Security.AuthTokenValidation.TokenValidation.Default {
internal sealed class JWTValidator : IJWTValidator {
private const string ALLOWED_SIGNATURE_ALGORITHM = "RS256";
private const string ALLOWED_TOKEN_TYPE = "JWT";
private readonly IPublicKeyProvider m_keyProvider;
internal JWTValidator( IPublicKeyProvider keyProvider ) {
m_keyProvider = keyProvider;
}
IValidatedJWT IJWTValidator.Validate( string jwt ) {
JwtSecurityTokenHandler tokenHandler = Helper.CreateTokenHandler();
IPublicKey key = m_keyProvider.Get();
TokenValidationParameters validationParameters =
Helper.CreateValidationParameters( key.Issuer, key.SecurityKey );
SecurityToken securityToken;
ClaimsPrincipal principal = tokenHandler.ValidateToken( jwt, validationParameters, out securityToken );
Type source = securityToken.GetType();
Type target = typeof( JwtSecurityToken );
if( !target.IsAssignableFrom( source ) ) {
string message = string.Format(
"Expected to deserialize token to {0} but was {1}",
target.AssemblyQualifiedName,
source.AssemblyQualifiedName
);
throw new Exception( message );
}
JwtSecurityToken jwtSecurityToken = (JwtSecurityToken)securityToken;
if( jwtSecurityToken.SignatureAlgorithm != ALLOWED_SIGNATURE_ALGORITHM ) {
string message = string.Format(
"Expected signature algorithm {0} but was {1}",
ALLOWED_SIGNATURE_ALGORITHM,
jwtSecurityToken.SignatureAlgorithm
);
throw new Exception( message );
}
string tokenType = jwtSecurityToken.Header.Typ;
if( tokenType != ALLOWED_TOKEN_TYPE ) {
string message = string.Format(
"Expected token type {0} but was {1}",
ALLOWED_TOKEN_TYPE,
tokenType
);
throw new Exception( message );
}
IValidatedJWT validatedJWT = new ValidatedJWT( jwtSecurityToken );
return validatedJWT;
}
}
}
| using System;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using D2L.Security.AuthTokenValidation.PublicKeys;
namespace D2L.Security.AuthTokenValidation.TokenValidation.Default {
internal sealed class JWTValidator : IJWTValidator {
private const string ALLOWED_SIGNATURE_ALGORITHM = "RS256";
private readonly IPublicKeyProvider m_keyProvider;
internal JWTValidator( IPublicKeyProvider keyProvider ) {
m_keyProvider = keyProvider;
}
IValidatedJWT IJWTValidator.Validate( string jwt ) {
JwtSecurityTokenHandler tokenHandler = Helper.CreateTokenHandler();
IPublicKey key = m_keyProvider.Get();
TokenValidationParameters validationParameters =
Helper.CreateValidationParameters( key.Issuer, key.SecurityKey );
SecurityToken securityToken;
ClaimsPrincipal principal = tokenHandler.ValidateToken( jwt, validationParameters, out securityToken );
Type source = securityToken.GetType();
Type target = typeof( JwtSecurityToken );
if( !target.IsAssignableFrom( source ) ) {
string message = string.Format(
"Expected to deserialize token to {0} but was {1}",
target.AssemblyQualifiedName,
source.AssemblyQualifiedName
);
throw new Exception( message );
}
JwtSecurityToken jwtSecurityToken = (JwtSecurityToken)securityToken;
if( jwtSecurityToken.SignatureAlgorithm != ALLOWED_SIGNATURE_ALGORITHM ) {
string message = string.Format(
"Expected signature algorithm {0} but was {1}",
ALLOWED_SIGNATURE_ALGORITHM,
jwtSecurityToken.SignatureAlgorithm
);
throw new Exception( message );
}
IValidatedJWT validatedJWT = new ValidatedJWT( jwtSecurityToken );
return validatedJWT;
}
}
}
| apache-2.0 | C# |
43588a2a6ba40378f0e4bff9fef182002e60a9a9 | Fix build | Tlaster/iHentai | src/iHentai.Services/EHentai/ApiExtensions.cs | src/iHentai.Services/EHentai/ApiExtensions.cs | using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using iHentai.Html;
namespace iHentai.Services.EHentai
{
internal static class ApiExtensions
{
public static Task<T?> GetHtmlAsync<T>(
this Url url,
CancellationToken cancellationToken = default,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) where T: class
{
return new FlurlRequest(url).GetHtmlAsync<T>(cancellationToken, completionOption);
}
public static Task<T?> GetHtmlAsync<T>(
this IFlurlRequest request,
CancellationToken cancellationToken = default,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) where T: class
{
return request.SendAsync(HttpMethod.Get, null, cancellationToken, completionOption).ReceiveHtml<T>();
}
public static async Task<T?> ReceiveHtml<T>(this Task<IFlurlResponse> response) where T: class
{
using var resp = await response;
if (resp == null)
{
return default;
}
using var result = await resp.GetStreamAsync();
return HtmlConvert.DeserializeObject<T>(result);
}
}
} | using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using iHentai.Html;
namespace iHentai.Services.EHentai
{
internal static class ApiExtensions
{
public static Task<T> GetHtmlAsync<T>(
this Url url,
CancellationToken cancellationToken = default,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
return new FlurlRequest(url).GetHtmlAsync<T>(cancellationToken, completionOption);
}
public static Task<T> GetHtmlAsync<T>(
this IFlurlRequest request,
CancellationToken cancellationToken = default,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
return request.SendAsync(HttpMethod.Get, null, cancellationToken, completionOption).ReceiveHtml<T>();
}
public static async Task<T> ReceiveHtml<T>(this Task<IFlurlResponse> response)
{
using var resp = await response;
if (resp == null)
{
return default;
}
using var result = await resp.GetStreamAsync();
return HtmlConvert.DeserializeObject<T>(result);
}
}
} | mit | C# |
4f97ff00120ac326272f0b5589c680934e57afc3 | Update Index.cshtml | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Updated: January 11, 2021<br /><br />
A modest rate increase will be implemented on February 1, 2021.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
| mit | C# |
28c430090212955f94a7f5b89d17600829078c23 | Remove most proxy logic from ProcessProxy | lou1306/CIV,lou1306/CIV | CIV.Ccs/Processes/ProcessProxy.cs | CIV.Ccs/Processes/ProcessProxy.cs | using System.Collections.Generic;
using static CIV.Ccs.CcsParser;
using CIV.Interfaces;
namespace CIV.Ccs
{
/// <summary>
/// Proxy class that delays the creation of a new Process instance until it
/// is needed.
/// </summary>
class ProcessProxy : Proxy<CcsProcess, ProcessContext>, IHasWeakTransitions
{
public ProcessProxy(IFactory<CcsProcess, ProcessContext> factory, ProcessContext context) : base(factory, context)
{
}
IEnumerable<Transition> IProcess.Transitions() => Real.Transitions();
IEnumerable<Transition> IHasWeakTransitions.WeakTransitions()
{
return Real.WeakTransitions();
}
}
}
| using System.Collections.Generic;
using static CIV.Ccs.CcsParser;
using CIV.Interfaces;
namespace CIV.Ccs
{
/// <summary>
/// Proxy class that delays the creation of a new Process instance until it
/// is needed.
/// </summary>
class ProcessProxy : CcsProcess
{
protected ProcessContext context;
protected ProcessFactory factory;
IProcess _real;
IProcess RealProcess => _real ?? (_real = factory.Create(context));
public ProcessProxy(ProcessFactory factory, ProcessContext context)
{
this.factory = factory;
this.context = context;
}
public override IEnumerable<Transition> Transitions() =>
RealProcess.Transitions();
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.