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 |
|---|---|---|---|---|---|---|---|---|
978fdd31093e139323bf500b90aafe3aed6638e0 | Set expires header to max when response is intented to be cached, so browsers will not use try-get pattern for those resources next time. | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | Foundation/Server/Foundation.Api/Middlewares/OwinCacheResponseMiddleware.cs | Foundation/Server/Foundation.Api/Middlewares/OwinCacheResponseMiddleware.cs | using System.Threading.Tasks;
using Microsoft.Owin;
using System.Linq;
using System;
using Foundation.Api.Implementations;
namespace Foundation.Api.Middlewares
{
public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware
{
public OwinCacheResponseMiddleware()
{
}
public OwinCacheResponseMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task OnActionExecutingAsync(IOwinContext owinContext)
{
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Cache-Control");
owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" });
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Pragma");
owinContext.Response.Headers.Add("Pragma", new[] { "public" });
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Expires");
owinContext.Response.Headers.Add("Expires", new[] { "max" });
await base.OnActionExecutingAsync(owinContext);
}
}
} | using System.Threading.Tasks;
using Microsoft.Owin;
using System.Linq;
using System;
using Foundation.Api.Implementations;
using System.Threading;
namespace Foundation.Api.Middlewares
{
public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware
{
public OwinCacheResponseMiddleware()
{
}
public OwinCacheResponseMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task OnActionExecutingAsync(IOwinContext owinContext)
{
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Cache-Control");
owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" });
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Pragma");
owinContext.Response.Headers.Add("Pragma", new[] { "public" });
if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase)))
owinContext.Response.Headers.Remove("Expires");
owinContext.Response.Headers.Add("Expires", new[] { "31536000" });
await base.OnActionExecutingAsync(owinContext);
}
}
} | mit | C# |
b44bfe7d00584c154d76836f238e943fa95af59f | Set line ending according to the enviroment in ReFormatXML | cezarypiatek/VanillaTransformer | Src/VanillaTransformer/PostTransformations/XML/ReFormatXMLTransformation.cs | Src/VanillaTransformer/PostTransformations/XML/ReFormatXMLTransformation.cs | using System;
using System.IO;
using System.Xml;
namespace VanillaTransformer.PostTransformations.XML
{
public class ReFormatXMLTransformation:IPostTransformation
{
public string Name { get { return "ReFormatXML"; } }
public string Execute(string configContent)
{
var settings = new XmlWriterSettings()
{
Indent = true,
IndentChars = " ",
NewLineChars = Environment.NewLine,
NewLineHandling = NewLineHandling.Replace,
};
var xDocument = new XmlDocument();
xDocument.LoadXml(configContent);
using (var textWriter = new StringWriter())
{
using (var writer = XmlWriter.Create(textWriter,settings))
{
xDocument.WriteTo(writer);
}
return textWriter.ToString();
}
}
}
}
| using System.IO;
using System.Xml;
namespace VanillaTransformer.PostTransformations.XML
{
public class ReFormatXMLTransformation:IPostTransformation
{
public string Name { get { return "ReFormatXML"; } }
public string Execute(string configContent)
{
var settings = new XmlWriterSettings()
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace,
};
var xDocument = new XmlDocument();
xDocument.LoadXml(configContent);
using (var textWriter = new StringWriter())
{
using (var writer = XmlWriter.Create(textWriter,settings))
{
xDocument.WriteTo(writer);
}
return textWriter.ToString();
}
}
}
}
| mit | C# |
85c4f388c6f0d743ad8e40596caddf0fe32f1dda | Fix header tags for Environment and Metrics (#1700) | dotnet/dotnet-docker,MichaelSimons/dotnet-docker,MichaelSimons/dotnet-docker,dotnet/dotnet-docker | samples/aspnetapp/aspnetapp/Pages/Index.cshtml | samples/aspnetapp/aspnetapp/Pages/Index.cshtml | @page
@using System.Runtime.InteropServices
@using System.IO
@using System.Diagnostics
@model IndexModel
@{
ViewData["Title"] = "Home page";
var process = Process.GetCurrentProcess();
}
<div class="text-center">
<h1 class="display-4">Welcome to .NET Core</h1>
<h5>Environment</h5>
<p>@RuntimeInformation.FrameworkDescription</p>
<p>@RuntimeInformation.OSDescription</p>
</div>
<div>
<h5 class="text-center">Metrics</h5>
<table width="500" align="center" class="table-striped table-hover">
<tr>
<td>Containerized</td>
<td>@(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") is object ? "true" : "false")</td>
</tr>
<tr>
<td>CPU cores</td>
<td>@Environment.ProcessorCount</td>
</tr>
@if (RuntimeInformation.OSDescription.StartsWith("Linux") && Directory.Exists("/sys/fs/cgroup/memory"))
{
<tr>
<td>cgroup memory usage</td>
<td>@System.IO.File.ReadAllLines("/sys/fs/cgroup/memory/memory.usage_in_bytes")[0]</td>
</tr>
}
<tr>
<td>Memory, current usage (bytes)</td>
<td>@process.WorkingSet64</td>
</tr>
<tr>
<td>Memory, max available (bytes)</td>
<td>@process.MaxWorkingSet</td>
</tr>
</table>
</div>
| @page
@using System.Runtime.InteropServices
@using System.IO
@using System.Diagnostics
@model IndexModel
@{
ViewData["Title"] = "Home page";
var process = Process.GetCurrentProcess();
}
<div class="text-center">
<h1 class="display-4">Welcome to .NET Core</h1>
<h5>Environment</h1>
<p>@RuntimeInformation.FrameworkDescription</p>
<p>@RuntimeInformation.OSDescription</p>
</div>
<div>
<h5 class="text-center">Metrics</h1>
<table width="500" align="center" class="table-striped table-hover">
<tr>
<td>Containerized</td>
<td>@(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") is object ? "true" : "false")</td>
</tr>
<tr>
<td>CPU cores</td>
<td>@Environment.ProcessorCount</td>
</tr>
@if (RuntimeInformation.OSDescription.StartsWith("Linux") && Directory.Exists("/sys/fs/cgroup/memory"))
{
<tr>
<td>cgroup memory usage</td>
<td>@System.IO.File.ReadAllLines("/sys/fs/cgroup/memory/memory.usage_in_bytes")[0]</td>
</tr>
}
<tr>
<td>Memory, current usage (bytes)</td>
<td>@process.WorkingSet64</td>
</tr>
<tr>
<td>Memory, max available (bytes)</td>
<td>@process.MaxWorkingSet</td>
</tr>
</table>
</div>
| mit | C# |
745cc8e5cba478dd23384e1990059d0c8ac01af2 | Fix v11 main | Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,selvasingh/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java | net/Azure.Storage.Blobs.V11.PerfStress/Program.cs | net/Azure.Storage.Blobs.V11.PerfStress/Program.cs | using Azure.Test.PerfStress;
using System;
using System.Threading.Tasks;
namespace Azure.Storage.Blobs.V11.PerfStress
{
class Program
{
static async Task Main(string[] args)
{
await PerfStressProgram.Main(typeof(Program).Assembly, args);
}
}
}
| using System;
namespace Azure.Storage.Blobs.V11.PerfStress
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| mit | C# |
0838a58b146cf25d6ee3650464e8468575b82606 | Add columns | Catel/Catel.Benchmarks | src/Catel.Benchmarks.Shared/BenchmarkConfig.cs | src/Catel.Benchmarks.Shared/BenchmarkConfig.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BenchmarkConfig.cs" company="Catel development team">
// Copyright (c) 2008 - 2016 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Benchmarks
{
using BenchmarkDotNet.Analysers;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters.Csv;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Validators;
public class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
Options = ConfigOptions.KeepBenchmarkFiles;
// Exporters
//Add(MarkdownExporter.Default);
//Add(MarkdownExporter.GitHub);
//Add(AsciiDocExporter.Default);
//Add(HtmlExporter.Default);
//Add(CsvExporter.Default);
Add(CsvMeasurementsExporter.Default);
//Add(RPlotExporter.Default);
// Columns
Add(DefaultColumnProviders.Instance);
// Loggers
Add(ConsoleLogger.Default);
// Analyzers
Add(EnvironmentAnalyser.Default);
Add(OutliersAnalyser.Default);
// Diagnosers
Add(MemoryDiagnoser.Default);
//Add(InliningDiagnoser.Default);
//Add(MemoryDiagnoser.Default);
// Validators
Add((IValidator)BaselineValidator.FailOnError);
Add(JitOptimizationsValidator.FailOnError);
Add(ExecutionValidator.FailOnError);
Add(ReturnValueValidator.FailOnError);
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BenchmarkConfig.cs" company="Catel development team">
// Copyright (c) 2008 - 2016 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Benchmarks
{
using BenchmarkDotNet.Analysers;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters.Csv;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Validators;
public class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
KeepBenchmarkFiles = true;
// Exporters
//Add(MarkdownExporter.Default);
//Add(MarkdownExporter.GitHub);
//Add(AsciiDocExporter.Default);
//Add(HtmlExporter.Default);
//Add(CsvExporter.Default);
Add(CsvMeasurementsExporter.Default);
//Add(RPlotExporter.Default);
// Loggers
Add(ConsoleLogger.Default);
// Analyzers
Add(EnvironmentAnalyser.Default);
Add(OutliersAnalyser.Default);
// Diagnosers
Add(MemoryDiagnoser.Default);
//Add(InliningDiagnoser.Default);
//Add(MemoryDiagnoser.Default);
// Validators
Add((IValidator)BaselineValidator.FailOnError);
Add(JitOptimizationsValidator.FailOnError);
Add(ExecutionValidator.FailOnError);
Add(ReturnValueValidator.FailOnError);
}
}
}
| mit | C# |
b83f8d899de527bdc1af074a4a051b75bab6ca8c | Add missing BiasPref to FullyConnLayer | cbovar/ConvNetSharp | src/ConvNetSharp.Flow/Layers/FullyConnLayer.cs | src/ConvNetSharp.Flow/Layers/FullyConnLayer.cs | using System;
using ConvNetSharp.Flow.Ops;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Flow.Layers
{
public class FullyConnLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable
{
private readonly int _neuronCount;
private bool _initialized;
private T _biasPref;
private Variable<T> _bias;
public FullyConnLayer(int neuronCount)
{
this._neuronCount = neuronCount;
}
public T BiasPref
{
get { return this._biasPref; }
set
{
this._biasPref = value;
if (this._initialized)
{
this._bias.Result = new T[this._neuronCount].Populate(this.BiasPref);
}
}
}
public override void AcceptParent(LayerBase<T> parent)
{
base.AcceptParent(parent);
var cns = ConvNetSharp<T>.Instance;
using (cns.Scope($"FullConnLayer_{this.Id}"))
{
this._bias = cns.Variable(BuilderInstance<T>.Volume.SameAs(new Shape(1, 1, this._neuronCount, 1)), "Bias");
this.Op = cns.Conv(cns.Reshape(parent.Op, new Shape(1, 1, -1, Shape.Keep)), 1, 1, this._neuronCount) + this._bias;
}
this._initialized = true;
}
}
} | using System;
using ConvNetSharp.Flow.Ops;
using ConvNetSharp.Volume;
namespace ConvNetSharp.Flow.Layers
{
public class FullyConnLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable
{
private readonly int _neuronCount;
private Variable<T> _bias;
public FullyConnLayer(int neuronCount)
{
this._neuronCount = neuronCount;
}
public override void AcceptParent(LayerBase<T> parent)
{
base.AcceptParent(parent);
var cns = ConvNetSharp<T>.Instance;
using (cns.Scope($"FullConnLayer_{this.Id}"))
{
this._bias = cns.Variable(BuilderInstance<T>.Volume.SameAs(new Shape(1, 1, this._neuronCount, 1)), "Bias");
this.Op = cns.Conv(cns.Reshape(parent.Op, new Shape(1, 1, -1, Shape.Keep)), 1, 1, this._neuronCount) + this._bias;
}
}
}
} | mit | C# |
7c0547b4ee00f053b87124b55cc65ac1ed7d47e0 | Replace todo | 2yangk23/osu,naoey/osu,johnneijzen/osu,ZLima12/osu,peppy/osu,smoogipooo/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,DrabWeb/osu,naoey/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu | osu.Game/Graphics/UserInterface/FocusedTextBox.cs | osu.Game/Graphics/UserInterface/FocusedTextBox.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 OpenTK.Graphics;
using osu.Framework.Input;
using System;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A textbox which holds focus eagerly.
/// </summary>
public class FocusedTextBox : OsuTextBox
{
protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255);
protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255);
public Action Exit;
private bool focus;
public bool HoldFocus
{
get { return focus; }
set
{
focus = value;
if (!focus && HasFocus)
KillFocus();
}
}
// We may not be focused yet, but we need to handle keyboard input to be able to request focus
public override bool HandleKeyboardInput => HoldFocus || base.HandleKeyboardInput;
protected override void OnFocus(InputState state)
{
base.OnFocus(state);
BorderThickness = 0;
}
protected override void KillFocus()
{
base.KillFocus();
Exit?.Invoke();
}
public override bool RequestsFocus => HoldFocus;
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Input;
using System;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A textbox which holds focus eagerly.
/// </summary>
public class FocusedTextBox : OsuTextBox
{
protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255);
protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255);
public Action Exit;
private bool focus;
public bool HoldFocus
{
get { return focus; }
set
{
focus = value;
if (!focus && HasFocus)
//todo: replace with KillInput after ppy/osu-framework#1656 is merged.
GetContainingInputManager().ChangeFocus(null);
}
}
// We may not be focused yet, but we need to handle keyboard input to be able to request focus
public override bool HandleKeyboardInput => HoldFocus || base.HandleKeyboardInput;
protected override void OnFocus(InputState state)
{
base.OnFocus(state);
BorderThickness = 0;
}
protected override void KillFocus()
{
base.KillFocus();
Exit?.Invoke();
}
public override bool RequestsFocus => HoldFocus;
}
}
| mit | C# |
d4c1b09a9b170a345a175b7585da71d92aa72134 | Increment minor version | emoacht/SnowyImageCopy | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| mit | C# |
4cd21fabf34e59956740ad78f5703285baced4b7 | Remove extra newlines | ppy/osu,DrabWeb/osu,2yangk23/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,naoey/osu,smoogipooo/osu,EVAST9919/osu,naoey/osu,johnneijzen/osu,naoey/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,ppy/osu | osu.Game/Graphics/UserInterface/TriangleButton.cs | osu.Game/Graphics/UserInterface/TriangleButton.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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Backgrounds;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with moving triangles in the background.
/// </summary>
public class TriangleButton : OsuButton, IFilterable
{
protected Triangles Triangles { get; private set; }
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Add(Triangles = new Triangles
{
RelativeSizeAxes = Axes.Both,
ColourDark = colours.BlueDarker,
ColourLight = colours.Blue,
});
}
public IEnumerable<string> FilterTerms => new[] { Text };
public bool MatchingFilter
{
set
{
this.FadeTo(value ? 1 : 0);
}
}
}
}
| // 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Backgrounds;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with moving triangles in the background.
/// </summary>
public class TriangleButton : OsuButton, IFilterable
{
protected Triangles Triangles { get; private set; }
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Add(Triangles = new Triangles
{
RelativeSizeAxes = Axes.Both,
ColourDark = colours.BlueDarker,
ColourLight = colours.Blue,
});
}
public IEnumerable<string> FilterTerms => new[] { Text };
public bool MatchingFilter
{
set
{
this.FadeTo(value ? 1 : 0);
}
}
}
}
| mit | C# |
e8455dc1e41ca92d0f9d1118af1187da88aba740 | Fix incorrect hash usage | peppy/osu-new,johnneijzen/osu,DrabWeb/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,ppy/osu,DrabWeb/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,naoey/osu,peppy/osu,smoogipooo/osu,2yangk23/osu,2yangk23/osu,EVAST9919/osu,ZLima12/osu,peppy/osu,ZLima12/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu | osu.Game/Online/API/Requests/GetBeatmapRequest.cs | osu.Game/Online/API/Requests/GetBeatmapRequest.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetBeatmapRequest : APIRequest<APIBeatmap>
{
private readonly BeatmapInfo beatmap;
private string lookupString => beatmap.OnlineBeatmapID > 0 ? beatmap.OnlineBeatmapID.ToString() : $@"lookup?checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}";
public GetBeatmapRequest(BeatmapInfo beatmap)
{
this.beatmap = beatmap;
}
protected override string Target => $@"beatmaps/{lookupString}";
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetBeatmapRequest : APIRequest<APIBeatmap>
{
private readonly BeatmapInfo beatmap;
private string lookupString => beatmap.OnlineBeatmapID > 0 ? beatmap.OnlineBeatmapID.ToString() : $@"lookup?checksum={beatmap.Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}";
public GetBeatmapRequest(BeatmapInfo beatmap)
{
this.beatmap = beatmap;
}
protected override string Target => $@"beatmaps/{lookupString}";
}
}
| mit | C# |
d20a3a3d9bb6b82e9d99c983dcb87c23ec73851a | allow global route prefix registration as string | WebApiContrib/WebAPIContrib.Core,WebApiContrib/WebAPIContrib.Core | src/WebApiContrib.Core/MvcOptionsExtensions.cs | src/WebApiContrib.Core/MvcOptionsExtensions.cs | using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;
using WebApiContrib.Core.Binding;
using WebApiContrib.Core.Routing;
namespace WebApiContrib.Core
{
public static class MvcOptionsExtensions
{
public static void UseGlobalRoutePrefix(this MvcOptions opts, string routeTemplate)
{
opts.Conventions.Insert(0, new GlobalRoutePrefixConvention(new RouteAttribute(routeTemplate)));
}
public static void UseGlobalRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
{
opts.Conventions.Insert(0, new GlobalRoutePrefixConvention(routeAttribute));
}
public static void UseFromBodyBinding(this MvcOptions opts, Func<ControllerModel, bool> controllerPredicate = null,
Func<ActionModel, bool> actionPredicate = null, Func<ParameterModel, bool> parameterPredicate = null)
{
opts.Conventions.Insert(0, new FromBodyApplicationModelConvention(controllerPredicate, actionPredicate, parameterPredicate));
}
}
}
| using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;
using WebApiContrib.Core.Binding;
using WebApiContrib.Core.Routing;
namespace WebApiContrib.Core
{
public static class MvcOptionsExtensions
{
public static void UseGlobalRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
{
opts.Conventions.Insert(0, new GlobalRoutePrefixConvention(routeAttribute));
}
public static void UseFromBodyBinding(this MvcOptions opts, Func<ControllerModel, bool> controllerPredicate = null,
Func<ActionModel, bool> actionPredicate = null, Func<ParameterModel, bool> parameterPredicate = null)
{
opts.Conventions.Insert(0, new FromBodyApplicationModelConvention(controllerPredicate, actionPredicate, parameterPredicate));
}
}
}
| mit | C# |
4bc324f040b3bfaca1e57af88f00558a6237d6bc | Rename parameter to make more sense | UselessToucan/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new | osu.Game/Graphics/UserInterface/ProgressBar.cs | osu.Game/Graphics/UserInterface/ProgressBar.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.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Graphics.UserInterface
{
public class ProgressBar : SliderBar<double>
{
public Action<double> OnSeek;
private readonly Box fill;
private readonly Box background;
public Color4 FillColour
{
set => fill.FadeColour(value, 150, Easing.OutQuint);
}
public Color4 BackgroundColour
{
set
{
background.Alpha = 1;
background.Colour = value;
}
}
public double EndTime
{
set => CurrentNumber.MaxValue = value;
}
public double CurrentTime
{
set => CurrentNumber.Value = value;
}
private readonly bool allowSeek;
public override bool HandlePositionalInput => allowSeek;
public override bool HandleNonPositionalInput => allowSeek;
/// <summary>
/// Construct a new progress bar.
/// </summary>
/// <param name="allowSeek">Whether the user should be allowed to click/drag to adjust the value.</param>
public ProgressBar(bool allowSeek)
{
this.allowSeek = allowSeek;
CurrentNumber.MinValue = 0;
CurrentNumber.MaxValue = 1;
RelativeSizeAxes = Axes.X;
Children = new Drawable[]
{
background = new Box
{
Alpha = 0,
RelativeSizeAxes = Axes.Both
},
fill = new Box { RelativeSizeAxes = Axes.Y }
};
}
protected override void UpdateValue(float value)
{
fill.Width = value * UsableWidth;
}
protected override void OnUserChange(double value) => OnSeek?.Invoke(value);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.UserInterface;
using osuTK.Graphics;
namespace osu.Game.Graphics.UserInterface
{
public class ProgressBar : SliderBar<double>
{
public Action<double> OnSeek;
private readonly Box fill;
private readonly Box background;
public Color4 FillColour
{
set => fill.FadeColour(value, 150, Easing.OutQuint);
}
public Color4 BackgroundColour
{
set
{
background.Alpha = 1;
background.Colour = value;
}
}
public double EndTime
{
set => CurrentNumber.MaxValue = value;
}
public double CurrentTime
{
set => CurrentNumber.Value = value;
}
private readonly bool userInteractive;
public override bool HandlePositionalInput => userInteractive;
public override bool HandleNonPositionalInput => userInteractive;
public ProgressBar(bool userInteractive)
{
this.userInteractive = userInteractive;
CurrentNumber.MinValue = 0;
CurrentNumber.MaxValue = 1;
RelativeSizeAxes = Axes.X;
Children = new Drawable[]
{
background = new Box
{
Alpha = 0,
RelativeSizeAxes = Axes.Both
},
fill = new Box { RelativeSizeAxes = Axes.Y }
};
}
protected override void UpdateValue(float value)
{
fill.Width = value * UsableWidth;
}
protected override void OnUserChange(double value) => OnSeek?.Invoke(value);
}
}
| mit | C# |
ef86fdf4a50fb7de19cdc6c2679daa7ef40579fc | Fix merging of 5.0.2 | hazzik/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core | src/NHibernate/Impl/SessionIdLoggingContext.cs | src/NHibernate/Impl/SessionIdLoggingContext.cs | using System;
#if !NETSTANDARD2_0 && !NETCOREAPP2_0
using System.Runtime.Remoting.Messaging;
#else
using System.Threading;
#endif
namespace NHibernate.Impl
{
public class SessionIdLoggingContext : IDisposable
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
private static readonly Lazy<AsyncLocal<Guid?>> _currentSessionId =
new Lazy<AsyncLocal<Guid?>>(() => new AsyncLocal<Guid?>(), true);
#else
private const string LogicalCallContextVariableName = "__" + nameof(SessionIdLoggingContext) + "__";
#endif
private readonly Guid? _oldSessonId;
private readonly bool _hasChanged;
public SessionIdLoggingContext(Guid id)
{
if (id == Guid.Empty) return;
_oldSessonId = SessionId;
if (id == _oldSessonId) return;
_hasChanged = true;
SessionId = id;
}
/// <summary>
/// We always set the result to use an async local variable, on the face of it,
/// it looks like it is not a valid choice, since ASP.Net and WCF may decide to switch
/// threads on us. But, since SessionIdLoggingContext is only used inside NH calls, and since
/// NH calls are either async-await or fully synchronous, this isn't an issue for us.
/// In addition to that, attempting to match to the current context has proven to be performance hit.
/// </summary>
public static Guid? SessionId
{
get
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
return _currentSessionId.IsValueCreated ? _currentSessionId.Value.Value : null;
#else
return (Guid?) CallContext.LogicalGetData(LogicalCallContextVariableName);
#endif
}
set
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
_currentSessionId.Value.Value = value;
#else
CallContext.LogicalSetData(LogicalCallContextVariableName, value);
#endif
}
}
public void Dispose()
{
if (_hasChanged)
{
SessionId = _oldSessonId;
}
}
}
}
| using System;
#if !NETSTANDARD2_0 && !NETCOREAPP2_0
using System.Runtime.Remoting.Messaging;
#else
using System.Threading;
#endif
namespace NHibernate.Impl
{
public class SessionIdLoggingContext : IDisposable
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
private static readonly Lazy<AsyncLocal<Guid?>> _currentSessionId =
new Lazy<AsyncLocal<Guid?>>(() => new AsyncLocal<Guid?>(), true);
#else
private const string LogicalCallContextVariableName = "__" + nameof(SessionIdLoggingContext) + "__";
#endif
private readonly Guid? _oldSessonId;
private readonly bool _hasChanged;
public SessionIdLoggingContext(Guid id)
{
_tracking = id != Guid.Empty;
if (!_tracking)
{
return;
}
_oldSessonId = SessionId;
_hasChanged = _oldSessonId != id;
if (_hasChanged)
{
SessionId = id;
}
}
/// <summary>
/// We always set the result to use an async local variable, on the face of it,
/// it looks like it is not a valid choice, since ASP.Net and WCF may decide to switch
/// threads on us. But, since SessionIdLoggingContext is only used inside NH calls, and since
/// NH calls are either async-await or fully synchronous, this isn't an issue for us.
/// In addition to that, attempting to match to the current context has proven to be performance hit.
/// </summary>
public static Guid? SessionId
{
get
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
return _currentSessionId.IsValueCreated ? _currentSessionId.Value.Value : null;
#else
return (Guid?) CallContext.LogicalGetData(LogicalCallContextVariableName);
#endif
}
set
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
_currentSessionId.Value.Value = value;
#else
CallContext.LogicalSetData(LogicalCallContextVariableName, value);
#endif
}
}
public void Dispose()
{
if (_hasChanged)
{
SessionId = _oldSessonId;
}
}
}
}
| lgpl-2.1 | C# |
2b0caeb056ccc42353f8d6c93edaccd5c747cb3d | Fix comparison | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Tools/VSWhere/VSWhereTasks.cs | source/Nuke.Common/Tools/VSWhere/VSWhereTasks.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Common.IO;
using Nuke.Common.Tooling;
using Nuke.Common.Utilities;
namespace Nuke.Common.Tools.VSWhere
{
partial class VSWhereTasks
{
public const string VcComponent = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64";
public const string MsBuildComponent = "Microsoft.Component.MSBuild";
public const string NetCoreComponent = "Microsoft.Net.Core.Component.SDK";
private static List<VSWhereResult> GetResult(IProcess process, VSWhereSettings toolSettings)
{
// RESHARPER: unintentional reference comparison
if (!(toolSettings.UTF8 ?? false) || toolSettings.Format.Equals(VSWhereFormat.json) || toolSettings.Property != null)
return null;
var output = process.Output.EnsureOnlyStd().Select(x => x.Text).JoinNewLine();
return SerializationTasks.JsonDeserialize<VSWhereResult[]>(output).ToList();
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Common.IO;
using Nuke.Common.Tooling;
using Nuke.Common.Utilities;
namespace Nuke.Common.Tools.VSWhere
{
partial class VSWhereTasks
{
public const string VcComponent = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64";
public const string MsBuildComponent = "Microsoft.Component.MSBuild";
public const string NetCoreComponent = "Microsoft.Net.Core.Component.SDK";
private static List<VSWhereResult> GetResult(IProcess process, VSWhereSettings toolSettings)
{
if (!(toolSettings.UTF8 ?? false) || toolSettings.Format != VSWhereFormat.json || toolSettings.Property != null)
return null;
var output = process.Output.EnsureOnlyStd().Select(x => x.Text).JoinNewLine();
return SerializationTasks.JsonDeserialize<VSWhereResult[]>(output).ToList();
}
}
}
| mit | C# |
24cdc68f5976520fdeaf8b645edc266fce7606e8 | Refactor ComparisionReport.cs | Ackara/Daterpillar | src/Daterpillar.Core/Compare/ComparisonReport.cs | src/Daterpillar.Core/Compare/ComparisonReport.cs | using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Gigobyte.Daterpillar.Compare
{
public class ComparisonReport : IEnumerable<Discrepancy>
{
public ComparisonReport()
{
Discrepancies = new List<Discrepancy>();
}
public Outcomes Summary { get; set; }
public int TotalSourceTables { get; set; }
public int TotalTargetTables { get; set; }
public IList<Discrepancy> Discrepancies { get; set; }
public IEnumerator<Discrepancy> GetEnumerator()
{
return Discrepancies.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Summarize()
{
if (Discrepancies.Count == 0)
{
Summary = Outcomes.Equal;
}
}
}
} | using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Gigobyte.Daterpillar.Compare
{
[DataContract]
public class ComparisonReport : IEnumerable<Discrepancy>
{
public Counter Counters;
[DataMember]
public Outcome Summary { get; set; }
[DataMember]
public IList<Discrepancy> Discrepancies { get; set; }
public IEnumerator<Discrepancy> GetEnumerator()
{
foreach (var item in Discrepancies) { yield return item; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Counter
{
public int SourceTables;
public int DestTables;
}
}
} | mit | C# |
449fd1d52bd1616b70a115890d6a0987d261c407 | Switch AspNet middleware over to using Authorizer | peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype | src/Glimpse.Host.Web.AspNet/GlimpseMiddleware.cs | src/Glimpse.Host.Web.AspNet/GlimpseMiddleware.cs | using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Web;
using System;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
private readonly MasterRequestRuntime _runtime;
private readonly ISettings _settings;
private readonly IContextData<MessageContext> _contextData;
public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider)
: this(innerNext, serviceProvider, null)
{
}
public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider, Func<IHttpContext, bool> shouldRun)
{
_innerNext = innerNext;
_runtime = new MasterRequestRuntime(serviceProvider);
_contextData = new ContextData<MessageContext>();
// TODO: Need to find a way/better place for
var settings = new Settings();
if (shouldRun != null)
{
settings.ShouldProfile = context => shouldRun((HttpContext)context);
}
_settings = settings;
}
// TODO: Look at pushing the workings of this into MasterRequestRuntime
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context, _settings);
if (_runtime.Authorized(newContext))
{
// TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first
_contextData.Value = new MessageContext {Id = Guid.NewGuid(), Type = "Request"};
await _runtime.Begin(newContext);
var handler = (IRequestHandler) null;
if (_runtime.TryGetHandle(newContext, out handler))
{
await handler.Handle(newContext);
}
else
{
await _innerNext(context);
}
// TODO: This doesn't work correctly :( (headers)
await _runtime.End(newContext);
}
else
{
await _innerNext(context);
}
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Web;
using System;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
private readonly MasterRequestRuntime _runtime;
private readonly ISettings _settings;
private readonly IContextData<MessageContext> _contextData;
public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider)
: this(innerNext, serviceProvider, null)
{
}
public GlimpseMiddleware(RequestDelegate innerNext, IServiceProvider serviceProvider, Func<IHttpContext, bool> shouldRun)
{
_innerNext = innerNext;
_runtime = new MasterRequestRuntime(serviceProvider);
_contextData = new ContextData<MessageContext>();
// TODO: Need to find a way/better place for
var settings = new Settings();
if (shouldRun != null)
{
settings.ShouldProfile = context => shouldRun((HttpContext)context);
}
_settings = settings;
}
// TODO: Look at pushing the workings of this into MasterRequestRuntime
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context, _settings);
// TODO: This is the wrong place for this, AgentRuntime isn't garenteed to execute first
_contextData.Value = new MessageContext { Id = Guid.NewGuid(), Type = "Request" };
await _runtime.Begin(newContext);
var handler = (IRequestHandler)null;
if (_runtime.TryGetHandle(newContext, out handler))
{
await handler.Handle(newContext);
}
else
{
await _innerNext(context);
}
// TODO: This doesn't work correctly :( (headers)
await _runtime.End(newContext);
}
}
} | mit | C# |
bd3d935d8f82c5de62dc2308ab8183405b9cb7c8 | Fix Issues #3 | linezero/NETCoreBBS,linezero/NETCoreBBS | src/NetCoreBBS/Views/Shared/_PagerPartial.cshtml | src/NetCoreBBS/Views/Shared/_PagerPartial.cshtml | @{
var pageindex = Convert.ToInt32(ViewBag.PageIndex);
var pagecount = Convert.ToInt32(ViewBag.PageCount);
var path = Context.Request.Path.Value;
var query = string.Empty;
var querys = Context.Request.Query;
foreach (var item in querys)
{
if (!item.Key.Equals("page"))
{
query += $"{item.Key}={item.Value}&";
}
}
query = query == string.Empty ? "?" : "?" + query;
path += query;
var pagestart = pageindex - 2 > 0 ? pageindex - 2 : 1;
var pageend = pagestart + 5 >= pagecount ? pagecount : pagestart + 5;
}
<ul class="pagination">
<li class="prev previous_page @(pageindex == 1 ? "disabled" : "")">
<a href="@(pageindex==1?"#":$"{path}page={pageindex - 1}")">← 上一页</a>
</li>
<li @(pageindex == 1 ? "class=active" : "")><a rel="start" href="@(path)page=1">1</a></li>
@if (pagestart > 2)
{
<li class="disabled"><a href="#">…</a></li>
}
@for (int i = pagestart; i < pageend; i++)
{
if (i > 1)
{
<li @(pageindex == i ? "class=active" : "")><a rel="next" href="@(path)page=@i">@i</a></li>
}
}
@if (pageend < pagecount)
{
<li class="disabled"><a href="#">…</a></li>
}
@if (pagecount > 1)
{
<li @(pageindex == pagecount ? "class=active" : "")><a rel="end" href="@(path)page=@pagecount">@pagecount</a></li>
}
<li class="next next_page @(pageindex==pagecount?"disabled":"")">
<a rel="next" href="@(pageindex==pagecount?"#":$"{path}page={pageindex + 1}")">下一页 →</a>
</li>
</ul> | @{
var pageindex = Convert.ToInt32(ViewBag.PageIndex);
var pagecount = Convert.ToInt32(ViewBag.PageCount);
var path = Context.Request.Path.Value;
var query = string.Empty;
var querys = Context.Request.Query;
foreach (var item in querys)
{
if (!item.Key.Equals("page"))
{
query += $"{item.Key}={item.Value}&";
}
}
query = query == string.Empty ? "?" : "?" + query;
path += query;
var pagestart = pageindex - 2 > 0 ? pageindex - 2 : 1;
var pageend = pagestart + 5 >= pagecount ? pagecount : pagestart + 5;
}
<ul class="pagination">
<li class="prev previous_page @(pageindex == 1 ? "disabled" : "")">
<a href="@(pageindex==1?"#":$"{path}page={pageindex - 1}")">← 上一页</a>
</li>
<li @(pageindex == 1 ? "class=active" : "")><a rel="start" href="@(path)page=1">1</a></li>
@if (pagestart > 1)
{
<li class="disabled"><a href="#">…</a></li>
}
@for (int i = pagestart; i < pageend; i++)
{
if (i > 1)
{
<li @(pageindex == i ? "class=active" : "")><a rel="next" href="@(path)page=@i">@i</a></li>
}
}
@if (pageend < pagecount)
{
<li class="disabled"><a href="#">…</a></li>
}
@if (pagecount > 1)
{
<li @(pageindex == pagecount ? "class=active" : "")><a rel="end" href="@(path)page=@pagecount">@pagecount</a></li>
}
<li class="next next_page @(pageindex==pagecount?"disabled":"")">
<a rel="next" href="@(pageindex==pagecount?"#":$"{path}page={pageindex + 1}")">下一页 →</a>
</li>
</ul> | mit | C# |
323a8089acd78e5af41ec483818fbe8567e7daeb | rename response | guitarrapc/AzureFunctionsIntroduction | src/PreCompileEnvironmentVariables/MyFunction.cs | src/PreCompileEnvironmentVariables/MyFunction.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
namespace PreCompileEnvironmentVariables
{
public class MyFunction
{
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Webhook was triggered!");
var appKey = "FooKey";
var appValue = Environment.GetEnvironmentVariable(appKey);
log.Info($"App Setting. Key : {appKey}, Value : {appValue}");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
if (data.first == null || data.last == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Please pass first/last properties in the input object"
});
}
log.Info("Hello world");
return req.CreateResponse(HttpStatusCode.OK, new
{
hello = $"Hello World. {data.first} {data.last}!"
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
namespace PreCompileEnvironmentVariables
{
public class MyFunction
{
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Webhook was triggered!");
var appKey = "FooKey";
var appValue = Environment.GetEnvironmentVariable(appKey);
log.Info($"App Setting. Key : {appKey}, Value : {appValue}");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
if (data.first == null || data.last == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Please pass first/last properties in the input object"
});
}
log.Info("Hello world");
return req.CreateResponse(HttpStatusCode.OK, new
{
hello = $"Hello World!! {data.first} {data.last}!"
});
}
}
}
| mit | C# |
830afe52096961bde1f33201f63e376c654811ce | Make spinner blueprint update values more frequently. Also handle right-click | ppy/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,ppy/osu,peppy/osu-new | osu.Game.Rulesets.Osu/Edit/Blueprints/Spinners/SpinnerPlacementBlueprint.cs | osu.Game.Rulesets.Osu/Edit/Blueprints/Spinners/SpinnerPlacementBlueprint.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.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osuTK;
using osuTK.Input;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece { Alpha = 0.5f };
}
protected override void Update()
{
base.Update();
if (isPlacingEnd)
HitObject.EndTime = Math.Max(HitObject.StartTime, EditorClock.CurrentTime);
piece.UpdateFrom(HitObject);
}
protected override bool OnMouseDown(MouseDownEvent e)
{
if (isPlacingEnd)
{
if (e.Button != MouseButton.Right)
return false;
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
if (e.Button != MouseButton.Left)
return false;
BeginPlacement();
isPlacingEnd = true;
}
return true;
}
public override void UpdatePosition(Vector2 screenSpacePosition)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece { Alpha = 0.5f };
}
protected override void Update()
{
base.Update();
piece.UpdateFrom(HitObject);
}
protected override bool OnClick(ClickEvent e)
{
if (isPlacingEnd)
{
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
isPlacingEnd = true;
piece.FadeTo(1f, 150, Easing.OutQuint);
BeginPlacement();
}
return true;
}
public override void UpdatePosition(Vector2 screenSpacePosition)
{
}
}
}
| mit | C# |
6c5cafe41599d159808b5437c40b7924385715ad | update levy monthly run date whilst investigation continues with payments | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ImportLevyDeclarationsJob
{
private readonly IMessageSession _messageSession;
public ImportLevyDeclarationsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 15 24 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ImportLevyDeclarationsCommand());
}
}
} | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ImportLevyDeclarationsJob
{
private readonly IMessageSession _messageSession;
public ImportLevyDeclarationsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 15 23 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ImportLevyDeclarationsCommand());
}
}
} | mit | C# |
c893a67f60ff651fefb250e78410884e65a13d04 | Update Timer for Levy to 23rd | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs | src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ImportLevyDeclarationsJob
{
private readonly IMessageSession _messageSession;
public ImportLevyDeclarationsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 15 23 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ImportLevyDeclarationsCommand());
}
}
} | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ImportLevyDeclarationsJob
{
private readonly IMessageSession _messageSession;
public ImportLevyDeclarationsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ImportLevyDeclarationsCommand());
}
}
} | mit | C# |
bea152a5e4228158474081373ac2140c19c1bbaf | Update AboutViewModel.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/AboutViewModel.cs | WalletWasabi.Fluent/ViewModels/AboutViewModel.cs | using System;
using System.IO;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using AutoNotify;
namespace WalletWasabi.Fluent.ViewModels
{
[NavigationMetaData(
Searchable = true,
Title = "About Wasabi",
Caption = "Displays all the current info about the app",
IconName = "info_regular",
Order = 4,
Category = "General",
Keywords = new [] { "About", "Software","Version", "Source", "Code", "Github", "Status", "Stats", "Tor", "Onion", "Bug", "Report", "FAQ","Questions,", "Docs","Documentation", "Link", "Links"," Help" },
NavBarPosition = NavBarPosition.None)]
public partial class AboutViewModel : RoutableViewModel
{
[AutoNotify]
private bool _test;
public AboutViewModel()
{
OpenBrowserCommand = ReactiveCommand.CreateFromTask<string>(IoHelpers.OpenBrowserAsync);
var interaction = new Interaction<Unit, Unit>();
interaction.RegisterHandler(
async x =>
x.SetOutput(
await new AboutAdvancedInfoViewModel().ShowDialogAsync()));
AboutAdvancedInfoDialogCommand = ReactiveCommand.CreateFromTask(
execute: async () => await interaction.Handle(Unit.Default).ToTask());
OpenBrowserCommand.ThrownExceptions
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
public override NavigationTarget DefaultTarget => NavigationTarget.DialogScreen;
public ICommand AboutAdvancedInfoDialogCommand { get; }
public ReactiveCommand<string, Unit> OpenBrowserCommand { get; }
public Version ClientVersion => Constants.ClientVersion;
public string ClearnetLink => "https://wasabiwallet.io/";
public string TorLink => "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion";
public string SourceCodeLink => "https://github.com/zkSNACKs/WalletWasabi/";
public string StatusPageLink => "https://stats.uptimerobot.com/YQqGyUL8A7";
public string UserSupportLink => "https://www.reddit.com/r/WasabiWallet/";
public string BugReportLink => "https://github.com/zkSNACKs/WalletWasabi/issues/";
public string FAQLink => "https://docs.wasabiwallet.io/FAQ/";
public string DocsLink => "https://docs.wasabiwallet.io/";
public string License => "https://github.com/zkSNACKs/WalletWasabi/blob/master/LICENSE.md";
}
} | using System;
using System.IO;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Windows.Input;
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using AutoNotify;
namespace WalletWasabi.Fluent.ViewModels
{
[NavigationMetaData(Searchable = true)]
public partial class AboutViewModel : RoutableViewModel
{
[AutoNotify]
private bool _test;
public AboutViewModel()
{
OpenBrowserCommand = ReactiveCommand.CreateFromTask<string>(IoHelpers.OpenBrowserAsync);
var interaction = new Interaction<Unit, Unit>();
interaction.RegisterHandler(
async x =>
x.SetOutput(
await new AboutAdvancedInfoViewModel().ShowDialogAsync()));
AboutAdvancedInfoDialogCommand = ReactiveCommand.CreateFromTask(
execute: async () => await interaction.Handle(Unit.Default).ToTask());
OpenBrowserCommand.ThrownExceptions
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
public override NavigationTarget DefaultTarget => NavigationTarget.DialogScreen;
public ICommand AboutAdvancedInfoDialogCommand { get; }
public ReactiveCommand<string, Unit> OpenBrowserCommand { get; }
public Version ClientVersion => Constants.ClientVersion;
public string ClearnetLink => "https://wasabiwallet.io/";
public string TorLink => "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion";
public string SourceCodeLink => "https://github.com/zkSNACKs/WalletWasabi/";
public string StatusPageLink => "https://stats.uptimerobot.com/YQqGyUL8A7";
public string UserSupportLink => "https://www.reddit.com/r/WasabiWallet/";
public string BugReportLink => "https://github.com/zkSNACKs/WalletWasabi/issues/";
public string FAQLink => "https://docs.wasabiwallet.io/FAQ/";
public string DocsLink => "https://docs.wasabiwallet.io/";
public string License => "https://github.com/zkSNACKs/WalletWasabi/blob/master/LICENSE.md";
}
} | mit | C# |
cfeb6a12825a04203ad997940be541d17be9c6f7 | Allow channel to be updated post-construction more than once | ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework/Audio/Track/BassAmplitudes.cs | osu.Framework/Audio/Track/BassAmplitudes.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 ManagedBass;
namespace osu.Framework.Audio.Track
{
/// <summary>
/// Computes and caches amplitudes for a bass channel.
/// </summary>
public class BassAmplitudes
{
private int channel;
private TrackAmplitudes currentAmplitudes;
public TrackAmplitudes CurrentAmplitudes => currentAmplitudes;
private const int size = 256; // should be half of the FFT length provided to ChannelGetData.
private static readonly TrackAmplitudes empty = new TrackAmplitudes { FrequencyAmplitudes = new float[size] };
public BassAmplitudes(int channel)
{
this.channel = channel;
setEmpty();
}
public void SetChannel(int channel)
{
this.channel = channel;
}
public void Update()
{
int ch = channel;
if (ch == 0)
return;
bool active = Bass.ChannelIsActive(ch) == PlaybackState.Playing;
var leftChannel = active ? Bass.ChannelGetLevelLeft(ch) / 32768f : -1;
var rightChannel = active ? Bass.ChannelGetLevelRight(ch) / 32768f : -1;
if (leftChannel >= 0 && rightChannel >= 0)
{
currentAmplitudes.LeftChannel = leftChannel;
currentAmplitudes.RightChannel = rightChannel;
float[] tempFrequencyData = new float[size];
Bass.ChannelGetData(ch, tempFrequencyData, (int)DataFlags.FFT512);
currentAmplitudes.FrequencyAmplitudes = tempFrequencyData;
}
else
setEmpty();
}
private void setEmpty()
{
currentAmplitudes.LeftChannel = 0;
currentAmplitudes.RightChannel = 0;
currentAmplitudes.FrequencyAmplitudes = empty.FrequencyAmplitudes;
}
}
}
| // 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.
// 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 ManagedBass;
namespace osu.Framework.Audio.Track
{
/// <summary>
/// Computes and caches amplitudes for a bass channel.
/// </summary>
public class BassAmplitudes
{
private int channel;
private TrackAmplitudes currentAmplitudes;
public TrackAmplitudes CurrentAmplitudes => currentAmplitudes;
private const int size = 256; // should be half of the FFT length provided to ChannelGetData.
private static readonly TrackAmplitudes empty = new TrackAmplitudes { FrequencyAmplitudes = new float[size] };
public BassAmplitudes(int channel)
{
this.channel = channel;
setEmpty();
}
public void SetChannel(int channel)
{
if (this.channel != 0)
// just for simple thread safety. limitation can be easily removed later if required.
throw new InvalidOperationException("Can only set channel to non-zero value once");
if (channel == 0)
throw new ArgumentException("Channel must be non-zero", nameof(channel));
this.channel = channel;
}
public void Update()
{
if (channel == 0)
return;
bool active = Bass.ChannelIsActive(channel) == PlaybackState.Playing;
var leftChannel = active ? Bass.ChannelGetLevelLeft(channel) / 32768f : -1;
var rightChannel = active ? Bass.ChannelGetLevelRight(channel) / 32768f : -1;
if (leftChannel >= 0 && rightChannel >= 0)
{
currentAmplitudes.LeftChannel = leftChannel;
currentAmplitudes.RightChannel = rightChannel;
float[] tempFrequencyData = new float[size];
Bass.ChannelGetData(channel, tempFrequencyData, (int)DataFlags.FFT512);
currentAmplitudes.FrequencyAmplitudes = tempFrequencyData;
}
else
setEmpty();
}
private void setEmpty()
{
currentAmplitudes.LeftChannel = 0;
currentAmplitudes.RightChannel = 0;
currentAmplitudes.FrequencyAmplitudes = empty.FrequencyAmplitudes;
}
}
}
| mit | C# |
7304c094d3246bdc68d6223b22922fd58462f0b7 | remove using System from LR/Statement.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs | WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs | using NBitcoin.Secp256k1;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
public class Statement
{
public Statement(params Equation[] equations)
: this(equations as IEnumerable<Equation>)
{
}
public Statement(IEnumerable<Equation> equations)
{
// The equation matrix should not be jagged
Guard.NotNullOrEmpty(nameof(equations), equations);
var n = equations.First().Generators.Count();
Guard.True(nameof(equations), equations.All(e => e.Generators.Count() == n));
foreach (var generator in equations.SelectMany(equation => equation.Generators))
{
Guard.NotNull(nameof(generator), generator);
}
Equations = equations;
}
public IEnumerable<Equation> Equations { get; }
public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, IEnumerable<ScalarVector> allResponses)
{
// The responses matrix should match the generators in the equations and
// there should be once nonce per equation.
Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count());
Equations.CheckDimesions(allResponses);
return Equations.Zip(publicNonces, allResponses, (equation, r, s) => equation.Verify(r, challenge, s)).All(x => x);
}
public GroupElementVector SimulatePublicNonces(Scalar challenge, IEnumerable<ScalarVector> allGivenResponses)
{
// The responses matrix should match the generators in the equations and
Equations.CheckDimesions(allGivenResponses);
return new GroupElementVector(Enumerable.Zip(Equations, allGivenResponses, (e, r) => e.Simulate(challenge, r)));
}
}
}
| using NBitcoin.Secp256k1;
using System;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
public class Statement
{
public Statement(params Equation[] equations)
: this(equations as IEnumerable<Equation>)
{
}
public Statement(IEnumerable<Equation> equations)
{
// The equation matrix should not be jagged
Guard.NotNullOrEmpty(nameof(equations), equations);
var n = equations.First().Generators.Count();
Guard.True(nameof(equations), equations.All(e => e.Generators.Count() == n));
foreach (var generator in equations.SelectMany(equation => equation.Generators))
{
Guard.NotNull(nameof(generator), generator);
}
Equations = equations;
}
public IEnumerable<Equation> Equations { get; }
public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, IEnumerable<ScalarVector> allResponses)
{
// The responses matrix should match the generators in the equations and
// there should be once nonce per equation.
Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count());
Equations.CheckDimesions(allResponses);
return Equations.Zip(publicNonces, allResponses, (equation, r, s) => equation.Verify(r, challenge, s)).All(x => x);
}
public GroupElementVector SimulatePublicNonces(Scalar challenge, IEnumerable<ScalarVector> allGivenResponses)
{
// The responses matrix should match the generators in the equations and
Equations.CheckDimesions(allGivenResponses);
return new GroupElementVector(Enumerable.Zip(Equations, allGivenResponses, (e, r) => e.Simulate(challenge, r)));
}
}
}
| mit | C# |
7dc65ec9645e71bd790f5e157bf757ebfd6748c4 | Add missing required types | johnneijzen/osu,peppy/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,EVAST9919/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,UselessToucan/osu | osu.Game.Tests/Visual/Editor/TestSceneTimingScreen.cs | osu.Game.Tests/Visual/Editor/TestSceneTimingScreen.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editor
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ControlPointTable),
typeof(RowAttribute)
};
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Child = new TimingScreen();
}
}
}
| // 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.Framework.Allocation;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editor
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Child = new TimingScreen();
}
}
}
| mit | C# |
08b3bc222d79a8d2a846ee11c1e300832d91a9d6 | Revert "Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available" | peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu | osu.Game/Configuration/DevelopmentOsuConfigManager.cs | osu.Game/Configuration/DevelopmentOsuConfigManager.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.Platform;
using osu.Framework.Testing;
namespace osu.Game.Configuration
{
[ExcludeFromDynamicCompile]
public class DevelopmentOsuConfigManager : OsuConfigManager
{
protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");
public DevelopmentOsuConfigManager(Storage storage)
: base(storage)
{
}
}
}
| // 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.Platform;
using osu.Framework.Testing;
namespace osu.Game.Configuration
{
[ExcludeFromDynamicCompile]
public class DevelopmentOsuConfigManager : OsuConfigManager
{
protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");
public DevelopmentOsuConfigManager(Storage storage)
: base(storage)
{
LookupKeyBindings = _ => "unknown";
LookupSkinName = _ => "unknown";
}
}
}
| mit | C# |
37495c34faa7a02852934d2d9db0dab9e2492a66 | Fix possible nullreference | peppy/osu,johnneijzen/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,peppy/osu,peppy/osu-new,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,ZLima12/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,naoey/osu,DrabWeb/osu,ZLima12/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu | osu.Game/Beatmaps/ControlPoints/ControlPoint.cs | osu.Game/Beatmaps/ControlPoints/ControlPoint.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;
namespace osu.Game.Beatmaps.ControlPoints
{
public class ControlPoint : IComparable<ControlPoint>, IEquatable<ControlPoint>
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
public double Time;
public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);
/// <summary>
/// Whether this <see cref="ControlPoint"/> provides the same changes to gameplay as another <see cref="ControlPoint"/>.
/// </summary>
/// <param name="other">The <see cref="ControlPoint"/> to compare to.</param>
/// <returns>Whether this <see cref="ControlPoint"/> provides the same changes to gameplay as <paramref name="other"/>.</returns>
public virtual bool ChangeEquals(ControlPoint other) => !ReferenceEquals(null, other);
public bool Equals(ControlPoint other)
=> ChangeEquals(other)
&& !ReferenceEquals(null, other)
&& Time.Equals(other.Time);
}
}
| // 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;
namespace osu.Game.Beatmaps.ControlPoints
{
public class ControlPoint : IComparable<ControlPoint>, IEquatable<ControlPoint>
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
public double Time;
public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);
/// <summary>
/// Whether this <see cref="ControlPoint"/> provides the same changes to gameplay as another <see cref="ControlPoint"/>.
/// </summary>
/// <param name="other">The <see cref="ControlPoint"/> to compare to.</param>
/// <returns>Whether this <see cref="ControlPoint"/> provides the same changes to gameplay as <paramref name="other"/>.</returns>
public virtual bool ChangeEquals(ControlPoint other) => !ReferenceEquals(null, other);
public bool Equals(ControlPoint other)
=> ChangeEquals(other)
&& Time.Equals(other.Time);
}
}
| mit | C# |
db7330b5050bcbfef29fa04d5d6deb81423e15f0 | Change variable name | nwoedf/HandShapeVisualizationPlatform | HandShapeVisualizationPlatform/CSVDataSetModel.cs | HandShapeVisualizationPlatform/CSVDataSetModel.cs | // author: Tommy
// created time:6/24/2014 11:27:15 PM
// organizatioin:CURE lab, CUHK
// copyright: 2014-2015
// CLR: 4.0.30319.17929
// project link:https://github.com/huangfuyang/Sign-Language-with-Kinect
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HandShapeVisualizationPlatform {
/// <summary>
/// add summary here
/// </summary>
public class CSVDataSetModel : AbstractDataSetModel {
string pathName;
private const string RAW_DATA_TABLE_NAME = "Raw Data Table";
public CSVDataSetModel(string pathName) {
this.pathName = pathName;
}
public override void loadRawData() {
DataLoader.loadFromCSV(pathName, false, DataSet.Tables.Add(RAW_DATA_TABLE_NAME));
Console.WriteLine("Row: " + DataSet.Tables[RAW_DATA_TABLE_NAME].Rows.Count + "\tCol: " + DataSet.Tables[RAW_DATA_TABLE_NAME].Columns.Count);
}
public override void initDataSet() {
DataSet.Tables[RAW_DATA_TABLE_NAME].Columns[0].ColumnName = "Class";
}
public override void update() {
}
public DataTable getRawDataTable() {
return DataSet.Tables[RAW_DATA_TABLE_NAME];
}
}
} | // author: Tommy
// created time:6/24/2014 11:27:15 PM
// organizatioin:CURE lab, CUHK
// copyright: 2014-2015
// CLR: 4.0.30319.17929
// project link:https://github.com/huangfuyang/Sign-Language-with-Kinect
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HandShapeVisualizationPlatform {
/// <summary>
/// add summary here
/// </summary>
public class CSVDataSetModel : AbstractDataSetModel {
string pathName;
private const string rawDataTableName = "Raw Data Table";
public CSVDataSetModel(string pathName) {
this.pathName = pathName;
}
public override void loadRawData() {
DataLoader.loadFromCSV(pathName, false, DataSet.Tables.Add(rawDataTableName));
Console.WriteLine("Row: " + DataSet.Tables[rawDataTableName].Rows.Count + "\tCol: " + DataSet.Tables[rawDataTableName].Columns.Count);
}
public override void initDataSet() {
DataSet.Tables[rawDataTableName].Columns[0].ColumnName = "Class";
}
public override void update() {
}
public DataTable getRawDataTable() {
return DataSet.Tables[rawDataTableName];
}
}
} | apache-2.0 | C# |
ff44e6732f48dfb6091b6489a318fbb132adb5da | delete seed method | Xzq70r4/Organizer,Xzq70r4/Organizer,Xzq70r4/Organizer | Source/Organizer.Data/Migrations/Configuration.cs | Source/Organizer.Data/Migrations/Configuration.cs | namespace Organizer.Data.Migrations
{
using System.Data.Entity.Migrations;
using Microsoft.AspNet.Identity;
using Organizer.Models;
internal sealed class Configuration : DbMigrationsConfiguration<OrganizerDbContext>
{
private UserManager<User> userManager;
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
//TODO: false in production
this.AutomaticMigrationDataLossAllowed = true;
}
}
}
| namespace Organizer.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Organizer.Models;
internal sealed class Configuration : DbMigrationsConfiguration<OrganizerDbContext>
{
private UserManager<User> userManager;
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
//TODO: false in production
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(OrganizerDbContext context)
{
if (context.OraganizerTasks.Any())
{
return;
}
this.userManager = new UserManager<User>(new UserStore<User>(context));
this.SeedUsers(context);
this.SeedOrganizerTasks(context);
}
private void SeedUsers(OrganizerDbContext context)
{
var user = new User
{
UserName = "mava",
};
this.userManager.Create(user, "123456");
}
private void SeedOrganizerTasks(OrganizerDbContext context)
{
var user = context.Users.FirstOrDefault();
for (int i = 0; i < 10; i++)
{
var task = new OrganizerTask
{
Description = "dsadsadsadsadsadadadsa",
Priority = Priority.Urgent,
Location = "u nas",
ReleaseTime = DateTime.Now,
UserId = user.Id
};
context.OraganizerTasks.Add(task);
context.SaveChanges();
}
}
}
}
| mit | C# |
a20f5baa4721d769db30158ce396635de8955a8d | Remove unused using | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/Controls/InfoMessage.axaml.cs | WalletWasabi.Fluent/Controls/InfoMessage.axaml.cs | using Avalonia;
using Avalonia.Controls;
namespace WalletWasabi.Fluent.Controls
{
public class InfoMessage : Label
{
public static readonly StyledProperty<int> IconSizeProperty =
AvaloniaProperty.Register<ContentArea, int>(nameof(IconSize), 20);
public int IconSize
{
get => GetValue(IconSizeProperty);
set => SetValue(IconSizeProperty, value);
}
}
} | using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
namespace WalletWasabi.Fluent.Controls
{
public class InfoMessage : Label
{
public static readonly StyledProperty<int> IconSizeProperty =
AvaloniaProperty.Register<ContentArea, int>(nameof(IconSize), 20);
public int IconSize
{
get => GetValue(IconSizeProperty);
set => SetValue(IconSizeProperty, value);
}
}
} | mit | C# |
9290253072ce61788f9b19cab64a8cfee85de6f4 | Delete Hello console | krisdimova/kasskata-Lessons | 01.Intro/Intro.cs | 01.Intro/Intro.cs | namespace _01.Intro
{
using System;
class Intro
{
static void Main()
{
}
}
}
| namespace _01.Intro
{
using System;
class Intro
{
static void Main()
{
Console.WriteLine("Hello");
}
}
}
| mit | C# |
ea9d46b2372caa2f549e2ecfe9ee2af20fe02891 | Add recaptcha tag helper. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Views/_ViewImports.cshtml | src/CompetitionPlatform/Views/_ViewImports.cshtml | @using CompetitionPlatform
@using CompetitionPlatform.Models
@using CompetitionPlatform.Models.AccountViewModels
@using CompetitionPlatform.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha
| @using CompetitionPlatform
@using CompetitionPlatform.Models
@using CompetitionPlatform.Models.AccountViewModels
@using CompetitionPlatform.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
| mit | C# |
6efecc45ee7cf420f86e62823b2b791995d0b673 | Hide the implementation details | joemcbride/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet | src/GraphQL/Subscription/ISubscriptionExecuter.cs | src/GraphQL/Subscription/ISubscriptionExecuter.cs | using System.Threading.Tasks;
namespace GraphQL.Subscription
{
public interface ISubscriptionExecuter
{
Task<SubscriptionExecutionResult> SubscribeAsync(ExecutionOptions config);
}
}
| using System.Threading.Tasks;
using GraphQL.Execution;
namespace GraphQL.Subscription
{
public interface ISubscriptionExecuter : IDocumentExecuter
{
Task<SubscriptionExecutionResult> SubscribeAsync(ExecutionOptions config);
}
}
| mit | C# |
32f9c6a2e2347b1fcc12553d90cc2038deb418e3 | Create ShowOnGitHubCmd command in ctor | punker76/simple-music-player | src/SimpleMusicPlayer/ViewModels/MainViewModel.cs | src/SimpleMusicPlayer/ViewModels/MainViewModel.cs | using System.Linq;
using System.Windows;
using System.Windows.Input;
using ReactiveUI;
using SimpleMusicPlayer.Core;
using SimpleMusicPlayer.Core.Interfaces;
using SimpleMusicPlayer.Core.Player;
using TinyIoC;
namespace SimpleMusicPlayer.ViewModels
{
public class MainViewModel : ReactiveObject, IKeyHandler
{
public MainViewModel()
{
var container = TinyIoCContainer.Current;
this.PlayerSettings = container.Resolve<PlayerSettings>().Update();
this.CustomWindowPlacementSettings = new CustomWindowPlacementSettings(this.PlayerSettings.MainWindow);
this.PlayerEngine = container.Resolve<PlayerEngine>().Configure();
this.PlayListsViewModel = new PlayListsViewModel();
this.PlayControlInfoViewModel = new PlayControlInfoViewModel(this);
this.ShowOnGitHubCmd = new DelegateCommand(this.ShowOnGitHub, () => true);
}
public CustomWindowPlacementSettings CustomWindowPlacementSettings { get; private set; }
public PlayerEngine PlayerEngine { get; private set; }
public PlayerSettings PlayerSettings { get; private set; }
public PlayControlInfoViewModel PlayControlInfoViewModel { get; private set; }
public PlayListsViewModel PlayListsViewModel { get; private set; }
public ICommand ShowOnGitHubCmd { get; }
private void ShowOnGitHub()
{
System.Diagnostics.Process.Start("https://github.com/punker76/simple-music-player");
}
public void ShutDown()
{
foreach (var w in Application.Current.Windows.OfType<Window>())
{
w.Close();
}
this.PlayerSettings.Save();
this.PlayerEngine.CleanUp();
this.PlayListsViewModel.SavePlayList();
}
public bool HandleKeyDown(Key key)
{
if (this.PlayControlInfoViewModel.PlayControlViewModel.HandleKeyDown(key))
{
return true;
}
return false;
}
}
} | using System.Linq;
using System.Windows;
using System.Windows.Input;
using ReactiveUI;
using SimpleMusicPlayer.Core;
using SimpleMusicPlayer.Core.Interfaces;
using SimpleMusicPlayer.Core.Player;
using TinyIoC;
namespace SimpleMusicPlayer.ViewModels
{
public class MainViewModel : ReactiveObject, IKeyHandler
{
private ICommand showOnGitHubCmd;
public MainViewModel()
{
var container = TinyIoCContainer.Current;
this.PlayerSettings = container.Resolve<PlayerSettings>().Update();
this.CustomWindowPlacementSettings = new CustomWindowPlacementSettings(this.PlayerSettings.MainWindow);
this.PlayerEngine = container.Resolve<PlayerEngine>().Configure();
this.PlayListsViewModel = new PlayListsViewModel();
this.PlayControlInfoViewModel = new PlayControlInfoViewModel(this);
}
public CustomWindowPlacementSettings CustomWindowPlacementSettings { get; private set; }
public PlayerEngine PlayerEngine { get; private set; }
public PlayerSettings PlayerSettings { get; private set; }
public PlayControlInfoViewModel PlayControlInfoViewModel { get; private set; }
public PlayListsViewModel PlayListsViewModel { get; private set; }
public ICommand ShowOnGitHubCmd
{
get { return this.showOnGitHubCmd ?? (this.showOnGitHubCmd = new DelegateCommand(this.ShowOnGitHub, () => true)); }
}
private void ShowOnGitHub()
{
System.Diagnostics.Process.Start("https://github.com/punker76/simple-music-player");
}
public void ShutDown()
{
foreach (var w in Application.Current.Windows.OfType<Window>())
{
w.Close();
}
this.PlayerSettings.Save();
this.PlayerEngine.CleanUp();
this.PlayListsViewModel.SavePlayList();
}
public bool HandleKeyDown(Key key)
{
if (this.PlayControlInfoViewModel.PlayControlViewModel.HandleKeyDown(key))
{
return true;
}
return false;
}
}
} | mit | C# |
6f41916241ef59f86d45ffebed58557674b64878 | Remove unused code | dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP | src/DotNetCore.CAP.AmazonSQS/TopicNormalizer.cs | src/DotNetCore.CAP.AmazonSQS/TopicNormalizer.cs | using System;
namespace DotNetCore.CAP.AmazonSQS
{
public static class TopicNormalizer
{
public static string NormalizeForAws(this string origin)
{
if (origin.Length > 256)
{
throw new ArgumentOutOfRangeException(nameof(origin) + " character string length must between 1~256!");
}
return origin.Replace(".", "-").Replace(":", "_");
}
}
}
| using System;
namespace DotNetCore.CAP.AmazonSQS
{
public static class TopicNormalizer
{
public static string NormalizeForAws(this string origin)
{
if (origin.Length > 256)
{
throw new ArgumentOutOfRangeException(nameof(origin) + " character string length must between 1~256!");
}
return origin.Replace(".", "-").Replace(":", "_");
}
public static string DeNormalizeForAws(this string origin)
{
return origin.Replace("-", ".").Replace("_", ":");
}
}
}
| mit | C# |
79fac317080b855ba010464b0c7e16a59b736360 | Rename StripeDefaultCard to DefaultCard on Recipient | stripe/stripe-dotnet,richardlawley/stripe.net | src/Stripe.net/Entities/Recipients/Recipient.cs | src/Stripe.net/Entities/Recipients/Recipient.cs | namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class Recipient : StripeEntity, IHasId, IHasMetadata, IHasObject
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("active_account")]
public BankAccount ActiveAccount { get; set; }
[JsonProperty("cards")]
public StripeList<Card> CardList { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(DateTimeConverter))]
public DateTime Created { get; set; }
#region Expandable Default Card
public string DefaultCardId { get; set; }
[JsonIgnore]
public Card DefaultCard { get; set; }
[JsonProperty("default_card")]
internal object InternalDefaultCard
{
set
{
StringOrObject<Card>.Map(value, s => this.DefaultCardId = s, o => this.DefaultCard = o);
}
}
#endregion
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("livemode")]
public bool Livemode { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("migrated_to")]
public string MigratedTo { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("rolled_back_from")]
public string RolledBackFrom { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("verified")]
public bool Verified { get; set; }
}
}
| namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class Recipient : StripeEntity, IHasId, IHasMetadata, IHasObject
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("active_account")]
public BankAccount ActiveAccount { get; set; }
[JsonProperty("cards")]
public StripeList<Card> CardList { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(DateTimeConverter))]
public DateTime Created { get; set; }
#region Expandable Default Card
public string StripeDefaultCardId { get; set; }
[JsonIgnore]
public Card StripeDefaultCard { get; set; }
[JsonProperty("default_card")]
internal object InternalDefaultCard
{
set
{
StringOrObject<Card>.Map(value, s => this.StripeDefaultCardId = s, o => this.StripeDefaultCard = o);
}
}
#endregion
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("livemode")]
public bool Livemode { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("migrated_to")]
public string MigratedTo { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("rolled_back_from")]
public string RolledBackFrom { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("verified")]
public bool Verified { get; set; }
}
}
| apache-2.0 | C# |
a787c7805012c53c7d5b876a04ee2d8a7ef26a52 | modify KlaviyoEvent.cs | zxed/net-klaviyo | thrunk/klaviyo.net/klaviyo.net/KlaviyoEvent.cs | thrunk/klaviyo.net/klaviyo.net/KlaviyoEvent.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace klaviyo.net
{
[DataContract]
public class KlaviyoEvent
{
public KlaviyoEvent()
{
CustomerProperties = new CustomerProperties();
Properties = new Properties();
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = DateTime.Now.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
Time = Math.Round(ts.TotalMilliseconds / 1000, 0).ToString();
}
[DataMember(Name = "token")]
public string Token { get; set; }
[DataMember(Name = "event")]
public string Type { get; set; }
[DataMember(Name = "customer_properties")]
public virtual CustomerProperties CustomerProperties { get; set; }
[DataMember(Name = "properties")]
public Properties Properties { get; set; }
[DataMember(Name = "Item Categories")]
public List<string> Categories { get; set; }
[DataMember(Name = "Unique Item Categories")]
public List<string> UniqueCategories { get; set; }
[DataMember(Name = "Item Count")]
public int ItemCount { get; set; }
[DataMember(Name = "time")]
public string Time { get; private set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace klaviyo.net
{
[DataContract]
public class KlaviyoEvent
{
public KlaviyoEvent()
{
CustomerProperties = new CustomerProperties();
Properties = new Properties();
}
[DataMember(Name = "token")]
public string Token { get; set; }
[DataMember(Name = "event")]
public string Type { get; set; }
[DataMember(Name = "customer_properties")]
public virtual CustomerProperties CustomerProperties { get; set; }
[DataMember(Name = "properties")]
public Properties Properties { get; set; }
[DataMember(Name = "Item Categories")]
public List<string> Categories { get; set; }
[DataMember(Name = "Unique Item Categories")]
public List<string> UniqueCategories { get; set; }
[DataMember(Name = "Item Count")]
public int ItemCount { get; set; }
[DataMember(Name = "time")]
public double Time { get; set; }
}
} | mit | C# |
b5fb7b14f50ebb64222fa2cb76d962f988b202ed | Fix nullable annotation in IsNullOrWhiteSpace | tom-englert/TomsToolbox | src/TomsToolbox.Essentials/NullabeExtensions.cs | src/TomsToolbox.Essentials/NullabeExtensions.cs | namespace TomsToolbox.Essentials
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
/// <summary>
/// Replacements for some common methods with extra nullable annotations.
/// </summary>
public static class NullableExtensions
{
/// <summary>Indicates whether the specified string is <see langword="null" /> or an empty string ("").</summary>
/// <param name="value">The string to test.</param>
/// <returns>
/// <see langword="true" /> if the <paramref name="value" /> parameter is <see langword="null" /> or an empty string (""); otherwise, <see langword="false" />.
/// </returns>
public static bool IsNullOrEmpty([NotNullWhen(false)] this string? value)
{
return string.IsNullOrEmpty(value);
}
/// <summary>Indicates whether a specified string is <see langword="null" />, empty, or consists only of white-space characters.</summary>
/// <param name="value">The string to test.</param>
/// <returns>
/// <see langword="true" /> if the <paramref name="value" /> parameter is <see langword="null" /> or <see cref="F:System.String.Empty" />, or if <paramref name="value" /> consists exclusively of white-space characters.
/// </returns>
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? value)
{
return string.IsNullOrWhiteSpace(value);
}
/// <summary>
/// Filters a sequence of values based on their nullness.
/// </summary>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to filter.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains all elements from the input sequence that are not null.
/// </returns>
public static IEnumerable<TSource> ExceptNullItems<TSource>(this IEnumerable<TSource?> source) where TSource : class
{
return source.Where(i => i != null)!;
}
}
}
| namespace TomsToolbox.Essentials
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
/// <summary>
/// Replacements for some common methods with extra nullable annotations.
/// </summary>
public static class NullableExtensions
{
/// <summary>Indicates whether the specified string is <see langword="null" /> or an empty string ("").</summary>
/// <param name="value">The string to test.</param>
/// <returns>
/// <see langword="true" /> if the <paramref name="value" /> parameter is <see langword="null" /> or an empty string (""); otherwise, <see langword="false" />.
/// </returns>
public static bool IsNullOrEmpty([NotNullWhen(false)] this string? value)
{
return string.IsNullOrEmpty(value);
}
/// <summary>Indicates whether a specified string is <see langword="null" />, empty, or consists only of white-space characters.</summary>
/// <param name="value">The string to test.</param>
/// <returns>
/// <see langword="true" /> if the <paramref name="value" /> parameter is <see langword="null" /> or <see cref="F:System.String.Empty" />, or if <paramref name="value" /> consists exclusively of white-space characters.
/// </returns>
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string value)
{
return string.IsNullOrWhiteSpace(value);
}
/// <summary>
/// Filters a sequence of values based on their nullness.
/// </summary>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to filter.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains all elements from the input sequence that are not null.
/// </returns>
public static IEnumerable<TSource> ExceptNullItems<TSource>(this IEnumerable<TSource?> source) where TSource : class
{
return source.Where(i => i != null)!;
}
}
}
| mit | C# |
28f11debcf6d18d06d136984714b33b5375a382f | Add constructor | Distant/MetroTileEditor | Data/BlockData.cs | Data/BlockData.cs | using System;
using UnityEngine;
namespace MetroTileEditor
{
[Serializable]
public class BlockData
{
public string blockType = "basic_cube";
public bool placed;
public string[] materialIDs;
public bool breakable;
public bool isTriggerOnly;
public bool excludeFromMesh;
[Range(0, 3)]
public int[] rotations;
[NonSerialized]
public ColliderData colliderData;
public BlockData()
{
materialIDs = new string[6];
colliderData = new ColliderData();
rotations = new int[6];
}
public BlockData(string blockType)
{
this.blockType = blockType;
materialIDs = new string[6];
colliderData = new ColliderData();
rotations = new int[6];
}
}
} | using System;
using UnityEngine;
namespace MetroTileEditor
{
[Serializable]
public class BlockData
{
public string blockType = "basic_cube";
public bool placed;
public string[] materialIDs;
public bool breakable;
public bool isTriggerOnly;
public bool excludeFromMesh;
[Range(0, 3)]
[SerializeField]
public int[] rotations;
[NonSerialized]
public ColliderData colliderData;
public BlockData()
{
materialIDs = new string[6];
colliderData = new ColliderData();
rotations = new int[6];
}
}
} | mit | C# |
2ecd783d72baa5e8752cebfedb96c12a54370e73 | Improve Launcher code | pvdstel/cgppm | src/cgppm/Launcher.cs | src/cgppm/Launcher.cs | using cgppm.Netpbm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace cgppm
{
public class Launcher
{
[STAThread]
public static void Main(string[] args)
{
List<string> switches = args.Where(s => s[0] == '-' || s[0] == '/').Select(s => s.Substring(1)).ToList();
List<string> files = args.Where(s => File.Exists(s)).ToList();
Parser parser = new Parser();
List<RawImage> rawImages = files.Select(f => parser.Read(f)).ToList();
ImageConverter ic = new ImageConverter();
foreach (RawImage image in rawImages)
{
ImageViewer iv = new ImageViewer();
iv.SetBitmapSource(ic.ConvertNetpbmTo8Bit(image));
iv.Show();
}
App.Main();
}
}
}
| using cgppm.Netpbm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace cgppm
{
public class Launcher
{
private static IEnumerable<string> switches;
private static IEnumerable<string> files;
[STAThread]
public static void Main(string[] args)
{
switches = args.Where(s => s[0] == '-' || s[0] == '/').Select(s => s.Substring(1));
files = args.Where(s => File.Exists(s));
Parser parser = new Parser();
IEnumerable<RawImage> rawImages = files.Select(f => parser.Read(f));
IEnumerable<NormalizedImage> normalizedImages = rawImages.Select(ri => new NormalizedImage(ri));
Console.WriteLine(string.Format("Successfully parsed {0} files.", normalizedImages.Count()));
}
}
}
| mpl-2.0 | C# |
aed0562ddd2282a1bae6210f924f42be0b7cc43c | Update Zcash to Fundingstream | coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore | src/Miningcore/Blockchain/Equihash/DaemonResponses/GetBlockSubsidyResponse.cs | src/Miningcore/Blockchain/Equihash/DaemonResponses/GetBlockSubsidyResponse.cs | /*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Miningcore.Blockchain.Equihash.DaemonResponses
{
public class ZCashBlockSubsidy
{
public decimal Miner { get; set; }
public decimal? Founders { get; set; }
public decimal? Community { get; set; }
public List<fundingStreams> FundingStreams { get; set; }
}
public class fundingStreams
{
public string Recipient { get; set; }
public string Specification { get; set; }
public decimal Value { get; set; }
public decimal ValueZat { get; set; }
public string Address { get; set; }
}
}
| /*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Newtonsoft.Json;
namespace Miningcore.Blockchain.Equihash.DaemonResponses
{
public class ZCashBlockSubsidy
{
public decimal Miner { get; set; }
public decimal? Founders { get; set; }
public decimal? Community { get; set; }
}
}
| mit | C# |
b000f7962586674e94172a97da1849445606228d | Bump version | pescuma/progressmonitor | csharp/ProgressMonitor/Properties/AssemblyInfo.cs | csharp/ProgressMonitor/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("ProgressMonitor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProgressMonitor")]
[assembly: AssemblyCopyright("Copyright © Ricardo Pescuma Domenecci 2020")]
[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("70c6334b-71a8-436b-a459-d23cc5f0e78f")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
[assembly: InternalsVisibleTo("ProgressMonitor.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010011e4b1df63b1ec298d8195aa43d17d28f8eb17a0e2c3036d8475cca68f5ff9a632c67865a2dfdfd6f61e3f670ab7e3521405686f6d6fd355ccbbc266078ea8d8d185ec2a10089abaf2d78113f7e041637089a64cb3e028c9a5aa6ce48dbc50dc6f7b2aac1fab554ad1d9538d637639bde1689acb4c6c39e39a1d3139515fa4d1")]
| 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("ProgressMonitor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProgressMonitor")]
[assembly: AssemblyCopyright("Copyright © Ricardo Pescuma Domenecci 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("70c6334b-71a8-436b-a459-d23cc5f0e78f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: InternalsVisibleTo("ProgressMonitor.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010011e4b1df63b1ec298d8195aa43d17d28f8eb17a0e2c3036d8475cca68f5ff9a632c67865a2dfdfd6f61e3f670ab7e3521405686f6d6fd355ccbbc266078ea8d8d185ec2a10089abaf2d78113f7e041637089a64cb3e028c9a5aa6ce48dbc50dc6f7b2aac1fab554ad1d9538d637639bde1689acb4c6c39e39a1d3139515fa4d1")]
| mit | C# |
0c5b7ec2c6711094474a8f2dddc5503ebfc635b6 | Improve custom resource test | robv8r/FluentValidation,roend83/FluentValidation,olcayseker/FluentValidation,deluxetiky/FluentValidation,roend83/FluentValidation,pacificIT/FluentValidation,mgmoody42/FluentValidation,glorylee/FluentValidation,regisbsb/FluentValidation,GDoronin/FluentValidation,IRlyDontKnow/FluentValidation,cecilphillip/FluentValidation,ruisebastiao/FluentValidation | src/FluentValidation.Tests/LocalisedMessagesTester.cs | src/FluentValidation.Tests/LocalisedMessagesTester.cs | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Tests {
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Internal;
using NUnit.Framework;
using Resources;
using Validators;
[TestFixture]
public class LocalisedMessagesTester {
[Test]
public void Correctly_assigns_default_localized_error_message() {
var originalCulture = Thread.CurrentThread.CurrentUICulture;
try {
var validator = new NotEmptyValidator(null);
foreach (var culture in new[] { "en", "de", "fr" }) {
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
var message = Messages.ResourceManager.GetString("notempty_error");
var errorMessage = new MessageFormatter().AppendPropertyName("name").BuildMessage(message);
Debug.WriteLine(errorMessage);
var result = validator.Validate(new PropertyValidatorContext("name", null, x => null));
result.Single().ErrorMessage.ShouldEqual(errorMessage);
}
}
finally {
// Always reset the culture.
Thread.CurrentThread.CurrentUICulture = originalCulture;
}
}
[Test]
public void Uses_custom_resouces() {
ValidatorOptions.ResourceProviderType = typeof(MyResources);
var validator = new TestValidator() {
v => v.RuleFor(x => x.Surname).NotEmpty()
};
var result = validator.Validate(new Person());
// 'foo' is the error message for the NotEmptyValidator defined in the customised MyResources type.
result.Errors.Single().ErrorMessage.ShouldEqual("foo");
ValidatorOptions.ResourceProviderType = null;
}
[Test]
public void Sets_localised_message_via_expression() {
var validator = new TestValidator();
validator.RuleFor(x => x.Surname).NotEmpty().WithLocalizedMessage(() => MyResources.notempty_error);
var result = validator.Validate(new Person());
result.Errors.Single().ErrorMessage.ShouldEqual("foo");
}
private class MyResources {
public static string notempty_error {
get { return "foo"; }
}
}
}
} | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Tests {
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Internal;
using NUnit.Framework;
using Resources;
using Validators;
[TestFixture]
public class LocalisedMessagesTester {
[Test]
public void Correctly_assigns_default_localized_error_message() {
var originalCulture = Thread.CurrentThread.CurrentUICulture;
try {
var validator = new NotEmptyValidator(null);
foreach (var culture in new[] {"en", "de", "fr"}) {
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
var message = Messages.ResourceManager.GetString("notempty_error");
var errorMessage = new MessageFormatter().AppendPropertyName("name").BuildMessage(message);
Debug.WriteLine(errorMessage);
var result = validator.Validate(new PropertyValidatorContext("name", null, x => null));
result.Single().ErrorMessage.ShouldEqual(errorMessage);
}
}
finally {
// Always reset the culture.
Thread.CurrentThread.CurrentUICulture = originalCulture;
}
}
[Test]
public void Uses_custom_resouces() {
ValidatorOptions.ResourceProviderType = typeof(MyResources);
var validator = new NotEmptyValidator(null);
var result = validator.Validate(new PropertyValidatorContext("name", null, x => null));
result.Single().ErrorMessage.ShouldEqual("foo");
ValidatorOptions.ResourceProviderType = null;
}
[Test]
public void Sets_localised_message_via_expression() {
var validator = new TestValidator();
validator.RuleFor(x => x.Surname).NotEmpty().WithLocalizedMessage(() => MyResources.notempty_error);
var result = validator.Validate(new Person());
result.Errors.Single().ErrorMessage.ShouldEqual("foo");
}
private class MyResources {
public static string notempty_error {
get { return "foo"; }
}
}
}
} | apache-2.0 | C# |
9309d779c74b2ea8747c4b719be395e91e0f201f | Call SetWaitNotificationRequired | SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia | src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs | src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs | using System;
using System.Threading;
namespace Avalonia.Threading
{
/// <summary>
/// SynchronizationContext to be used on main thread
/// </summary>
public class AvaloniaSynchronizationContext : SynchronizationContext
{
public interface INonPumpingPlatformWaitProvider
{
int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
}
private readonly INonPumpingPlatformWaitProvider _waitProvider;
public AvaloniaSynchronizationContext(INonPumpingPlatformWaitProvider waitProvider)
{
_waitProvider = waitProvider;
if (_waitProvider != null)
SetWaitNotificationRequired();
}
/// <summary>
/// Controls if SynchronizationContext should be installed in InstallIfNeeded. Used by Designer.
/// </summary>
public static bool AutoInstall { get; set; } = true;
/// <summary>
/// Installs synchronization context in current thread
/// </summary>
public static void InstallIfNeeded()
{
if (!AutoInstall || Current is AvaloniaSynchronizationContext)
{
return;
}
SetSynchronizationContext(new AvaloniaSynchronizationContext(AvaloniaLocator.Current
.GetService<INonPumpingPlatformWaitProvider>()));
}
/// <inheritdoc/>
public override void Post(SendOrPostCallback d, object state)
{
Dispatcher.UIThread.Post(() => d(state), DispatcherPriority.Send);
}
/// <inheritdoc/>
public override void Send(SendOrPostCallback d, object state)
{
if (Dispatcher.UIThread.CheckAccess())
d(state);
else
Dispatcher.UIThread.InvokeAsync(() => d(state), DispatcherPriority.Send).Wait();
}
public override int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
if (_waitProvider != null)
return _waitProvider.Wait(waitHandles, waitAll, millisecondsTimeout);
return base.Wait(waitHandles, waitAll, millisecondsTimeout);
}
}
}
| using System;
using System.Threading;
namespace Avalonia.Threading
{
/// <summary>
/// SynchronizationContext to be used on main thread
/// </summary>
public class AvaloniaSynchronizationContext : SynchronizationContext
{
public interface INonPumpingPlatformWaitProvider
{
int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
}
private readonly INonPumpingPlatformWaitProvider _waitProvider;
public AvaloniaSynchronizationContext(INonPumpingPlatformWaitProvider waitProvider)
{
_waitProvider = waitProvider;
}
/// <summary>
/// Controls if SynchronizationContext should be installed in InstallIfNeeded. Used by Designer.
/// </summary>
public static bool AutoInstall { get; set; } = true;
/// <summary>
/// Installs synchronization context in current thread
/// </summary>
public static void InstallIfNeeded()
{
if (!AutoInstall || Current is AvaloniaSynchronizationContext)
{
return;
}
SetSynchronizationContext(new AvaloniaSynchronizationContext(AvaloniaLocator.Current
.GetService<INonPumpingPlatformWaitProvider>()));
}
/// <inheritdoc/>
public override void Post(SendOrPostCallback d, object state)
{
Dispatcher.UIThread.Post(() => d(state), DispatcherPriority.Send);
}
/// <inheritdoc/>
public override void Send(SendOrPostCallback d, object state)
{
if (Dispatcher.UIThread.CheckAccess())
d(state);
else
Dispatcher.UIThread.InvokeAsync(() => d(state), DispatcherPriority.Send).Wait();
}
public override int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
if (_waitProvider != null)
return _waitProvider.Wait(waitHandles, waitAll, millisecondsTimeout);
return base.Wait(waitHandles, waitAll, millisecondsTimeout);
}
}
}
| mit | C# |
5df5ea45b95dc3a127e2c763a492e00799eeb08f | Fix spelling Costa Rica | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/CostaRicaProvider.cs | Src/Nager.Date/PublicHolidays/CostaRicaProvider.cs | using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class CostaRicaProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Costa Rica
//https://en.wikipedia.org/wiki/Public_holidays_in_Costa_Rica
var countryCode = CountryCode.CR;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 11, "Juan Santa maria Day", "Juan Santa maria Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(-3), "Good Thursday", "Maundy Thursday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Labor Day", "Labor Day", countryCode));
items.Add(new PublicHoliday(year, 7, 25, "Guanacaste Day", "Guanacaste Day", countryCode));
items.Add(new PublicHoliday(year, 8, 2, "Virgin of Los Angeles Day", "Virgin of Los Angeles Day", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Mother´s Day", "Mother´s Day", countryCode));
items.Add(new PublicHoliday(year, 9, 15, "Independence Day", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 10, 12, "Cultures National Day", "Cultures National Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class CostaRicaProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Costa Rica
//https://en.wikipedia.org/wiki/Public_holidays_in_Costa_Rica
var countryCode = CountryCode.CR;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 11, "Juan Santa maria Day", "Juan Santa maria Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(-3), "Good Thursday ", "Maundy Thursday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Labor Day", "Labor Day", countryCode));
items.Add(new PublicHoliday(year, 7, 25, "Guanacaste Day", "Guanacaste Day", countryCode));
items.Add(new PublicHoliday(year, 8, 2, "Virgin of Los Angeles Day", "Virgin of Los Angeles Day", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Mother´s Day", "Mother´s Day", countryCode));
items.Add(new PublicHoliday(year, 9, 15, "Independence Day", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 10, 12, "Cultures National Day", "Cultures National Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
b04e20a2286a0234bf0746b5fc282c60456f56d7 | Modify the AutomaticPackageCurator query so that it will be case insensitive. | KuduApps/NuGetGallery,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,ScottShingler/NuGetGallery,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,projectkudu/SiteExtensionGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,mtian/SiteExtensionGallery,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,mtian/SiteExtensionGallery,skbkontur/NuGetGallery,KuduApps/NuGetGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,KuduApps/NuGetGallery,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,ScottShingler/NuGetGallery | Website/PackageCurators/AutomaticPackageCurator.cs | Website/PackageCurators/AutomaticPackageCurator.cs | using System;
using System.Linq;
using System.Web.Mvc;
using NuGet;
namespace NuGetGallery
{
public abstract class AutomaticPackageCurator : IAutomaticPackageCurator
{
public abstract void Curate(
Package galleryPackage,
IPackage nugetPackage);
protected virtual T GetService<T>()
{
return DependencyResolver.Current.GetService<T>();
}
protected bool DependenciesAreCurated(Package galleryPackage, CuratedFeed curatedFeed)
{
if (galleryPackage.Dependencies.IsEmpty())
{
return true;
}
return galleryPackage.Dependencies.All(
d => curatedFeed.Packages
.Where(p => p.Included)
.Any(p => p.PackageRegistration.Id.Equals(d.Id, StringComparison.InvariantCultureIgnoreCase)));
}
}
} | using System.Diagnostics.Contracts;
using System.Linq;
using System.Web.Mvc;
using NuGet;
namespace NuGetGallery
{
public abstract class AutomaticPackageCurator : IAutomaticPackageCurator
{
public abstract void Curate(
Package galleryPackage,
IPackage nugetPackage);
protected virtual T GetService<T>()
{
return DependencyResolver.Current.GetService<T>();
}
protected bool DependenciesAreCurated(Package galleryPackage, CuratedFeed curatedFeed)
{
if (galleryPackage.Dependencies.IsEmpty())
{
return true;
}
return galleryPackage.Dependencies.All(d => curatedFeed.Packages.Where(p => p.Included).Select(p => p.PackageRegistration.Id).Contains(d.Id));
}
}
} | apache-2.0 | C# |
88f6f9f6c702171369b6956776a133a99f8bbca9 | Change formatting. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/MitternachtBot/Common/TypeReaders/BotCommandTypeReader.cs | src/MitternachtBot/Common/TypeReaders/BotCommandTypeReader.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using Mitternacht.Modules.CustomReactions.Services;
using Mitternacht.Services;
namespace Mitternacht.Common.TypeReaders {
public class CommandTypeReader : TypeReader {
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) {
var cmds = services.GetService<CommandService>();
var cmdHandler = services.GetService<CommandHandler>();
var prefix = cmdHandler.GetPrefix(context.Guild);
var cmd = (input.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? cmds.Commands.FirstOrDefault(c => c.Aliases.Any(ca => ca.Equals(input[prefix.Length..], StringComparison.OrdinalIgnoreCase))) : null)
?? cmds.Commands.FirstOrDefault(c => c.Aliases.Any(ca => ca.Equals(input, StringComparison.OrdinalIgnoreCase)));
return Task.FromResult(cmd == null ? TypeReaderResult.FromError(CommandError.ParseFailed, $"No command named '{input}' found.") : TypeReaderResult.FromSuccess(cmd));
}
}
public class CommandOrCrTypeReader : CommandTypeReader {
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) {
var crs = services.GetService<CustomReactionsService>();
if(crs.GlobalReactions.Any(x => x.Trigger.Equals(input, StringComparison.OrdinalIgnoreCase))) {
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input));
} else {
var guild = context.Guild;
if(guild != null && crs.ReactionsForGuild(guild.Id).Concat(crs.GlobalReactions).Any(x => x.Trigger.Equals(input, StringComparison.OrdinalIgnoreCase))) {
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input));
} else {
var cmd = await base.ReadAsync(context, input, services);
return cmd.IsSuccess ? TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name)) : TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found.");
}
}
}
}
public class CommandOrCrInfo {
public string Name { get; set; }
public CommandOrCrInfo(string input) {
Name = input;
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using Mitternacht.Modules.CustomReactions.Services;
using Mitternacht.Services;
namespace Mitternacht.Common.TypeReaders {
public class CommandTypeReader : TypeReader {
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) {
var cmds = services.GetService<CommandService>();
var cmdHandler = services.GetService<CommandHandler>();
var prefix = cmdHandler.GetPrefix(context.Guild);
CommandInfo cmd = null;
if(input.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {
var inputWithoutPrefix = input.Substring(prefix.Length);
cmd = cmds.Commands.FirstOrDefault(c => c.Aliases.Any(ca => ca.Equals(inputWithoutPrefix, StringComparison.OrdinalIgnoreCase)));
}
if(cmd == null) {
cmd = cmds.Commands.FirstOrDefault(c => c.Aliases.Any(ca => ca.Equals(input, StringComparison.OrdinalIgnoreCase)));
}
return Task.FromResult(cmd == null ? TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.") : TypeReaderResult.FromSuccess(cmd));
}
}
public class CommandOrCrTypeReader : CommandTypeReader {
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) {
var crs = services.GetService<CustomReactionsService>();
if(!crs.GlobalReactions.Any(x => x.Trigger.Equals(input, StringComparison.OrdinalIgnoreCase))) {
var guild = context.Guild;
if(guild != null && crs.ReactionsForGuild(guild.Id).Concat(crs.GlobalReactions).Any(x => x.Trigger.Equals(input, StringComparison.OrdinalIgnoreCase))) {
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input));
} else {
var cmd = await base.ReadAsync(context, input, services);
return cmd.IsSuccess ? TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name)) : TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found.");
}
} else {
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input));
}
}
}
public class CommandOrCrInfo {
public string Name { get; set; }
public CommandOrCrInfo(string input) {
Name = input;
}
}
}
| mit | C# |
da2e7314f89c1c2d3b15f2b35eef6e8692ebb883 | Clarify comment. | sharadagrawal/Roslyn,dotnet/roslyn,aelij/roslyn,MatthieuMEZIL/roslyn,agocke/roslyn,jmarolf/roslyn,khyperia/roslyn,bbarry/roslyn,ErikSchierboom/roslyn,jeffanders/roslyn,Maxwe11/roslyn,tmat/roslyn,physhi/roslyn,thomaslevesque/roslyn,khellang/roslyn,ValentinRueda/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,pdelvo/roslyn,robinsedlaczek/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,leppie/roslyn,cston/roslyn,bartdesmet/roslyn,HellBrick/roslyn,abock/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,mattwar/roslyn,tmeschter/roslyn,srivatsn/roslyn,wvdd007/roslyn,ericfe-ms/roslyn,Pvlerick/roslyn,swaroop-sridhar/roslyn,xasx/roslyn,weltkante/roslyn,tannergooding/roslyn,kelltrick/roslyn,davkean/roslyn,akrisiun/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,Shiney/roslyn,vcsjones/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,mmitche/roslyn,OmarTawfik/roslyn,jaredpar/roslyn,lorcanmooney/roslyn,ErikSchierboom/roslyn,aelij/roslyn,xasx/roslyn,vslsnap/roslyn,Shiney/roslyn,jhendrixMSFT/roslyn,DustinCampbell/roslyn,ericfe-ms/roslyn,jaredpar/roslyn,yeaicc/roslyn,Hosch250/roslyn,AmadeusW/roslyn,natgla/roslyn,pdelvo/roslyn,a-ctor/roslyn,yeaicc/roslyn,jmarolf/roslyn,DustinCampbell/roslyn,xasx/roslyn,Giftednewt/roslyn,MatthieuMEZIL/roslyn,natidea/roslyn,tannergooding/roslyn,leppie/roslyn,Pvlerick/roslyn,reaction1989/roslyn,CaptainHayashi/roslyn,drognanar/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,gafter/roslyn,tmeschter/roslyn,akrisiun/roslyn,budcribar/roslyn,rgani/roslyn,Pvlerick/roslyn,gafter/roslyn,vcsjones/roslyn,jkotas/roslyn,nguerrera/roslyn,KevinH-MS/roslyn,jhendrixMSFT/roslyn,ValentinRueda/roslyn,KiloBravoLima/roslyn,srivatsn/roslyn,CyrusNajmabadi/roslyn,amcasey/roslyn,TyOverby/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,mmitche/roslyn,KiloBravoLima/roslyn,kelltrick/roslyn,CaptainHayashi/roslyn,AArnott/roslyn,VSadov/roslyn,balajikris/roslyn,jmarolf/roslyn,kelltrick/roslyn,michalhosala/roslyn,balajikris/roslyn,lorcanmooney/roslyn,davkean/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,basoundr/roslyn,jasonmalinowski/roslyn,balajikris/roslyn,diryboy/roslyn,bartdesmet/roslyn,sharwell/roslyn,zooba/roslyn,sharwell/roslyn,drognanar/roslyn,budcribar/roslyn,akrisiun/roslyn,panopticoncentral/roslyn,tvand7093/roslyn,aelij/roslyn,nguerrera/roslyn,bbarry/roslyn,DustinCampbell/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,agocke/roslyn,Hosch250/roslyn,bkoelman/roslyn,SeriaWei/roslyn,Maxwe11/roslyn,mgoertz-msft/roslyn,natidea/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,zooba/roslyn,lorcanmooney/roslyn,jamesqo/roslyn,xoofx/roslyn,jamesqo/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,a-ctor/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,jcouv/roslyn,abock/roslyn,genlu/roslyn,rgani/roslyn,ErikSchierboom/roslyn,managed-commons/roslyn,AnthonyDGreen/roslyn,amcasey/roslyn,abock/roslyn,HellBrick/roslyn,AmadeusW/roslyn,natidea/roslyn,MattWindsor91/roslyn,jasonmalinowski/roslyn,bkoelman/roslyn,basoundr/roslyn,HellBrick/roslyn,khellang/roslyn,jeffanders/roslyn,KevinRansom/roslyn,robinsedlaczek/roslyn,xoofx/roslyn,antonssonj/roslyn,weltkante/roslyn,AlekseyTs/roslyn,thomaslevesque/roslyn,cston/roslyn,stephentoub/roslyn,KevinRansom/roslyn,ericfe-ms/roslyn,wvdd007/roslyn,budcribar/roslyn,KiloBravoLima/roslyn,tmeschter/roslyn,gafter/roslyn,brettfo/roslyn,yeaicc/roslyn,sharadagrawal/Roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,michalhosala/roslyn,diryboy/roslyn,KevinH-MS/roslyn,a-ctor/roslyn,VSadov/roslyn,Hosch250/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,dotnet/roslyn,drognanar/roslyn,heejaechang/roslyn,agocke/roslyn,physhi/roslyn,TyOverby/roslyn,brettfo/roslyn,zooba/roslyn,swaroop-sridhar/roslyn,vslsnap/roslyn,tmat/roslyn,jkotas/roslyn,AlekseyTs/roslyn,jhendrixMSFT/roslyn,MattWindsor91/roslyn,ljw1004/roslyn,AArnott/roslyn,OmarTawfik/roslyn,paulvanbrenk/roslyn,jasonmalinowski/roslyn,jcouv/roslyn,panopticoncentral/roslyn,natgla/roslyn,jkotas/roslyn,amcasey/roslyn,tmat/roslyn,sharadagrawal/Roslyn,thomaslevesque/roslyn,jaredpar/roslyn,ljw1004/roslyn,diryboy/roslyn,AlekseyTs/roslyn,Maxwe11/roslyn,jeffanders/roslyn,mattscheffer/roslyn,bartdesmet/roslyn,srivatsn/roslyn,physhi/roslyn,rgani/roslyn,vslsnap/roslyn,sharwell/roslyn,VSadov/roslyn,genlu/roslyn,mavasani/roslyn,mattscheffer/roslyn,SeriaWei/roslyn,ValentinRueda/roslyn,nguerrera/roslyn,OmarTawfik/roslyn,SeriaWei/roslyn,eriawan/roslyn,antonssonj/roslyn,khyperia/roslyn,mgoertz-msft/roslyn,mattscheffer/roslyn,jamesqo/roslyn,heejaechang/roslyn,mmitche/roslyn,khyperia/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MichalStrehovsky/roslyn,TyOverby/roslyn,orthoxerox/roslyn,mattwar/roslyn,wvdd007/roslyn,Shiney/roslyn,dpoeschl/roslyn,mavasani/roslyn,paulvanbrenk/roslyn,heejaechang/roslyn,managed-commons/roslyn,KevinH-MS/roslyn,AArnott/roslyn,panopticoncentral/roslyn,reaction1989/roslyn,mattwar/roslyn,tvand7093/roslyn,brettfo/roslyn,basoundr/roslyn,bbarry/roslyn,AnthonyDGreen/roslyn,KevinRansom/roslyn,mavasani/roslyn,leppie/roslyn,stephentoub/roslyn,ljw1004/roslyn,antonssonj/roslyn,cston/roslyn,orthoxerox/roslyn,managed-commons/roslyn,dpoeschl/roslyn,Giftednewt/roslyn,MatthieuMEZIL/roslyn,AnthonyDGreen/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,dpoeschl/roslyn,khellang/roslyn,xoofx/roslyn,michalhosala/roslyn,vcsjones/roslyn,natgla/roslyn,orthoxerox/roslyn,MattWindsor91/roslyn,tvand7093/roslyn | src/Workspaces/Core/Portable/Utilities/BKTree.Node.cs | src/Workspaces/Core/Portable/Utilities/BKTree.Node.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Roslyn.Utilities
{
internal partial class BKTree
{
private struct Node
{
// The string this node corresponds to. Specifically, this span is the range of
// _allLowerCaseCharacters for that string.
public readonly TextSpan CharacterSpan;
// How many children/edges this node has.
public readonly int EdgeCount;
// Where the first edge can be found in "_edges". The edges are in the range:
// _edges[FirstEdgeIndex, FirstEdgeIndex + EdgeCount)
public readonly int FirstEdgeIndex;
public Node(TextSpan characterSpan, int edgeCount, int firstEdgeIndex)
{
CharacterSpan = characterSpan;
EdgeCount = edgeCount;
FirstEdgeIndex = firstEdgeIndex;
}
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt32(CharacterSpan.Start);
writer.WriteInt32(CharacterSpan.Length);
writer.WriteInt32(EdgeCount);
writer.WriteInt32(FirstEdgeIndex);
}
internal static Node ReadFrom(ObjectReader reader)
{
return new Node(new TextSpan(reader.ReadInt32(), reader.ReadInt32()), reader.ReadInt32(), reader.ReadInt32());
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Roslyn.Utilities
{
internal partial class BKTree
{
private struct Node
{
// The string this node corresponds to. Stored in char[] format so we can easily compute
// edit distances on it.
public readonly TextSpan CharacterSpan;
// How many children/edges this node has.
public readonly int EdgeCount;
// Where the first edge can be found in "_edges". The edges are in the range:
// _edges[FirstEdgeIndex, FirstEdgeIndex + EdgeCount)
public readonly int FirstEdgeIndex;
public Node(TextSpan characterSpan, int edgeCount, int firstEdgeIndex)
{
CharacterSpan = characterSpan;
EdgeCount = edgeCount;
FirstEdgeIndex = firstEdgeIndex;
}
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt32(CharacterSpan.Start);
writer.WriteInt32(CharacterSpan.Length);
writer.WriteInt32(EdgeCount);
writer.WriteInt32(FirstEdgeIndex);
}
internal static Node ReadFrom(ObjectReader reader)
{
return new Node(new TextSpan(reader.ReadInt32(), reader.ReadInt32()), reader.ReadInt32(), reader.ReadInt32());
}
}
}
}
| apache-2.0 | C# |
f115bb340143dec599f0714f7aa7f887676c2ac7 | update mapi claims type | ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian | src/Obsidian.Application/ManagementAPIClaimsType.cs | src/Obsidian.Application/ManagementAPIClaimsType.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Obsidian.Application
{
/// <summary>
/// Contains ClaimType string about Management API in Obsidian
/// </summary>
public static class ManagementAPIClaimsType
{
private const string _obsidianManagementAPIPrefix = "http://schema.za-pt.org/Obsidian/ManagementAPI/";
public const string UserName = _obsidianManagementAPIPrefix + "User/UserName";
public const string Password = _obsidianManagementAPIPrefix + "User/Password";
public const string Profile = _obsidianManagementAPIPrefix + "User/Profile";
public const string Claims = _obsidianManagementAPIPrefix + "User/Claims";
public const string User = _obsidianManagementAPIPrefix + "User";
public const string Client = _obsidianManagementAPIPrefix + "Client";
public const string ClientSecret = _obsidianManagementAPIPrefix + "Client/Secret";
public const string UpdateClient = _obsidianManagementAPIPrefix + "Client/UpdateClient";
public const string UpdateClientSecret = _obsidianManagementAPIPrefix + "Client/UpdateClientSecret";
public const string GetScope = _obsidianManagementAPIPrefix + "Scope/GetScope";
public const string AddScope = _obsidianManagementAPIPrefix + "Scope/AddScope";
public const string UpdateScope = _obsidianManagementAPIPrefix + "Scope/UpdateScope";
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Obsidian.Application
{
/// <summary>
/// Contains ClaimType string about Management API in Obsidian
/// </summary>
public static class ManagementAPIClaimsType
{
private const string _obsidianManagementAPIPrefix = "http://schema.za-pt.org/Obsidian/ManagementAPI/";
public const string UpdateUserName = _obsidianManagementAPIPrefix + "User/UpdateUserName";
public const string UpdatePassword = _obsidianManagementAPIPrefix + "User/UpdatePassword";
public const string UpdateProfile = _obsidianManagementAPIPrefix + "User/UpdateProfile";
public const string UpdateClaims = _obsidianManagementAPIPrefix + "User/UpdateClaims";
public const string AddUser = _obsidianManagementAPIPrefix + "User/AddUser";
public const string GetUser = _obsidianManagementAPIPrefix + "User/GetUser";
public const string GetClient = _obsidianManagementAPIPrefix + "Client/GetClient";
public const string GetClientSecret = _obsidianManagementAPIPrefix + "Client/GetClientSecret";
public const string AddClient = _obsidianManagementAPIPrefix + "Client/AddClient";
public const string UpdateClient = _obsidianManagementAPIPrefix + "Client/UpdateClient";
public const string UpdateClientSecret = _obsidianManagementAPIPrefix + "Client/UpdateClientSecret";
public const string GetScope = _obsidianManagementAPIPrefix + "Scope/GetScope";
public const string AddScope = _obsidianManagementAPIPrefix + "Scope/AddScope";
public const string UpdateScope = _obsidianManagementAPIPrefix + "Scope/UpdateScope";
}
}
| apache-2.0 | C# |
4dbcc1422b2ad1319e0ddeffcc7c2f1902dd9dcf | add overload for ray table | mrvux/kgp | src/KGP.Direct3D11/Textures/RayTableTexture.cs | src/KGP.Direct3D11/Textures/RayTableTexture.cs | using KGP.Direct3D11.Descriptors;
using Microsoft.Kinect;
using SharpDX;
using SharpDX.Direct3D11;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KGP.Direct3D11.Textures
{
/// <summary>
/// Ray table texture, used to perform depth/world reconstruction in gpu
/// </summary>
public class RayTableTexture : IDisposable
{
private Texture2D texture;
private ShaderResourceView rawView;
/// <summary>
/// Shader resource view
/// </summary>
public ShaderResourceView ShaderView
{
get { return this.rawView; }
}
private RayTableTexture(Texture2D texture, ShaderResourceView view)
{
this.texture = texture;
this.rawView = view;
}
/// <summary>
/// Convenience factory to create table from Kinect coordinate mapper
/// </summary>
/// <param name="device">Direct3D Device</param>
/// <param name="coordinateMapper">Kinect Coordinate mapper</param>
/// <returns>Ray table texture</returns>
public unsafe static RayTableTexture FromCoordinateMapper(Device device, CoordinateMapper coordinateMapper)
{
var points = coordinateMapper.GetDepthFrameToCameraSpaceTable();
return FromPoints(device, points);
}
/// <summary>
/// Convenience factory to create table from Kinect coordinate mapper
/// </summary>
/// <param name="device">Direct3D Device</param>
/// <param name="initialData">Initial points array</param>
/// <returns>Ray table texture</returns>
public unsafe static RayTableTexture FromPoints(Device device, PointF[] initialData)
{
if (initialData.Length != Consts.DepthPixelCount)
throw new ArgumentException("initialData", "Initial data length should be same size as depth frame pixel count");
fixed (PointF* ptr = &initialData[0])
{
DataRectangle rect = new DataRectangle(new IntPtr(ptr), Consts.DepthWidth * 8);
var texture = new Texture2D(device, LookupTableTextureDescriptors.DepthToCameraRayTable, rect);
var view = new ShaderResourceView(device, texture);
return new RayTableTexture(texture, view);
}
}
/// <summary>
/// Disposes GPU resources
/// </summary>
public void Dispose()
{
this.rawView.Dispose();
this.texture.Dispose();
}
}
}
| using KGP.Direct3D11.Descriptors;
using Microsoft.Kinect;
using SharpDX;
using SharpDX.Direct3D11;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KGP.Direct3D11.Textures
{
/// <summary>
/// Ray table texture, used to perform depth/world reconstruction in gpu
/// </summary>
public class RayTableTexture : IDisposable
{
private Texture2D texture;
private ShaderResourceView rawView;
/// <summary>
/// Shader resource view
/// </summary>
public ShaderResourceView ShaderView
{
get { return this.rawView; }
}
private RayTableTexture(Texture2D texture, ShaderResourceView view)
{
this.texture = texture;
this.rawView = view;
}
/// <summary>
/// Convenience factory to create table from Kinect coordinate mapper
/// </summary>
/// <param name="device">Direct3D Device</param>
/// <param name="coordinateMapper">Kinect Coordinate mapper</param>
/// <returns>Ray table texture</returns>
public unsafe static RayTableTexture FromCoordinateMapper(Device device, CoordinateMapper coordinateMapper)
{
var points = coordinateMapper.GetDepthFrameToCameraSpaceTable();
fixed (PointF* ptr = &points[0])
{
DataRectangle rect = new DataRectangle(new IntPtr(ptr), Consts.DepthWidth * 8);
var texture = new Texture2D(device, LookupTableTextureDescriptors.DepthToCameraRayTable, rect);
var view = new ShaderResourceView(device, texture);
return new RayTableTexture(texture, view);
}
}
/// <summary>
/// Disposes GPU resources
/// </summary>
public void Dispose()
{
this.rawView.Dispose();
this.texture.Dispose();
}
}
}
| mit | C# |
60d4807161ef9be2c09f00830ce851ab163279dd | Update AssemblyInfo.cs | Kyrodan/hidrive-dotnet-sdk | src/Kyrodan.HiDrive/Properties/AssemblyInfo.cs | src/Kyrodan.HiDrive/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("HiDrive .Net SDK")]
[assembly: AssemblyDescription("Integrates HiDrive into your C# app")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Bölts")]
[assembly: AssemblyProduct("Kyrodan.HiDrive")]
[assembly: AssemblyCopyright("Copyright © Daniel Bölts")]
[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.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0-alpha")]
| 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("HiDrive .Net SDK")]
[assembly: AssemblyDescription("Integrates HiDrive into your C# app")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Bölts")]
[assembly: AssemblyProduct("Kyrodan.HiDrive")]
[assembly: AssemblyCopyright("Copyright © Daniel Bölts")]
[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.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0-unstable")]
| mit | C# |
c2ce340130605c3001e8c6b20376f8f25769f21f | Add error checking to `p`. | mono/sdb,mono/sdb | src/Commands/PrintCommand.cs | src/Commands/PrintCommand.cs | /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class PrintCommand : Command
{
public override string[] Names
{
get { return new[] { "print", "evaluate" }; }
}
public override string Summary
{
get { return "Print (evaluate) a given expression."; }
}
public override string Syntax
{
get { return "print|evaluate <expr>"; }
}
public override void Process(string args)
{
var f = Debugger.ActiveFrame;
if (f == null)
{
Log.Error("No active stack frame");
return;
}
if (args.Length == 0)
{
Log.Error("No expression given");
return;
}
if (!f.ValidateExpression(args))
{
Log.Error("Expression '{0}' is invalid", args);
return;
}
var val = f.GetExpressionValue(args, Debugger.Options.EvaluationOptions);
var strErr = Utilities.StringizeValue(val);
if (strErr.Item2)
{
Log.Error(strErr.Item1);
return;
}
Log.Info("{0}{1}{2} it = {3}", Color.DarkGreen, val.TypeName, Color.Reset, strErr.Item1);
}
}
}
| /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class PrintCommand : Command
{
public override string[] Names
{
get { return new[] { "print", "evaluate" }; }
}
public override string Summary
{
get { return "Print (evaluate) a given expression."; }
}
public override string Syntax
{
get { return "print|evaluate <expr>"; }
}
public override void Process(string args)
{
var f = Debugger.ActiveFrame;
if (f == null)
{
Log.Error("No active stack frame");
return;
}
if (!f.ValidateExpression(args))
{
Log.Error("Expression '{0}' is invalid", args);
return;
}
var val = f.GetExpressionValue(args, Debugger.Options.EvaluationOptions);
var strErr = Utilities.StringizeValue(val);
if (strErr.Item2)
{
Log.Error(strErr.Item1);
return;
}
Log.Info("{0}{1}{2} it = {3}", Color.DarkGreen, val.TypeName, Color.Reset, strErr.Item1);
}
}
}
| mit | C# |
a7dbc83326a76d90ac0c742c756d1cc37c5aa081 | Fix the build | mono/maccore,jorik041/maccore,cwensley/maccore | src/Foundation/NSCalendar.cs | src/Foundation/NSCalendar.cs | //
// This file describes the API that the generator will produce
//
// Authors:
// Miguel de Icaza
//
// 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;
using MonoMac.ObjCRuntime;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.CoreMedia;
namespace MonoTouch.Foundation {
public enum NSCalendarType {
Gregorian, Buddhist, Chinese, Hebrew, Islamic, IslamicCivil, Japanese, RepublicOfChina, Persian, Indian, ISO8601
}
public partial class NSCalendar {
static NSString GetCalendarIdentifier (NSCalendarType type)
{
switch (type){
case NSCalendarType.Gregorian:
return NSGregorianCalendar;
case NSCalendarType.Buddhist:
return NSBuddhistCalendar;
case NSCalendarType.Chinese:
return NSChineseCalendar;
case NSCalendarType.Hebrew:
return NSHebrewCalendar;
case NSCalendarType.Islamic:
return NSIslamicCalendar;
case NSCalendarType.IslamicCivil:
return NSIslamicCivilCalendar;
case NSCalendarType.Japanese:
return NSJapaneseCalendar;
case NSCalendarType.RepublicOfChina:
return NSRepublicOfChinaCalendar;
case NSCalendarType.Persian:
return NSPersianCalendar;
case NSCalendarType.Indian:
return NSIndianCalendar;
case NSCalendarType.ISO8601:
return NSISO8601Calendar;
default:
throw new ArgumentException ("Unknown NSCalendarType value");
}
}
public NSCalendar (NSCalendarType calendarType) : this (GetCalendarIdentifier (calendarType)) {}
}
} | //
// This file describes the API that the generator will produce
//
// Authors:
// Miguel de Icaza
//
// 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 MonoMac.ObjCRuntime;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.CoreMedia;
namespace MonoTouch.Foundation {
public enum NSCalendarType {
Gregorian, Buddhist, Chinese, Hebrew, Islamic, IslamicCivil, Japanese, RepublicOfChina, Persian, Indian, ISO8601
}
public partial class NSCalendar {
static NSString GetCalendarIdentifier (NSCalendarType type)
{
switch (type){
case Gregorian:
return NSGregorianCalendar;
case Buddhist:
return NSBuddhistCalendar;
case Chinese:
return NSChineseCalendar;
case Hebrew:
return NSHebrewCalendar;
case Islamic:
return NSIslamicCalendar;
case IslamicCivil:
return NSIslamicCivilCalendar;
case Japanese:
return NSJapaneseCalendar;
case RepublicOfChina:
return NSRepublicOfChinaCalendar;
case Persian:
return NSPersianCalendar;
case Indian:
return NSIndianCalendar;
case ISO8601:
return NSISO8601Calendar;
default:
throw new ArgumentException ("Unknown NSCalendarType value");
}
}
public NSCalendar (NSCalendarType calendarType) : this (GetCalendarIdentifier (calendarType)) {}
}
} | apache-2.0 | C# |
33f34c9421cfcfab602c4a57235f0453c1b7ace8 | Build fix 2 | ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab | source/Server/Common/Diagnostics/AssemblyLog.cs | source/Server/Common/Diagnostics/AssemblyLog.cs | using System.Diagnostics;
using System.IO;
using Mono.Cecil;
namespace SharpLab.Server.Common.Diagnostics {
public static class AssemblyLog {
#if DEBUG
private static readonly AsyncLocal<string> _pathFormat = new AsyncLocal<string>();
public static void Enable(string pathFormat) {
_pathFormat.Value = pathFormat;
}
#endif
[Conditional("DEBUG")]
public static void Log(string stepName, AssemblyDefinition assembly) {
#if DEBUG
var path = GetLogPath(stepName);
if (path == null)
return;
assembly.Write(path);
#endif
}
public static void Log(string stepName, MemoryStream assemblyStream) {
#if DEBUG
var path = GetLogPath(stepName);
if (path == null)
return;
File.WriteAllBytes(path, assemblyStream.ToArray());
#endif
}
#if DEBUG
private static string? GetLogPath(string stepName) {
var format = _pathFormat.Value;
if (format == null)
return null;
var path = string.Format(format, stepName);
var directoryPath = Path.GetDirectoryName(path);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
return path;
}
#endif
}
}
| using System.Diagnostics;
using System.IO;
#if DEBUG
using System.Threading;
#endif
using Mono.Cecil;
namespace SharpLab.Server.Common.Diagnostics {
public static class AssemblyLog {
#if DEBUG
private static readonly AsyncLocal<string> _pathFormat = new AsyncLocal<string>();
public static void Enable(string pathFormat) {
_pathFormat.Value = pathFormat;
}
#endif
[Conditional("DEBUG")]
public static void Log(string stepName, AssemblyDefinition assembly) {
#if DEBUG
var path = GetLogPath(stepName);
if (path == null)
return;
assembly.Write(path);
#endif
}
public static void Log(string stepName, MemoryStream assemblyStream) {
#if DEBUG
var path = GetLogPath(stepName);
if (path == null)
return;
File.WriteAllBytes(path, assemblyStream.ToArray());
#endif
}
private static string? GetLogPath(string stepName) {
var format = _pathFormat.Value;
if (format == null)
return null;
var path = string.Format(format, stepName);
var directoryPath = Path.GetDirectoryName(path);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
return path;
}
}
}
| bsd-2-clause | C# |
a08e9ef7d1c28a67c808aa473df28751a950117f | Fix build bug | cnurse/Naif.Core | src/Naif.Core/Models/User.cs | src/Naif.Core/Models/User.cs | using System.Collections.Generic;
namespace Naif.Core.Models
{
public class User
{
public User()
{
Created = System.DateTime.MinValue;
Roles = new List<Role>();
LastUpdated = System.DateTime.MinValue;
}
public System.DateTime Created {get; set;}
public string EmailAddress { get; set; }
public bool EmailVerified {get; set; }
public string GivenName {get; set;}
public string Identifier {get; set; }
public bool IsAuthenticated { get; set; }
public System.DateTime LastUpdated {get; set;}
public string Locale {get; set;}
public string NickName { get; set; }
public string Name { get; set; }
public string ProfileImage { get; set; }
public IList<Role> Roles { get; set; }
public string Surname {get; set; }
}
} | using System.Collections.Generic;
namespace Naif.Core.Models
{
public class User
{
public User()
{
Created = System.DateTime.MinValue;
Roles = new List<Role>();
LastUpdated = System.DateTime.MinValue;
}
public System.DateTime Created {get; set;}
public string EmailAddress { get; set; }
public bool EmailVerified {get; set; }
public string GivenName {get; set;}
public string Identifier {get; set; }
public bool IsAuthenticated { get; set; }
public DateTime LastUpdated {get; set;}
public string Locale {get; set;}
public string NickName { get; set; }
public string Name { get; set; }
public string ProfileImage { get; set; }
public IList<Role> Roles { get; set; }
public string Surname {get; set; }
}
} | mit | C# |
0f348406ded518a105bd93d87fb4989deabd3cf2 | Append new line at EOF | Archie-Yang/PcscDotNet | src/PcscDotNet/SCardShare.cs | src/PcscDotNet/SCardShare.cs | namespace PcscDotNet
{
/// <summary>
/// Indicates whether other applications may form connections to the card.
/// </summary>
public enum SCardShare
{
/// <summary>
/// This application demands direct control of the reader, so it is not available to other applications.
/// </summary>
Direct = 3,
/// <summary>
/// This application is not willing to share this card with other applications.
/// </summary>
Exclusive = 1,
/// <summary>
/// This application is willing to share this card with other applications.
/// </summary>
Shared = 2,
/// <summary>
/// Share mode is undefined, can not be used to connect to card/reader.
/// </summary>
Undefined = 0
}
}
| namespace PcscDotNet
{
/// <summary>
/// Indicates whether other applications may form connections to the card.
/// </summary>
public enum SCardShare
{
/// <summary>
/// This application demands direct control of the reader, so it is not available to other applications.
/// </summary>
Direct = 3,
/// <summary>
/// This application is not willing to share this card with other applications.
/// </summary>
Exclusive = 1,
/// <summary>
/// This application is willing to share this card with other applications.
/// </summary>
Shared = 2,
/// <summary>
/// Share mode is undefined, can not be used to connect to card/reader.
/// </summary>
Undefined = 0
}
} | mit | C# |
0edd533eba15931d91529ab6394c2be9c1ecc66c | Increase AuthorBage.HoverText db table column length | ssh-git/training-manager,ssh-git/training-manager,ssh-git/training-manager,ssh-git/training-manager | src/TM.Shared/AuthorBadge.cs | src/TM.Shared/AuthorBadge.cs | using System.ComponentModel.DataAnnotations;
namespace TM.Shared
{
public class AuthorBadge
{
[StringLength(400)]
public string ImageSiteUrl { get; set; }
[StringLength(100)]
public string ImageName { get; set; }
[StringLength(400)]
public string Link { get; set; }
[StringLength(400)]
public string HoverText { get; set; }
public bool IsEmpty
{
get { return string.IsNullOrWhiteSpace(Link); }
}
}
} | using System.ComponentModel.DataAnnotations;
namespace TM.Shared
{
public class AuthorBadge
{
[StringLength(400)]
public string ImageSiteUrl { get; set; }
[StringLength(100)]
public string ImageName { get; set; }
[StringLength(400)]
public string Link { get; set; }
[StringLength(100)]
public string HoverText { get; set; }
public bool IsEmpty
{
get { return string.IsNullOrWhiteSpace(Link); }
}
}
} | mit | C# |
6d338d1be4e5f419e18fea15bfaabe05d2d5ccf8 | Fix failing test | jammycakes/dolstagis.web,jammycakes/dolstagis.web,jammycakes/dolstagis.web | src/Dolstagis.Tests/Web/Owin/OwinFixtureBase.cs | src/Dolstagis.Tests/Web/Owin/OwinFixtureBase.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dolstagis.Web.Owin;
namespace Dolstagis.Tests.Web.Owin
{
public class OwinFixtureBase
{
/// <summary>
/// Creates a sample Owin context containing all the keys that are
/// required per the Owin 1.0 specification, section 3.2.1.
/// </summary>
/// <remarks>
/// This context MUST NOT be altered to include any keys not listed in
/// section 3.2.1 of the Owin specification. In particular, it must not
/// include the common keys listed in section 6 of the Owin "Common
/// Keys" document, as these are implementation-dependent and are not
/// guaranteed to be present.
/// </remarks>
/// <returns></returns>
protected IDictionary<string, object> BuildDefaultOwinEnvironment()
{
return new Dictionary<string, object>() {
{ EnvironmentKeys.RequestBody, Stream.Null },
{ EnvironmentKeys.RequestHeaders,
new Dictionary<string, string[]> {
{ "Host", new string[] { "localhost" } }
}
},
{ EnvironmentKeys.RequestMethod, "GET" },
{ EnvironmentKeys.RequestPath, "/" },
{ EnvironmentKeys.RequestPathBase, String.Empty },
{ EnvironmentKeys.RequestProtocol, "HTTP/1.1" },
{ EnvironmentKeys.RequestQueryString, String.Empty },
{ EnvironmentKeys.RequestScheme, "http" },
{ EnvironmentKeys.ResponseBody, Stream.Null },
{ EnvironmentKeys.ResponseHeaders, new Dictionary<string, string[]>() },
{ EnvironmentKeys.ResponseStatusCode, 200 },
{ EnvironmentKeys.ResponseReasonPhrase, "OK" },
{ EnvironmentKeys.ResponseProtocol, "HTTP/1.1" },
{ EnvironmentKeys.CallCancelled, new CancellationToken() },
{ EnvironmentKeys.OwinVersion, "1.0" }
};
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dolstagis.Web.Owin;
namespace Dolstagis.Tests.Web.Owin
{
public class OwinFixtureBase
{
/// <summary>
/// Creates a sample Owin context containing all the keys that are
/// required per the Owin 1.0 specification, section 3.2.1.
/// </summary>
/// <remarks>
/// This context MUST NOT be altered to include any keys not listed in
/// section 3.2.1 of the Owin specification. In particular, it must not
/// include the common keys listed in section 6 of the Owin "Common
/// Keys" document, as these are implementation-dependent and are not
/// guaranteed to be present.
/// </remarks>
/// <returns></returns>
protected IDictionary<string, object> BuildDefaultOwinEnvironment()
{
return new Dictionary<string, object>() {
{ EnvironmentKeys.RequestBody, Stream.Null },
{ EnvironmentKeys.RequestBody,
new Dictionary<string, string[]> {
{ "Host", new string[] { "localhost" } }
}
},
{ EnvironmentKeys.RequestMethod, "GET" },
{ EnvironmentKeys.RequestPath, "/" },
{ EnvironmentKeys.RequestPathBase, String.Empty },
{ EnvironmentKeys.RequestProtocol, "HTTP/1.1" },
{ EnvironmentKeys.RequestQueryString, String.Empty },
{ EnvironmentKeys.RequestScheme, "http" },
{ EnvironmentKeys.ResponseBody, Stream.Null },
{ EnvironmentKeys.ResponseHeaders, new Dictionary<string, string[]>() },
{ EnvironmentKeys.ResponseStatusCode, 200 },
{ EnvironmentKeys.ResponseReasonPhrase, "OK" },
{ EnvironmentKeys.ResponseProtocol, "HTTP/1.1" },
{ EnvironmentKeys.CallCancelled, new CancellationToken() },
{ EnvironmentKeys.OwinVersion, "1.0" }
};
}
}
}
| mit | C# |
07cd4bbc7f20ca427d7de2a62b235a52627fa234 | Disable test parallelism | filipw/dotnet-script,filipw/dotnet-script | src/Dotnet.Script.Tests/ScriptExecutionTests.cs | src/Dotnet.Script.Tests/ScriptExecutionTests.cs | using System.IO;
using Xunit;
namespace Dotnet.Script.Tests
{
[Collection("IntegrationTests")]
public class ScriptExecutionTests
{
[Fact]
public void ShouldExecuteHelloWorld()
{
var result = Execute(Path.Combine("HelloWorld", "HelloWorld.csx"));
Assert.Contains("Hello World", result);
}
[Fact]
public void ShouldExecuteScriptWithInlineNugetPackage()
{
var result = Execute(Path.Combine("InlineNugetPackage", "InlineNugetPackage.csx"));
Assert.Contains("AutoMapper.MapperConfiguration", result);
}
[Fact]
public void ShouldIncludeExceptionLineNumberAndFile()
{
var result = Execute(Path.Combine("Exception", "Error.csx"));
Assert.Contains("Error.csx:line 1", result);
}
[Fact]
public void ShouldHandlePackageWithNativeLibraries()
{
var result = Execute(Path.Combine("NativeLibrary", "NativeLibrary.csx"));
Assert.Contains("Connection successful", result);
}
private static string Execute(string fixture)
{
var result = ProcessHelper.RunAndCaptureOutput("dotnet", GetDotnetScriptArguments(Path.Combine("..", "..", "..", "TestFixtures", fixture)));
return result;
}
/// <summary>
/// Use this method if you need to debug
/// </summary>
private static int ExecuteInProcess(string fixture)
{
var pathToFixture = Path.Combine("..", "..", "..","TestFixtures", fixture);
return Program.Main(new []{ pathToFixture });
}
private static string[] GetDotnetScriptArguments(string fixture)
{
return new[] { "exec", Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "Dotnet.Script", "bin", "Debug", "netcoreapp1.1", "dotnet-script.dll"), fixture };
}
}
}
| using System.IO;
using Xunit;
namespace Dotnet.Script.Tests
{
public class ScriptExecutionTests
{
[Fact]
public void ShouldExecuteHelloWorld()
{
var result = Execute(Path.Combine("HelloWorld", "HelloWorld.csx"));
Assert.Contains("Hello World", result);
}
[Fact]
public void ShouldExecuteScriptWithInlineNugetPackage()
{
var result = Execute(Path.Combine("InlineNugetPackage", "InlineNugetPackage.csx"));
Assert.Contains("AutoMapper.MapperConfiguration", result);
}
[Fact]
public void ShouldIncludeExceptionLineNumberAndFile()
{
var result = Execute(Path.Combine("Exception", "Error.csx"));
Assert.Contains("Error.csx:line 1", result);
}
[Fact]
public void ShouldHandlePackageWithNativeLibraries()
{
var result = Execute(Path.Combine("NativeLibrary", "NativeLibrary.csx"));
Assert.Contains("Connection successful", result);
}
private static string Execute(string fixture)
{
var result = ProcessHelper.RunAndCaptureOutput("dotnet", GetDotnetScriptArguments(Path.Combine("..", "..", "..", "TestFixtures", fixture)));
return result;
}
/// <summary>
/// Use this method if you need to debug
/// </summary>
private static int ExecuteInProcess(string fixture)
{
var pathToFixture = Path.Combine("..", "..", "..","TestFixtures", fixture);
return Program.Main(new []{ pathToFixture });
}
private static string[] GetDotnetScriptArguments(string fixture)
{
return new[] { "exec", Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "Dotnet.Script", "bin", "Debug", "netcoreapp1.1", "dotnet-script.dll"), fixture };
}
}
}
| mit | C# |
ea0ed95ca0344cdb10bf58b0e491c59234a0bc0d | Fix time bug with scrobbles | realworld666/lastfm,Brijen/lastfm | src/IF.Lastfm.Core/Api/Helpers/ApiExtensions.cs | src/IF.Lastfm.Core/Api/Helpers/ApiExtensions.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace IF.Lastfm.Core.Api.Helpers
{
public static class ApiExtensions
{
public static T GetAttribute<T>(this Enum enumValue)
where T : Attribute
{
return enumValue
.GetType()
.GetTypeInfo()
.GetDeclaredField(enumValue.ToString())
.GetCustomAttribute<T>();
}
public static string GetApiName(this Enum enumValue)
{
var attribute = enumValue.GetAttribute<ApiNameAttribute>();
return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text))
? attribute.Text
: enumValue.ToString();
}
public static int ToUnixTimestamp(this DateTime dt)
{
var d = (dt - new DateTime(1970, 1, 1)).TotalSeconds;
return Convert.ToInt32(d);
}
public static DateTime ToDateTimeUtc(this double stamp)
{
var d = new DateTime(1970, 1, 1).ToUniversalTime();
d = d.AddSeconds(stamp);
return d;
}
public static int CountOrDefault<T>(this IEnumerable<T> enumerable)
{
return enumerable != null
? enumerable.Count()
: 0;
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace IF.Lastfm.Core.Api.Helpers
{
public static class ApiExtensions
{
public static T GetAttribute<T>(this Enum enumValue)
where T : Attribute
{
return enumValue
.GetType()
.GetTypeInfo()
.GetDeclaredField(enumValue.ToString())
.GetCustomAttribute<T>();
}
public static string GetApiName(this Enum enumValue)
{
var attribute = enumValue.GetAttribute<ApiNameAttribute>();
return (attribute != null && !string.IsNullOrWhiteSpace(attribute.Text))
? attribute.Text
: enumValue.ToString();
}
public static int ToUnixTimestamp(this DateTime dt)
{
var d = (dt - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
return Convert.ToInt32(d);
}
public static DateTime ToDateTimeUtc(this double stamp)
{
var d = new DateTime(1970, 1, 1).ToUniversalTime();
d = d.AddSeconds(stamp);
return d;
}
public static int CountOrDefault<T>(this IEnumerable<T> enumerable)
{
return enumerable != null
? enumerable.Count()
: 0;
}
}
} | mit | C# |
7113d1f60d60878d0d79dc98b3819ef75ab521e2 | Fix issue with nulll image icon in tabbed navigation container | rid00z/FreshMvvm,bbqchickenrobot/FreshMvvm,takenet/FreshMvvm,asednev/FreshMvvm,Mark-RSK/FreshMvvm,keannan5390/FreshMvvm | src/FreshMvvm/FreshTabbedNavigationContainer.cs | src/FreshMvvm/FreshTabbedNavigationContainer.cs | using System;
using Xamarin.Forms;
using System.Collections.Generic;
namespace FreshMvvm
{
public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService
{
public FreshTabbedNavigationContainer ()
{
RegisterNavigation ();
}
protected void RegisterNavigation ()
{
FreshIOC.Container.Register<IFreshNavigationService> (this);
}
public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel
{
var page = FreshPageModelResolver.ResolvePageModel<T> (data);
var navigationContainer = CreateContainerPage (page);
navigationContainer.Title = title;
if (!string.IsNullOrWhiteSpace(icon))
navigationContainer.Icon = icon;
Children.Add (navigationContainer);
return navigationContainer;
}
protected virtual Page CreateContainerPage (Page page)
{
return new NavigationPage (page);
}
public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false)
{
if (modal)
await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page));
else
await this.CurrentPage.Navigation.PushAsync (page);
}
public async System.Threading.Tasks.Task PopPage (bool modal = false)
{
if (modal)
await this.CurrentPage.Navigation.PopModalAsync ();
else
await this.CurrentPage.Navigation.PopAsync ();
}
}
}
| using System;
using Xamarin.Forms;
using System.Collections.Generic;
namespace FreshMvvm
{
public class FreshTabbedNavigationContainer : TabbedPage, IFreshNavigationService
{
public FreshTabbedNavigationContainer ()
{
RegisterNavigation ();
}
protected void RegisterNavigation ()
{
FreshIOC.Container.Register<IFreshNavigationService> (this);
}
public virtual Page AddTab<T> (string title, string icon, object data = null) where T : FreshBasePageModel
{
var page = FreshPageModelResolver.ResolvePageModel<T> (data);
var navigationContainer = CreateContainerPage (page);
navigationContainer.Title = title;
navigationContainer.Icon = icon;
Children.Add (navigationContainer);
return navigationContainer;
}
protected virtual Page CreateContainerPage (Page page)
{
return new NavigationPage (page);
}
public async System.Threading.Tasks.Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false)
{
if (modal)
await this.CurrentPage.Navigation.PushModalAsync (CreateContainerPage (page));
else
await this.CurrentPage.Navigation.PushAsync (page);
}
public async System.Threading.Tasks.Task PopPage (bool modal = false)
{
if (modal)
await this.CurrentPage.Navigation.PopModalAsync ();
else
await this.CurrentPage.Navigation.PopAsync ();
}
}
}
| apache-2.0 | C# |
3870e7fdaab526d201d7c5424699f71e34f3e8cc | Implement supported parts of Spn/UpnEndpointIdentity | KKhurin/wcf,imcarolwang/wcf,mconnew/wcf,MattGal/wcf,MattGal/wcf,iamjasonp/wcf,zhenlan/wcf,zhenlan/wcf,mconnew/wcf,iamjasonp/wcf,StephenBonikowsky/wcf,khdang/wcf,KKhurin/wcf,hongdai/wcf,ElJerry/wcf,dotnet/wcf,shmao/wcf,StephenBonikowsky/wcf,imcarolwang/wcf,hongdai/wcf,imcarolwang/wcf,ElJerry/wcf,dotnet/wcf,ericstj/wcf,khdang/wcf,mconnew/wcf,shmao/wcf,ericstj/wcf,dotnet/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/SpnEndpointIdentity.cs | src/System.Private.ServiceModel/src/System/ServiceModel/SpnEndpointIdentity.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IdentityModel.Claims;
using System.Runtime;
using System.Security.Principal;
namespace System.ServiceModel
{
public class SpnEndpointIdentity : EndpointIdentity
{
private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1);
public SpnEndpointIdentity(string spnName)
{
if (spnName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName");
base.Initialize(Claim.CreateSpnClaim(spnName));
}
public SpnEndpointIdentity(Claim identity)
{
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (!identity.ClaimType.Equals(ClaimTypes.Spn))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn));
base.Initialize(identity);
}
public static TimeSpan SpnLookupTime
{
get
{
return _spnLookupTime;
}
set
{
if (value.Ticks < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative)));
}
_spnLookupTime = value;
}
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IdentityModel.Claims;
using System.Runtime;
using System.Security.Principal;
namespace System.ServiceModel
{
public class SpnEndpointIdentity : EndpointIdentity
{
private static TimeSpan _spnLookupTime = TimeSpan.FromMinutes(1);
public SpnEndpointIdentity(string spnName)
{
if (spnName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName");
base.Initialize(Claim.CreateSpnClaim(spnName));
}
public SpnEndpointIdentity(Claim identity)
{
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (!identity.ClaimType.Equals(ClaimTypes.Spn))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn));
base.Initialize(identity);
}
public static TimeSpan SpnLookupTime
{
get
{
return _spnLookupTime;
}
set
{
if (value.Ticks < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("value", value.Ticks, SR.Format(SR.ValueMustBeNonNegative)));
}
_spnLookupTime = value;
}
}
}
}
| mit | C# |
dcb6fed27192f8b27991ede6f68c045fb7c7c550 | Update AGameManager.cs | Nicolas-Constanty/UnityTools | Assets/UnityTools/MonoBehaviour/AGameManager.cs | Assets/UnityTools/MonoBehaviour/AGameManager.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityTools.DesignPatern;
// ReSharper disable once CheckNamespace
namespace UnityTools
{
public abstract class AGameManager<T, TE> : Singleton<T>
where T : MonoBehaviour
where TE : struct, IConvertible
{
// ReSharper disable once EmptyConstructor
protected AGameManager() {}
protected delegate void GameAction();
protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>();
protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>();
protected override void Awake()
{
base.Awake();
bool init = false;
foreach (TE state in Enum.GetValues(typeof(TE)))
{
if (!init)
{
init = true;
}
Type type = typeof(T);
MethodInfo method = type.GetMethod("On" + state + "Game", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (method != null)
{
GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
method = type.GetMethod("OnFixed" + state + "Game");
if (method != null)
{
GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
}
}
public TE CurrentState;
public T GetInstance()
{
return Instance;
}
protected virtual void Update()
{
if (GameStatesUpdateActions.ContainsKey(CurrentState))
GameStatesUpdateActions[CurrentState]();
}
protected virtual void FixedUpdate()
{
if (GameStatesFixedUpdateActions.ContainsKey(CurrentState))
GameStatesFixedUpdateActions[CurrentState]();
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityTools.DesignPatern;
// ReSharper disable once CheckNamespace
namespace UnityTools
{
public abstract class AGameManager<T, TE> : Singleton<T>
where T : MonoBehaviour
where TE : struct, IConvertible
{
// ReSharper disable once EmptyConstructor
protected AGameManager() {}
protected delegate void GameAction();
protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>();
protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>();
protected override void Awake()
{
base.Awake();
bool init = false;
foreach (TE state in Enum.GetValues(typeof(TE)))
{
if (!init)
{
init = true;
}
Type type = typeof(T);
MethodInfo method = type.GetMethod("On" + state + "Game", BindingFlags.NonPublic);
if (method != null)
{
GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
method = type.GetMethod("OnFixed" + state + "Game");
if (method != null)
{
GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
}
}
public TE CurrentState;
public T GetInstance()
{
return Instance;
}
protected virtual void Update()
{
if (GameStatesUpdateActions.ContainsKey(CurrentState))
GameStatesUpdateActions[CurrentState]();
}
protected virtual void FixedUpdate()
{
if (GameStatesFixedUpdateActions.ContainsKey(CurrentState))
GameStatesFixedUpdateActions[CurrentState]();
}
}
}
| mit | C# |
beef9fd2c373779403182eeae27d8cad067cadb4 | Fix code completion not working. | mrward/monodevelop-dnx-addin | src/MonoDevelop.Dnx/MonoDevelop.Dnx/XProject.cs | src/MonoDevelop.Dnx/MonoDevelop.Dnx/XProject.cs | //
// XProject.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using MonoDevelop.Projects;
using MonoDevelop.Core;
namespace MonoDevelop.Dnx
{
public class XProject : DotNetProject
{
public XProject ()
{
UseMSBuildEngine = false;
Initialize (this);
}
protected override void OnInitialize ()
{
base.OnInitialize ();
SupportsRoslyn = true;
StockIcon = "md-csharp-project";
}
protected override DotNetCompilerParameters OnCreateCompilationParameters (DotNetProjectConfiguration config, ConfigurationKind kind)
{
return new DnxConfigurationParameters ();
}
protected override ClrVersion[] OnGetSupportedClrVersions ()
{
return new ClrVersion[] {
ClrVersion.Net_4_5
};
}
public void SetDefaultNamespace (FilePath fileName)
{
DefaultNamespace = GetDefaultNamespace (fileName);
}
}
}
| //
// XProject.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using MonoDevelop.Projects;
using MonoDevelop.Core;
namespace MonoDevelop.Dnx
{
public class XProject : DotNetProject
{
public XProject ()
{
UseMSBuildEngine = false;
Initialize (this);
}
protected override void OnInitialize ()
{
base.OnInitialize ();
StockIcon = "md-csharp-project";
}
protected override DotNetCompilerParameters OnCreateCompilationParameters (DotNetProjectConfiguration config, ConfigurationKind kind)
{
return new DnxConfigurationParameters ();
}
protected override ClrVersion[] OnGetSupportedClrVersions ()
{
return new ClrVersion[] {
ClrVersion.Net_4_5
};
}
public void SetDefaultNamespace (FilePath fileName)
{
DefaultNamespace = GetDefaultNamespace (fileName);
}
}
}
| mit | C# |
0afd9c25fb3d48463a87f87de44081577bb1a840 | Update version of .Variants | ProgramFOX/Chess.NET | ChessDotNet.Variants/Properties/AssemblyInfo.cs | ChessDotNet.Variants/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("ChessDotNet.Variants")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChessDotNet.Variants")]
[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("bd136017-2e1f-48f4-b072-958f9ba853c7")]
// 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.10.0.1")]
[assembly: AssemblyFileVersion("0.10.0.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ChessDotNet.Variants")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChessDotNet.Variants")]
[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("bd136017-2e1f-48f4-b072-958f9ba853c7")]
// 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.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
| mit | C# |
e71e96c576f00af271ad6b9e7e6061bf03cd6871 | Fix build | DaveSenn/Stomp.Net | .Src/Examples/Stomp.Net.Example.SendReceive/Program.cs | .Src/Examples/Stomp.Net.Example.SendReceive/Program.cs | #region Usings
using System;
using Apache.NMS;
using Apache.NMS.Stomp;
using Extend;
#endregion
namespace Stomp.Net.Example.Producer
{
public class Program
{
#region Constants
private const String Destination = "TestQ";
private const String Host = "HOST";
private const String Password = "password";
private const Int32 Port = 60000;
private const String User = "admin";
#endregion
public static void Main( String[] args )
{
SendReceive();
Console.WriteLine( "Press <enter> to exit." );
Console.ReadLine();
}
private static void SendReceive()
{
var brokerUri = "stomp:tcp://" + Host + ":" + Port;
var factory = new ConnectionFactory( brokerUri, new StompConnectionSettings { UserName = User, Password = Password });
// Create connection for both requests and responses
var connection = factory.CreateConnection( );
connection.Start();
// Create session for both requests and responses
var session = connection.CreateSession( AcknowledgementMode.IndividualAcknowledge );
IDestination destinationQueue = session.GetQueue( Destination );
var producer = session.CreateProducer( destinationQueue );
producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
var message = session.CreateTextMessage( RandomValueEx.GetRandomString() );
producer.Send( message );
Console.WriteLine( "Message sent" );
IDestination sourceQueue = session.GetQueue( Destination );
var consumer = session.CreateConsumer( sourceQueue );
var msg = consumer.Receive();
if ( msg is ITextMessage )
{
msg.Acknowledge();
Console.WriteLine( "Message received" );
}
else
Console.WriteLine( "Unexpected message type: " + msg.GetType()
.Name );
connection.Close();
}
}
}
| #region Usings
using System;
using Apache.NMS;
using Apache.NMS.Stomp;
using Extend;
#endregion
namespace Stomp.Net.Example.Producer
{
public class Program
{
#region Constants
private const String Destination = "TestQ";
private const String Host = "HOST";
private const String Password = "password";
private const Int32 Port = 60000;
private const String User = "admin";
#endregion
public static void Main( String[] args )
{
SendReceive();
Console.WriteLine( "Press <enter> to exit." );
Console.ReadLine();
}
private static void SendReceive()
{
var brokerUri = "stomp:tcp://" + Host + ":" + Port;
//var factory = new NMSConnectionFactory( brokerUri );
var factory = new ConnectionFactory( brokerUri );
// Create connection for both requests and responses
var connection = factory.CreateConnection( User, Password );
connection.Start();
// Create session for both requests and responses
var session = connection.CreateSession( AcknowledgementMode.IndividualAcknowledge );
IDestination destinationQueue = session.GetQueue( Destination );
var producer = session.CreateProducer( destinationQueue );
producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
var message = session.CreateTextMessage( RandomValueEx.GetRandomString() );
producer.Send( message );
Console.WriteLine( "Message sent" );
IDestination sourceQueue = session.GetQueue( Destination );
var consumer = session.CreateConsumer( sourceQueue );
var msg = consumer.Receive();
if ( msg is ITextMessage )
{
msg.Acknowledge();
Console.WriteLine( "Message received" );
}
else
Console.WriteLine( "Unexpected message type: " + msg.GetType()
.Name );
connection.Close();
}
}
}
| mit | C# |
27d2f9fd7ba59511586b3ae2769101d9d37ccdff | Update JsonUtility.cs | OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,phillipharding/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core | Core/OfficeDevPnP.Core/Utilities/JsonUtility.cs | Core/OfficeDevPnP.Core/Utilities/JsonUtility.cs | using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Utilities
{
/// <summary>
/// Utility class that supports the serialization from Json to type and vice versa
/// </summary>
public static class JsonUtility
{
/// <summary>
/// Serializes an object of type T to a json string
/// </summary>
/// <typeparam name="T">Type of obj</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>json string</returns>
public static string Serialize<T>(T obj)
{
//string retVal = null;
//using (MemoryStream ms = new MemoryStream())
//{
// System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
// serializer.WriteObject(ms, obj);
// retVal = Encoding.Default.GetString(ms.ToArray());
//}
//var s = new JavaScriptSerializer();
//var retVal = s.Serialize(obj);
//return retVal;
return JsonConvert.SerializeObject(obj) ;
}
/// <summary>
/// Deserializes a json string to an object of type T
/// </summary>
/// <typeparam name="T">Type of the returned object</typeparam>
/// <param name="json">json string</param>
/// <returns>Object of type T</returns>
public static T Deserialize<T>(string json)
{
//var obj = Activator.CreateInstance<T>();
//using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
//{
// System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
// obj = (T)serializer.ReadObject(ms);
//}
//var s = new JavaScriptSerializer();
//var obj = s.Deserialize<T>(json);
//return obj;
return JsonConvert.DeserializeObject<T>(json);
}
}
}
| using System.Web.Script.Serialization;
namespace OfficeDevPnP.Core.Utilities
{
/// <summary>
/// Utility class that supports the serialization from Json to type and vice versa
/// </summary>
public static class JsonUtility
{
/// <summary>
/// Serializes an object of type T to a json string
/// </summary>
/// <typeparam name="T">Type of obj</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>json string</returns>
public static string Serialize<T>(T obj)
{
//string retVal = null;
//using (MemoryStream ms = new MemoryStream())
//{
// System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
// serializer.WriteObject(ms, obj);
// retVal = Encoding.Default.GetString(ms.ToArray());
//}
var s = new JavaScriptSerializer();
var retVal = s.Serialize(obj);
return retVal;
}
/// <summary>
/// Deserializes a json string to an object of type T
/// </summary>
/// <typeparam name="T">Type of the returned object</typeparam>
/// <param name="json">json string</param>
/// <returns>Object of type T</returns>
public static T Deserialize<T>(string json)
{
//var obj = Activator.CreateInstance<T>();
//using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
//{
// System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
// obj = (T)serializer.ReadObject(ms);
//}
var s = new JavaScriptSerializer();
var obj = s.Deserialize<T>(json);
return obj;
}
}
}
| mit | C# |
a60909415d2b26cb951645cdbc5b684edc4de34b | Add an overload of `AddSystemFonts` | SixLabors/Fonts | src/SixLabors.Fonts/FontCollectionExtensions.cs | src/SixLabors.Fonts/FontCollectionExtensions.cs | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
namespace SixLabors.Fonts
{
/// <summary>
/// Extension methods for <see cref="IFontCollection"/>.
/// </summary>
public static class FontCollectionExtensions
{
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection)
{
// This cast is safe because our underlying SystemFontCollection implements
// both interfaces separately.
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
return collection;
}
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <param name="match">The System.Predicate delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match)
{
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
if (match(metric))
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
}
return collection;
}
}
}
| // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts
{
/// <summary>
/// Extension methods for <see cref="IFontCollection"/>.
/// </summary>
public static class FontCollectionExtensions
{
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection)
{
// This cast is safe because our underlying SystemFontCollection implements
// both interfaces separately.
foreach (FontMetrics? metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
return collection;
}
}
}
| apache-2.0 | C# |
4ffacef1b103f4ee0ee3212f2a5d7949acc35132 | Clean up Utf8StringPerf benchmark | ericstj/corefxlab,ericstj/corefxlab,KrzysztofCwalina/corefxlab,stephentoub/corefxlab,whoisj/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,joshfree/corefxlab,stephentoub/corefxlab,adamsitnik/corefxlab,ericstj/corefxlab,tarekgh/corefxlab,benaadams/corefxlab,ericstj/corefxlab,dotnet/corefxlab,ahsonkhan/corefxlab,whoisj/corefxlab,stephentoub/corefxlab,adamsitnik/corefxlab,dotnet/corefxlab,joshfree/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,KrzysztofCwalina/corefxlab,ericstj/corefxlab,tarekgh/corefxlab,benaadams/corefxlab,ahsonkhan/corefxlab | tests/Benchmarks/System.Text.Utf8/Utf8StringPerf.cs | tests/Benchmarks/System.Text.Utf8/Utf8StringPerf.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 BenchmarkDotNet.Attributes;
namespace System.Text.Utf8.Benchmarks
{
public class Utf8StringPerf
{
[Params(TestCaseType.ShortAscii, TestCaseType.ShortMultiByte, TestCaseType.LongAscii, TestCaseType.LongMultiByte)]
public TestCaseType TestCase;
private string _string;
private Utf8String _utf8String;
[GlobalSetup]
public void Setup()
{
int length;
int maxCodePoint;
switch (TestCase)
{
case TestCaseType.ShortAscii:
{ length = 5; maxCodePoint = 126; break; }
case TestCaseType.ShortMultiByte:
{ length = 5; maxCodePoint = 0xD7FF; break; }
case TestCaseType.LongAscii:
{ length = 50000; maxCodePoint = 126; break; }
case TestCaseType.LongMultiByte:
{ length = 50000; maxCodePoint = 0xD7FF; break; }
default:
throw new InvalidOperationException();
}
// the length of the string is same across the runs, so the content of the string can be random for this particular benchmarks
_string = GetRandomString(length, 32, maxCodePoint);
_utf8String = new Utf8String(_string);
}
[Benchmark]
public Utf8String ConstructFromString() => new Utf8String(_string);
[Benchmark]
public uint EnumerateCodePoints()
{
uint retVal = default;
foreach (uint codePoint in _utf8String)
{
retVal = codePoint;
}
return retVal;
}
private string GetRandomString(int length, int minCodePoint, int maxCodePoint)
{
Random r = new Random(42);
StringBuilder sb = new StringBuilder(length);
while (length-- != 0)
{
sb.Append((char)r.Next(minCodePoint, maxCodePoint));
}
return sb.ToString();
}
public enum TestCaseType
{
ShortAscii,
ShortMultiByte,
LongAscii,
LongMultiByte
}
}
}
| // 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 BenchmarkDotNet.Attributes;
namespace System.Text.Utf8.Benchmarks
{
public class Utf8StringPerf
{
[Params(5, 50000)]
public int Length;
[Params(126, 0xD7FF)]
public int MaxCodePoint;
private string randomString;
private Utf8String utf8String;
[GlobalSetup]
public void Setup()
{
// the length of the string is same across the runs, so the content of the string can be random for this particular benchmarks
randomString = GetRandomString(Length, 32, MaxCodePoint);
utf8String = new Utf8String(randomString);
}
[Benchmark]
public Utf8String ConstructFromString() => new Utf8String(randomString);
[Benchmark]
public void EnumerateCodePoints()
{
foreach (uint codePoint in utf8String)
{
}
}
private string GetRandomString(int length, int minCodePoint, int maxCodePoint)
{
Random r = new Random(42);
StringBuilder sb = new StringBuilder(length);
while (length-- != 0)
{
sb.Append((char)r.Next(minCodePoint, maxCodePoint));
}
return sb.ToString();
}
}
}
| mit | C# |
545dabff307bca42e1527748195c2ad9007ba567 | Use generic implementation | peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework | osu.Framework/Input/JoystickButtonEventManager.cs | osu.Framework/Input/JoystickButtonEventManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
namespace osu.Framework.Input
{
public class JoystickButtonEventManager : ButtonEventManager<JoystickButton>
{
public JoystickButtonEventManager(JoystickButton button)
: base(button)
{
}
protected override Drawable HandleButtonDown(InputState state, List<Drawable> targets) => PropagateButtonEvent(targets, new JoystickPressEvent(state, Button));
protected override void HandleButtonUp(InputState state, List<Drawable> targets)
{
if (targets == null)
return;
PropagateButtonEvent(targets, new JoystickReleaseEvent(state, Button));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
namespace osu.Framework.Input
{
public class JoystickButtonEventManager : ButtonEventManager
{
/// <summary>
/// The joystick button this manager manages.
/// </summary>
public readonly JoystickButton Button;
public JoystickButtonEventManager(JoystickButton button)
{
Button = button;
}
protected override Drawable HandleButtonDown(InputState state, List<Drawable> targets) => PropagateButtonEvent(targets, new JoystickPressEvent(state, Button));
protected override void HandleButtonUp(InputState state, List<Drawable> targets)
{
if (targets == null)
return;
PropagateButtonEvent(targets, new JoystickReleaseEvent(state, Button));
}
}
}
| mit | C# |
75aba48634fc279152cfadec683fbec29e969e14 | fix seucrity issue for subnav links | Mozu/mozu-dotnet-webtoolkit,sanjaymandadi/mozu-dotnet-webtoolkit | Mozu.Api.WebToolKit/Filters/ConfigurationAuthFilter.cs | Mozu.Api.WebToolKit/Filters/ConfigurationAuthFilter.cs | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Mozu.Api.Logging;
using Mozu.Api.Resources.Platform;
using Mozu.Api.Security;
namespace Mozu.Api.WebToolKit.Filters
{
[AttributeUsage(AttributeTargets.Method)]
public class ConfigurationAuthFilter : ActionFilterAttribute
{
private readonly ILogger _logger = LogManager.GetLogger(typeof(ConfigurationAuthFilter));
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (!ConfigurationAuth.IsRequestValid(filterContext.HttpContext.Request))
throw new UnauthorizedAccessException();
var request = filterContext.RequestContext.HttpContext.Request;
var apiContext = new ApiContext(request.Headers); //try to load from headers
if (apiContext.TenantId == 0) //try to load from body
apiContext = new ApiContext(request.Params);
if (apiContext.TenantId == 0) //if not found load from query string
{
var tenantId = request.QueryString.Get("tenantId");
if (String.IsNullOrEmpty(tenantId))
throw new UnauthorizedAccessException();
apiContext = new ApiContext(int.Parse(tenantId));
}
try
{
var tenantResource = new TenantResource();
var tenant = Task.Factory.StartNew(() => tenantResource.GetTenantAsync(apiContext.TenantId).Result, TaskCreationOptions.LongRunning).Result;
}
catch (ApiException exc)
{
_logger.Error(exc);
throw new Exception(exc.Message);
}
}
}
}
| using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Mozu.Api.Logging;
using Mozu.Api.Resources.Platform;
using Mozu.Api.Security;
namespace Mozu.Api.WebToolKit.Filters
{
[AttributeUsage(AttributeTargets.Method)]
public class ConfigurationAuthFilter : ActionFilterAttribute
{
private readonly ILogger _logger = LogManager.GetLogger(typeof(ConfigurationAuthFilter));
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (!ConfigurationAuth.IsRequestValid(filterContext.HttpContext.Request))
throw new UnauthorizedAccessException();
var request = filterContext.RequestContext.HttpContext.Request;
var apiContext = new ApiContext(request.Headers);
if (apiContext.TenantId == 0)
{
apiContext = new ApiContext(int.Parse(request.QueryString.Get("tenantId")));
}
try
{
var tenantResource = new TenantResource();
var tenant = Task.Factory.StartNew(() => tenantResource.GetTenantAsync(apiContext.TenantId).Result, TaskCreationOptions.LongRunning).Result;
}
catch (ApiException exc)
{
_logger.Error(exc);
throw new Exception(exc.Message);
}
}
}
}
| mit | C# |
90cda7a0ce9fab9c08d8e9e4bf805dd0407d6ea2 | reformat app builder | wangkanai/Detection | src/DependencyInjection/DetectionBuilder.cs | src/DependencyInjection/DetectionBuilder.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper functions for configuring detection services.
/// </summary>
public class DetectionBuilder : IDetectionBuilder
{
/// <summary>
/// Creates a new instance of <see cref="DetectionBuilder" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to attach to.</param>
public DetectionBuilder(IServiceCollection services)
=> Services = services ?? throw new ArgumentNullException(nameof(services));
/// <summary>
/// Gets the <see cref="IServiceCollection" /> services are attached to.
/// </summary>
/// <value>
/// The <see cref="IServiceCollection" /> services are attached to.
/// </value>
public IServiceCollection Services { get; }
}
} | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper functions for configuring detection services.
/// </summary>
public class DetectionBuilder : IDetectionBuilder
{
/// <summary>
/// Creates a new instance of <see cref="DetectionBuilder" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to attach to.</param>
public DetectionBuilder(IServiceCollection services)
=> Services = services ?? throw new ArgumentNullException(nameof(services));
/// <summary>
/// Gets the <see cref="IServiceCollection" /> services are attached to.
/// </summary>
/// <value>
/// The <see cref="IServiceCollection" /> services are attached to.
/// </value>
public IServiceCollection Services { get; }
}
} | apache-2.0 | C# |
0b447d3ddd73e0bc1c47514f242930ac13475e98 | Remove ViewLogic Validation on Edit Settings Screen | tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS | Portal.CMS.Web/Areas/Admin/Views/Settings/_Edit.cshtml | Portal.CMS.Web/Areas/Admin/Views/Settings/_Edit.cshtml | @model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel
@{
Layout = "";
}
@using (Html.BeginForm("Edit", "Settings", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.SettingId)
@Html.ValidationMessage("SettingName")
<div class="control-group float-container">
@Html.LabelFor(x => x.SettingName)
@Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" })
</div>
<div class="control-group float-container">
@Html.LabelFor(x => x.SettingValue)
@Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" })
</div>
<br />
<div class="footer">
<button class="btn primary">Save</button>
<a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a>
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
} | @model Portal.CMS.Web.Areas.Admin.ViewModels.Settings.EditViewModel
@{
Layout = "";
}
@using (Html.BeginForm("Edit", "Settings", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.SettingId)
@Html.ValidationMessage("SettingName")
<div class="control-group float-container">
@Html.LabelFor(x => x.SettingName)
@if (Model.SettingName != "Website Name")
{
@Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name" })
}
else
{
@Html.TextBoxFor(x => x.SettingName, new { placeholder = "Setting Name", @readonly="true" })
}
</div>
<div class="control-group float-container">
@Html.LabelFor(x => x.SettingValue)
@Html.TextBoxFor(x => x.SettingValue, new { placeholder = "Setting Value" })
</div>
<br />
<div class="footer">
<button class="btn primary">Save</button>
@if (Model.SettingName != "Website Name")
{
<a href="@Url.Action("Delete", "Settings", new { settingId = Model.SettingId })" class="btn delete">Delete</a>
}
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
} | mit | C# |
7f72bcd0aac12b180bbcc463e074def4e957be5f | Add instant-timestamp conversions | PietroProperties/holms.platformclient.net | csharp/HOLMS.Platform/HOLMS.Platform/Support/Conversions/DateTimeConversions.cs | csharp/HOLMS.Platform/HOLMS.Platform/Support/Conversions/DateTimeConversions.cs | using System;
using Google.Protobuf.WellKnownTypes;
using NodaTime;
namespace HOLMS.Support.Conversions {
public static class DateTimeConversions {
public static Timestamp ToTS(this DateTime dt) =>
Timestamp.FromDateTime(dt.ToUniversalTime());
public static LocalDate ToLD(this Timestamp ts) {
var dt = ts.ToDateTime();
return new LocalDate(dt.Year, dt.Month, dt.Day);
}
public static Instant ToInstant(this Timestamp ts) {
return Instant.FromDateTimeUtc(ts.ToDateTime().ToUniversalTime());
}
public static Timestamp ToTS(this Instant ins) {
return ins.ToDateTimeUtc().ToTS();
}
}
}
| using System;
using Google.Protobuf.WellKnownTypes;
using NodaTime;
namespace HOLMS.Support.Conversions {
public static class DateTimeConversions {
public static Timestamp ToTS(this DateTime dt) =>
Timestamp.FromDateTime(dt.ToUniversalTime());
public static LocalDate ToLD(this Timestamp ts) {
var dt = ts.ToDateTime();
return new LocalDate(dt.Year, dt.Month, dt.Day);
}
}
}
| mit | C# |
ef0bf06b202803fffa76c327c5c65ba26b11fc43 | Add default message to CurrencyNotFoundException. | chtoucas/Narvalo.NET,chtoucas/Narvalo.NET | src/Narvalo.Finance/CurrencyNotFoundException.cs | src/Narvalo.Finance/CurrencyNotFoundException.cs | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Finance
{
using System;
using Narvalo.Finance.Properties;
/// <summary>
/// The exception thrown when a method is invoked which attempts to construct
/// a currency that is not available.
/// </summary>
public class CurrencyNotFoundException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with its message string set to a system-supplied message.
/// </summary>
public CurrencyNotFoundException() : base(Strings.CurrencyNotFoundException_DefaultMessage) { }
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with the specified error message.
/// </summary>
/// <param name="message">The error message to display with this exception.</param>
public CurrencyNotFoundException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with a specified error message and a reference to the inner exception
/// that is the cause of this exception.
/// </summary>
/// <param name="message">The error message to display with this exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception.
/// If the innerException parameter is not a null reference, the current exception is raised
/// in a catch block that handles the inner exception.</param>
public CurrencyNotFoundException(string message, Exception innerException) :
base(message, innerException) { }
}
}
| // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Finance
{
using System;
/// <summary>
/// The exception thrown when a method is invoked which attempts to construct
/// a currency that is not available.
/// </summary>
public class CurrencyNotFoundException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with its message string set to a system-supplied message.
/// </summary>
public CurrencyNotFoundException() { }
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with the specified error message.
/// </summary>
/// <param name="message">The error message to display with this exception.</param>
public CurrencyNotFoundException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyNotFoundException"/>
/// class with a specified error message and a reference to the inner exception
/// that is the cause of this exception.
/// </summary>
/// <param name="message">The error message to display with this exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception.
/// If the innerException parameter is not a null reference, the current exception is raised
/// in a catch block that handles the inner exception.</param>
public CurrencyNotFoundException(string message, Exception innerException) :
base(message, innerException) { }
}
}
| bsd-2-clause | C# |
64c6155ae76cf6e3eef083a9839fd3ef5df6bac3 | Fix ResultLimitAttribute to actually throw on error conditions | scz2011/WebApi,congysu/WebApi,LianwMS/WebApi,chimpinano/WebApi,abkmr/WebApi,lungisam/WebApi,yonglehou/WebApi,chimpinano/WebApi,yonglehou/WebApi,lewischeng-ms/WebApi,LianwMS/WebApi,lewischeng-ms/WebApi,scz2011/WebApi,lungisam/WebApi,abkmr/WebApi,congysu/WebApi | src/System.Web.Http/ResultLimitAttribute.cs | src/System.Web.Http/ResultLimitAttribute.cs | using System.Collections;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Common;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Properties;
using System.Web.Http.Query;
namespace System.Web.Http
{
/// <summary>
/// This result filter indicates that the results returned from an action should
/// be limited to the specified ResultLimit.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class ResultLimitAttribute : ActionFilterAttribute
{
private int _resultLimit;
public ResultLimitAttribute(int resultLimit)
{
_resultLimit = resultLimit;
}
public int ResultLimit
{
get { return _resultLimit; }
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
Contract.Assert(actionContext.ControllerContext.Request != null);
if (_resultLimit <= 0)
{
throw Error.ArgumentOutOfRange("resultLimit", _resultLimit, SRResources.ResultLimitFilter_OutOfRange, actionContext.ActionDescriptor.ActionName);
}
HttpActionDescriptor action = actionContext.ActionDescriptor;
if (!typeof(IEnumerable).IsAssignableFrom(action.ReturnType))
{
throw Error.InvalidOperation(SRResources.ResultLimitFilter_InvalidReturnType, action.ActionName);
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext == null)
{
throw Error.ArgumentNull("actionExecutedContext");
}
Contract.Assert(actionExecutedContext.Request != null);
HttpResponseMessage response = actionExecutedContext.Result;
IEnumerable results;
if (response != null && response.TryGetContentValue(out results))
{
// apply the result limit
results = results.AsQueryable().Take(_resultLimit);
((ObjectContent)response.Content).Value = results;
}
}
}
}
| using System.Collections;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Common;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Properties;
using System.Web.Http.Query;
namespace System.Web.Http
{
/// <summary>
/// This result filter indicates that the results returned from an action should
/// be limited to the specified ResultLimit.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class ResultLimitAttribute : ActionFilterAttribute
{
private int _resultLimit;
public ResultLimitAttribute(int resultLimit)
{
_resultLimit = resultLimit;
}
public int ResultLimit
{
get { return _resultLimit; }
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
Contract.Assert(actionContext.ControllerContext.Request != null);
if (_resultLimit <= 0)
{
Error.ArgumentOutOfRange("resultLimit", _resultLimit, SRResources.ResultLimitFilter_OutOfRange, actionContext.ActionDescriptor.ActionName);
}
HttpActionDescriptor action = actionContext.ActionDescriptor;
if (!typeof(IEnumerable).IsAssignableFrom(action.ReturnType))
{
Error.InvalidOperation(SRResources.ResultLimitFilter_InvalidReturnType, action.ActionName);
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext == null)
{
throw Error.ArgumentNull("actionExecutedContext");
}
Contract.Assert(actionExecutedContext.Request != null);
HttpResponseMessage response = actionExecutedContext.Result;
IEnumerable results;
if (response != null && response.TryGetContentValue(out results))
{
// apply the result limit
results = results.AsQueryable().Take(_resultLimit);
((ObjectContent)response.Content).Value = results;
}
}
}
}
| mit | C# |
3c7ddabc948e10c351557ac95915e09bb3846ae1 | use interface context | WojcikMike/docs.particular.net | Snippets/Snippets_6/Headers/OutgoingBehavior.cs | Snippets/Snippets_6/Headers/OutgoingBehavior.cs | namespace Snippets6.Headers
{
using System;
using System.Threading.Tasks;
using NServiceBus.OutgoingPipeline;
using NServiceBus.Pipeline;
#region header-outgoing-behavior
public class OutgoingBehavior : Behavior<IOutgoingPhysicalMessageContext>
{
public override async Task Invoke(IOutgoingPhysicalMessageContext context, Func<Task> next)
{
context.Headers["MyCustomHeader"] = "My custom value";
await next();
}
}
#endregion
} | namespace Snippets6.Headers
{
using System;
using System.Threading.Tasks;
using NServiceBus.OutgoingPipeline;
using NServiceBus.Pipeline;
#region header-outgoing-behavior
public class OutgoingBehavior : Behavior<OutgoingPhysicalMessageContext>
{
public override async Task Invoke(OutgoingPhysicalMessageContext context, Func<Task> next)
{
context.Headers["MyCustomHeader"] = "My custom value";
await next();
}
}
#endregion
} | apache-2.0 | C# |
18947f4c6d2d16e5e1493a13c6a2460829face8c | Revert "Make DisposeMethodKind internal to avoid conflicts" | mavasani/roslyn-analyzers,pakdev/roslyn-analyzers,dotnet/roslyn-analyzers,pakdev/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers | src/Utilities/Compiler/DisposeMethodKind.cs | src/Utilities/Compiler/DisposeMethodKind.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Analyzer.Utilities
{
/// <summary>
/// Describes different kinds of Dispose-like methods.
/// </summary>
public enum DisposeMethodKind
{
/// <summary>
/// Not a dispose-like method.
/// </summary>
None,
/// <summary>
/// An override of <see cref="System.IDisposable.Dispose"/>.
/// </summary>
Dispose,
/// <summary>
/// A virtual method named Dispose that takes a single Boolean parameter, as
/// is used when implementing the standard Dispose pattern.
/// </summary>
DisposeBool,
/// <summary>
/// A method named DisposeAsync that has no parameters and returns Task.
/// </summary>
DisposeAsync,
/// <summary>
/// An overridden method named DisposeCoreAsync that takes a single Boolean parameter and returns Task, as
/// is used when implementing the standard DisposeAsync pattern.
/// </summary>
DisposeCoreAsync,
/// <summary>
/// A method named Close on a type that implements <see cref="System.IDisposable"/>.
/// </summary>
Close
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Analyzer.Utilities
{
/// <summary>
/// Describes different kinds of Dispose-like methods.
/// </summary>
internal enum DisposeMethodKind
{
/// <summary>
/// Not a dispose-like method.
/// </summary>
None,
/// <summary>
/// An override of <see cref="System.IDisposable.Dispose"/>.
/// </summary>
Dispose,
/// <summary>
/// A virtual method named Dispose that takes a single Boolean parameter, as
/// is used when implementing the standard Dispose pattern.
/// </summary>
DisposeBool,
/// <summary>
/// A method named DisposeAsync that has no parameters and returns Task.
/// </summary>
DisposeAsync,
/// <summary>
/// An overridden method named DisposeCoreAsync that takes a single Boolean parameter and returns Task, as
/// is used when implementing the standard DisposeAsync pattern.
/// </summary>
DisposeCoreAsync,
/// <summary>
/// A method named Close on a type that implements <see cref="System.IDisposable"/>.
/// </summary>
Close
}
}
| mit | C# |
64762d9af8db3c7fb1d842e24fb7146421b8bc23 | Fix documentation. | SonnevilleJ/Investing,SonnevilleJ/Investing | Sonneville.Fidelity.Shell/Interface/ICommand.cs | Sonneville.Fidelity.Shell/Interface/ICommand.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace Sonneville.Fidelity.Shell.Interface
{
public interface ICommand : IDisposable
{
/// <summary>
/// The name of the command. Users will invoke the command by typing the name of the command.
/// </summary>
string CommandName { get; }
/// <summary>
/// Invoke the command.
/// </summary>
/// <param name="inputReader">A <see cref="TextReader"/> used to accept input from the user. Typically <see cref="System.Console.In"/>.</param>
/// <param name="outputWriter">A <see cref="TextWriter"/> used to provide output to the user. Typically <see cref="System.Console.Out"/>.</param>
/// <param name="fullInput">The full command entered by the user. The first value will always be the name of the command.</param>
/// <returns>A bool indicating whether or not the system should exit upon completion of the invocation.</returns>
bool Invoke(TextReader inputReader, TextWriter outputWriter, IReadOnlyList<string> fullInput);
}
} | using System;
using System.Collections.Generic;
using System.IO;
namespace Sonneville.Fidelity.Shell.Interface
{
public interface ICommand : IDisposable
{
/// <summary>
/// The name of the command. Users will invoke the command by typing the name of the command.
/// </summary>
string CommandName { get; }
/// <summary>
/// Invoke the command.
/// </summary>
/// <param name="inputReader">A <see cref="TextReader"/> used to accept input from the user. Typically <see cref="System.In"/>.</param>
/// <param name="outputWriter">A <see cref="TextWriter"/> used to provide output to the user. Typically <see cref="System.Out"/>.</param>
/// <param name="fullInput">The full command entered by the user. The first value will always be the name of the command.</param>
/// <returns>A bool indicating whether or not the system should exit upon completion of the invocation.</returns>
bool Invoke(TextReader inputReader, TextWriter outputWriter, IReadOnlyList<string> fullInput);
}
} | mit | C# |
4adde4f0de10a1edcc2cc067e0fb7a7edcf988e8 | Update `SpecFlowHooks` to add screenshot files to SpecFlow output | atata-framework/atata-samples | SpecFlow/AtataSamples.SpecFlow/SpecFlowHooks.cs | SpecFlow/AtataSamples.SpecFlow/SpecFlowHooks.cs | using Atata;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Infrastructure;
namespace AtataSamples.SpecFlow
{
[Binding]
public sealed class SpecFlowHooks
{
private readonly ISpecFlowOutputHelper _outputHelper;
public SpecFlowHooks(ISpecFlowOutputHelper outputHelper)
{
_outputHelper = outputHelper;
}
[BeforeTestRun]
public static void SetUpTestRun()
{
AtataContext.GlobalConfiguration
.UseChrome()
.WithArguments("start-maximized")
.UseBaseUrl("https://demo.atata.io/")
.UseCulture("en-US")
.UseNUnitTestName()
.UseNUnitTestSuiteName()
.UseNUnitTestSuiteType()
.UseNUnitAssertionExceptionType()
.UseNUnitAggregateAssertionStrategy()
.UseNUnitWarningReportStrategy()
.LogNUnitError()
.TakeScreenshotOnNUnitError()
.AddScreenshotFileSaving()
.WithArtifactsFolderPath();
AtataContext.GlobalConfiguration.AutoSetUpDriverToUse();
}
[BeforeScenario]
public void SetUpScenario()
{
AtataContext.Configure()
.EventSubscriptions.Add<ScreenshotFileSavedEvent>(eventData => _outputHelper.AddAttachment(eventData.FilePath))
.AddLogConsumer(new TextOutputLogConsumer(_outputHelper.WriteLine))
.Build();
}
[AfterScenario]
public void TearDownScenario()
{
AtataContext.Current?.CleanUp();
}
}
}
| using Atata;
using TechTalk.SpecFlow;
namespace AtataSamples.SpecFlow
{
[Binding]
public sealed class SpecFlowHooks
{
// For additional details on SpecFlow hooks see http://go.specflow.org/doc-hooks
[BeforeTestRun]
public static void SetUpTestRun()
{
AtataContext.GlobalConfiguration
.UseChrome()
.WithArguments("start-maximized")
.UseBaseUrl("https://demo.atata.io/")
.UseCulture("en-US")
.UseAllNUnitFeatures();
AtataContext.GlobalConfiguration.AutoSetUpDriverToUse();
}
[BeforeScenario]
public static void SetUpScenario()
{
AtataContext.Configure().Build();
}
[AfterScenario]
public static void TearDownScenario()
{
AtataContext.Current?.CleanUp();
}
}
}
| apache-2.0 | C# |
016afaa9fb875105388791ea274f6918f642e1a3 | Exclude test utility from coverage | tsqllint/tsqllint,tsqllint/tsqllint | TSQLLint.Tests/Helpers/RuleViolationComparer.cs | TSQLLint.Tests/Helpers/RuleViolationComparer.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using TSQLLint.Lib.Rules.RuleViolations;
namespace TSQLLint.Tests.Helpers
{
[ExcludeFromCodeCoverage]
public class RuleViolationComparer : IComparer, IComparer<RuleViolation>
{
public int Compare(object x, object y)
{
if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs))
{
throw new InvalidOperationException("cannot compare null object");
}
return Compare(lhs, rhs);
}
public int Compare(RuleViolation left, RuleViolation right)
{
if (right != null && left != null && left.Line != right.Line)
{
return -1;
}
if (right != null && left != null && left.Column != right.Column)
{
return -1;
}
if (right != null && left != null && left.RuleName != right.RuleName)
{
return -1;
}
return 0;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using TSQLLint.Lib.Rules.RuleViolations;
namespace TSQLLint.Tests.Helpers
{
public class RuleViolationComparer : IComparer, IComparer<RuleViolation>
{
public int Compare(object x, object y)
{
if (!(x is RuleViolation lhs) || !(y is RuleViolation rhs))
{
throw new InvalidOperationException("cannot compare null object");
}
return Compare(lhs, rhs);
}
public int Compare(RuleViolation left, RuleViolation right)
{
if (right != null && left != null && left.Line != right.Line)
{
return -1;
}
if (right != null && left != null && left.Column != right.Column)
{
return -1;
}
if (right != null && left != null && left.RuleName != right.RuleName)
{
return -1;
}
return 0;
}
}
}
| mit | C# |
b6e46643c40645b9d96996c38afee6b463895e63 | Update comments | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using System;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private NavigationStateViewModel _navigationState;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogViewModelBase _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
// TODO: Set Dialog with IScreen implementation
// TODO: Set default NextView
// TODO: Set default CancelView
_navigationState = new NavigationStateViewModel()
{
Screen = () => this
};
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(_navigationState, Router, global.WalletManager, global.UiConfig);
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogViewModelBase CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialogs;
using System;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private NavigationStateViewModel _navigationState;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogViewModelBase _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
_navigationState = new NavigationStateViewModel()
{
Screen = () => this,
// TODO: Add IScreen implementation to Dialog from main view
Dialog = () => this
// TODO: NextView
// TODO: CancelView
};
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(_navigationState, Router, global.WalletManager, global.UiConfig);
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogViewModelBase CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| mit | C# |
69a2838f0f3c0d97f11024a4113ab69e60b47929 | Extend Locations & EndPointCommands models | MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings | DynThings.Data.Models/ModelsExtensions/Location.cs | DynThings.Data.Models/ModelsExtensions/Location.cs | /////////////////////////////////////////////////////////////////
// Created by : Caesar Moussalli //
// TimeStamp : 31-1-2016 //
// Content : Extend the properties of Location Model //
// Notes : Don't add Behavior in this class //
/////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DynThings.Data.Models
{
public partial class Location
{
private DynThingsEntities db = new DynThingsEntities();
/// <summary>
/// Get List of associated Endpoints
/// </summary>
public List<Endpoint> EndPoints
{
get
{
List<Endpoint> ends = new List<Endpoint>();
List<LinkEndpointsLocation> lnks = db.LinkEndpointsLocations.Where(l => l.LocationID == this.ID).ToList();
foreach (LinkEndpointsLocation lnk in lnks)
{
ends.Add(lnk.Endpoint);
}
return ends;
}
}
public List<LocationView> locationViews
{
get
{
List<LocationView> locs = new List<LocationView>();
List<LinkLocationsLocationView> lnks = db.LinkLocationsLocationViews.Where(l => l.LocationID == this.ID).ToList();
foreach (LinkLocationsLocationView lnk in lnks)
{
locs.Add(lnk.LocationView);
}
return locs;
}
}
}
}
| /////////////////////////////////////////////////////////////////
// Created by : Caesar Moussalli //
// TimeStamp : 31-1-2016 //
// Content : Extend the properties of Location Model //
// Notes : Don't add Behavior in this class //
/////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DynThings.Data.Models
{
public partial class Location
{
private DynThingsEntities db = new DynThingsEntities();
/// <summary>
/// Get List of associated Endpoints
/// </summary>
public List<Endpoint> EndPoints
{
get
{
List<Endpoint> ends = new List<Endpoint>();
List<LinkEndpointsLocation> lnks = db.LinkEndpointsLocations.Where(l => l.LocationID == this.ID).ToList();
foreach (LinkEndpointsLocation lnk in lnks)
{
ends.Add(lnk.Endpoint);
}
return ends;
}
}
}
}
| mit | C# |
0a32b360b0e006bf9c053aa1a81f1132587895d8 | Fix for previous minor refactoring. | lemestrez/aspnetboilerplate,ilyhacker/aspnetboilerplate,ddNils/aspnetboilerplate,takintsft/aspnetboilerplate,ddNils/aspnetboilerplate,ryancyq/aspnetboilerplate,4nonym0us/aspnetboilerplate,4nonym0us/aspnetboilerplate,Saviio/aspnetboilerplate,ryancyq/aspnetboilerplate,lvjunlei/aspnetboilerplate,verdentk/aspnetboilerplate,Tobyee/aspnetboilerplate,s-takatsu/aspnetboilerplate,virtualcca/aspnetboilerplate,liujunhua/aspnetboilerplate,gentledepp/aspnetboilerplate,asauriol/aspnetboilerplate,sagacite2/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,zclmoon/aspnetboilerplate,ZhaoRd/aspnetboilerplate,jaq316/aspnetboilerplate,ddNils/aspnetboilerplate,nineconsult/Kickoff2016Net,verdentk/aspnetboilerplate,gentledepp/aspnetboilerplate,ZhaoRd/aspnetboilerplate,burakaydemir/aspnetboilerplate,berdankoca/aspnetboilerplate,lvjunlei/aspnetboilerplate,zquans/aspnetboilerplate,690486439/aspnetboilerplate,zclmoon/aspnetboilerplate,carldai0106/aspnetboilerplate,SXTSOFT/aspnetboilerplate,chenkaibin/aspnetboilerplate,yuzukwok/aspnetboilerplate,ShiningRush/aspnetboilerplate,daywrite/aspnetboilerplate,lemestrez/aspnetboilerplate,jaq316/aspnetboilerplate,backendeveloper/aspnetboilerplate,FJQBT/ABP,Tobyee/aspnetboilerplate,asauriol/aspnetboilerplate,jefferyzhang/aspnetboilerplate,s-takatsu/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,lemestrez/aspnetboilerplate,fengyeju/aspnetboilerplate,690486439/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,spraiin/aspnetboilerplate,oceanho/aspnetboilerplate,saeedallahyari/aspnetboilerplate,carldai0106/aspnetboilerplate,saeedallahyari/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AndHuang/aspnetboilerplate,virtualcca/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,yuzukwok/aspnetboilerplate,daywrite/aspnetboilerplate,MDSNet2016/aspnetboilerplate,berdankoca/aspnetboilerplate,yuzukwok/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,andmattia/aspnetboilerplate,4nonym0us/aspnetboilerplate,chenkaibin/aspnetboilerplate,fengyeju/aspnetboilerplate,beratcarsi/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,fengyeju/aspnetboilerplate,lvjunlei/aspnetboilerplate,ZhaoRd/aspnetboilerplate,daywrite/aspnetboilerplate,liujunhua/aspnetboilerplate,SXTSOFT/aspnetboilerplate,nineconsult/Kickoff2016Net,oceanho/aspnetboilerplate,Nongzhsh/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,jefferyzhang/aspnetboilerplate,yhhno/aspnetboilerplate,AlexGeller/aspnetboilerplate,AndHuang/aspnetboilerplate,backendeveloper/aspnetboilerplate,jaq316/aspnetboilerplate,cato541265/aspnetboilerplate,Nongzhsh/aspnetboilerplate,Tinkerc/aspnetboilerplate,zquans/aspnetboilerplate,Saviio/aspnetboilerplate,berdankoca/aspnetboilerplate,chendong152/aspnetboilerplate,s-takatsu/aspnetboilerplate,ShiningRush/aspnetboilerplate,virtualcca/aspnetboilerplate,SXTSOFT/aspnetboilerplate,AlexGeller/aspnetboilerplate,yhhno/aspnetboilerplate,AntTech/aspnetboilerplate,AndHuang/aspnetboilerplate,chendong152/aspnetboilerplate,690486439/aspnetboilerplate,sagacite2/aspnetboilerplate,ShiningRush/aspnetboilerplate,burakaydemir/aspnetboilerplate,oceanho/aspnetboilerplate,takintsft/aspnetboilerplate,ryancyq/aspnetboilerplate,AlexGeller/aspnetboilerplate,cato541265/aspnetboilerplate,zquans/aspnetboilerplate,Tinkerc/aspnetboilerplate,beratcarsi/aspnetboilerplate,AntTech/aspnetboilerplate,spraiin/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,FJQBT/ABP,chenkaibin/aspnetboilerplate,luchaoshuai/aspnetboilerplate,MDSNet2016/aspnetboilerplate,andmattia/aspnetboilerplate,Tobyee/aspnetboilerplate,andmattia/aspnetboilerplate,verdentk/aspnetboilerplate | src/Abp/Auditing/AuditingInterceptorRegistrar.cs | src/Abp/Auditing/AuditingInterceptorRegistrar.cs | using System;
using System.Linq;
using Abp.Dependency;
using Castle.Core;
using Castle.MicroKernel;
namespace Abp.Auditing
{
internal class AuditingInterceptorRegistrar
{
private readonly IIocManager _iocManager;
private readonly IAuditingConfiguration _auditingConfiguration;
public AuditingInterceptorRegistrar(IIocManager iocManager)
{
_iocManager = iocManager;
_auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>();
}
public void Initialize()
{
if (!_auditingConfiguration.IsEnabled)
{
return;
}
_iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
}
private void Kernel_ComponentRegistered(string key, IHandler handler)
{
if (ShouldIntercept(handler.ComponentModel.Implementation))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
}
}
private bool ShouldIntercept(Type type)
{
if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
{
return true;
}
if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false?
{
return true;
}
if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false?
{
return true;
}
return false;
}
}
} | using System;
using System.Linq;
using Abp.Dependency;
using Castle.Core;
using Castle.MicroKernel;
namespace Abp.Auditing
{
internal class AuditingInterceptorRegistrar
{
private readonly IAuditingConfiguration _auditingConfiguration;
private readonly IIocManager _iocManager;
public AuditingInterceptorRegistrar(IIocManager iocManager)
{
_auditingConfiguration = _iocManager.Resolve<IAuditingConfiguration>();
_iocManager = iocManager;
}
public void Initialize()
{
if (!_auditingConfiguration.IsEnabled)
{
return;
}
_iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
}
private void Kernel_ComponentRegistered(string key, IHandler handler)
{
if (ShouldIntercept(handler.ComponentModel.Implementation))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
}
}
private bool ShouldIntercept(Type type)
{
if (_auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
{
return true;
}
if (type.IsDefined(typeof(AuditedAttribute), true)) //TODO: true or false?
{
return true;
}
if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true))) //TODO: true or false?
{
return true;
}
return false;
}
}
} | mit | C# |
bd6d408c6fb80f299ff0506559024e9398f8ed86 | bump version | raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2 | source/Raml.Parser/Properties/AssemblyInfo.cs | source/Raml.Parser/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("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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")] | 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("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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.4")] | apache-2.0 | C# |
9edecc81ff798bab6762dc34207e5547c8ceae2c | Use invoke explicitly | FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp | src/AngleSharp/Extensions/EventLoopExtensions.cs | src/AngleSharp/Extensions/EventLoopExtensions.cs | namespace AngleSharp.Extensions
{
using System;
/// <summary>
/// A set of useful extensions for the event loop.
/// </summary>
static class EventLoopExtensions
{
/// <summary>
/// Enqueues another action without considering the cancellation token.
/// </summary>
/// <param name="loop">The loop to extend.</param>
/// <param name="action">The action to enqueue.</param>
/// <param name="priority">The priority of the item.</param>
public static void Enqueue(this IEventLoop loop, Action action, TaskPriority priority = TaskPriority.Normal)
{
if (loop != null)
{
loop.Enqueue(c => action.Invoke(), priority);
}
else
{
action.Invoke();
}
}
}
}
| namespace AngleSharp.Extensions
{
using System;
/// <summary>
/// A set of useful extensions for the event loop.
/// </summary>
static class EventLoopExtensions
{
/// <summary>
/// Enqueues another action without considering the cancellation token.
/// </summary>
/// <param name="loop">The loop to extend.</param>
/// <param name="action">The action to enqueue.</param>
/// <param name="priority">The priority of the item.</param>
public static void Enqueue(this IEventLoop loop, Action action, TaskPriority priority = TaskPriority.Normal)
{
if (loop != null)
{
loop.Enqueue(c => action(), priority);
}
else
{
action.Invoke();
}
}
}
}
| mit | C# |
e7ee3cc771268de13a6d876585299d5d5364eb2e | remove useless attribute | StefanoFiumara/Harry-Potter-Unity | Assets/Scripts/HarryPotterUnity/UI/SubMenuManager.cs | Assets/Scripts/HarryPotterUnity/UI/SubMenuManager.cs | using HarryPotterUnity.UI.Menu;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.UI
{
public class SubMenuManager : MonoBehaviour
{
private BaseMenu _currentMenu;
public void ShowMenu(BaseMenu menu)
{
if (menu.IsOpen)
{
return;
}
_currentMenu = menu;
_currentMenu.IsOpen = true;
}
public void HideMenu()
{
if (_currentMenu == null) return;
_currentMenu.IsOpen = false;
_currentMenu.OnHideMenu();
_currentMenu = null;
}
}
}
| using HarryPotterUnity.UI.Menu;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.UI
{
public class SubMenuManager : MonoBehaviour
{
private BaseMenu _currentMenu;
[UsedImplicitly]
public void ShowMenu(BaseMenu menu)
{
if (menu.IsOpen)
{
return;
}
_currentMenu = menu;
_currentMenu.IsOpen = true;
}
[UsedImplicitly]
public void HideMenu()
{
if (_currentMenu == null) return;
_currentMenu.IsOpen = false;
_currentMenu.OnHideMenu();
_currentMenu = null;
}
}
}
| mit | C# |
4ec026b934a59f9c42fa5029204b670af9366b01 | add comment to GenericSerializationInfo | peopleware/net-ppwcode-util-oddsandends | src/II/Serialization/GenericSerializationInfo.cs | src/II/Serialization/GenericSerializationInfo.cs | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.Serialization;
namespace PPWCode.Util.OddsAndEnds.II.Serialization
{
/// <summary>
/// Class for generic serialization info.
/// </summary>
public class GenericSerializationInfo
{
private readonly SerializationInfo m_SerializationInfo;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="info">The SerializationInfo.</param>
public GenericSerializationInfo(SerializationInfo info)
{
m_SerializationInfo = info;
}
/// <summary>
/// Adds a value into the SerializationInfo store.
/// </summary>
/// <typeparam name="T">The type declaration.</typeparam>
/// <param name="name">The name to associate with the value.</param>
/// <param name="value">The value to be serialized.</param>
public void AddValue<T>(string name, T value)
{
m_SerializationInfo.AddValue(name, value, typeof(T));
}
/// <summary>
/// Retrieves a value from the SerializationInfo store.
/// </summary>
/// <typeparam name="T">The type declaration.</typeparam>
/// <param name="name">The name associated with the value to retrieve.</param>
/// <returns>The object of the specified Type associated with the name.</returns>
public T GetValue<T>(string name)
{
object obj = m_SerializationInfo.GetValue(name, typeof(T));
return (T)obj;
}
}
} | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.Serialization;
namespace PPWCode.Util.OddsAndEnds.II.Serialization
{
/// <summary>
/// Class for generic serialization info.
/// </summary>
public class GenericSerializationInfo
{
private readonly SerializationInfo m_SerializationInfo;
public GenericSerializationInfo(SerializationInfo info)
{
m_SerializationInfo = info;
}
public void AddValue<T>(string name, T value)
{
m_SerializationInfo.AddValue(name, value, typeof(T));
}
public T GetValue<T>(string name)
{
object obj = m_SerializationInfo.GetValue(name, typeof(T));
return (T)obj;
}
}
} | apache-2.0 | C# |
63564ccb5b1946e948e73a4a777b40f84ec0ed38 | 修改 HelloWorldController "Index" action 回傳View Item. | NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie | src/MvcMovie/Controllers/HelloWorldController.cs | src/MvcMovie/Controllers/HelloWorldController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.WebEncoders;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public IActionResult Index()
{
return View();
}
//
// GET: /HelloWorld/Welcome/
public string Welcome(string name, int ID = 1)
{
return HtmlEncoder.Default.HtmlEncode(
"Hello " + name + ", ID: " + ID);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.WebEncoders;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome(string name, int ID = 1)
{
return HtmlEncoder.Default.HtmlEncode(
"Hello " + name + ", ID: " + ID);
}
}
}
| apache-2.0 | C# |
0aeb48a64b24a2910c86d99c7272975d8c50e32e | Update AbpFluentValidationLanguageManager.cs | verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate | src/Abp.FluentValidation/FluentValidation/AbpFluentValidationLanguageManager.cs | src/Abp.FluentValidation/FluentValidation/AbpFluentValidationLanguageManager.cs | using System.Collections.Generic;
using System.Globalization;
using Abp.Extensions;
using Abp.FluentValidation.Configuration;
using Abp.Localization;
using Abp.Localization.Sources;
using LanguageManager = FluentValidation.Resources.LanguageManager;
namespace Abp.FluentValidation
{
public class AbpFluentValidationLanguageManager : LanguageManager
{
public AbpFluentValidationLanguageManager(
ILocalizationManager localizationManager,
ILanguageManager languageManager,
IAbpFluentValidationConfiguration configuration)
{
if (!configuration.LocalizationSourceName.IsNullOrEmpty())
{
var source = localizationManager.GetSource(configuration.LocalizationSourceName);
var languages = languageManager.GetActiveLanguages();
AddAllTranslations(source, languages);
}
}
private void AddAllTranslations(ILocalizationSource source, IReadOnlyList<LanguageInfo> languages)
{
foreach (var language in languages)
{
var culture = new CultureInfo(language.Name);
var translations = source.GetAllStrings(culture, false);
AddTranslations(language.Name, translations);
}
}
private void AddTranslations(string language, IReadOnlyList<LocalizedString> translations)
{
foreach (var translation in translations)
{
AddTranslation(language, translation.Name, translation.Value);
}
}
}
}
| using System.Collections.Generic;
using System.Globalization;
using Abp.Extensions;
using Abp.FluentValidation.Configuration;
using Abp.Localization;
using Abp.Localization.Sources;
using LanguageManager = FluentValidation.Resources.LanguageManager;
namespace Abp.FluentValidation
{
public class AbpFluentValidationLanguageManager : LanguageManager
{
public AbpFluentValidationLanguageManager(
ILocalizationManager localizationManager,
ILanguageManager languageManager,
IAbpFluentValidationConfiguration configuration)
{
if (!configuration.LocalizationSourceName.IsNullOrEmpty())
{
var source = localizationManager.GetSource(configuration.LocalizationSourceName);
var languages = languageManager.GetLanguages();
AddAllTranslations(source, languages);
}
}
private void AddAllTranslations(ILocalizationSource source, IReadOnlyList<LanguageInfo> languages)
{
foreach (var language in languages)
{
var culture = new CultureInfo(language.Name);
var translations = source.GetAllStrings(culture, false);
AddTranslations(language.Name, translations);
}
}
private void AddTranslations(string language, IReadOnlyList<LocalizedString> translations)
{
foreach (var translation in translations)
{
AddTranslation(language, translation.Name, translation.Value);
}
}
}
}
| mit | C# |
d209ba0dd53d25992b1ad530c85912bf14df14b0 | Update AssemblyInfo.cs | fredatgithub/UsefulFunctions | FluentAssertionsUnitTests/Properties/AssemblyInfo.cs | FluentAssertionsUnitTests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("FluentAssertionsUnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Freddy Juhel")]
[assembly: AssemblyProduct("FluentAssertionsUnitTests")]
[assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("cfd4fa8a-cbe2-4f08-b6ce-ed51b93b2dba")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("FluentAssertionsUnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard Company")]
[assembly: AssemblyProduct("FluentAssertionsUnitTests")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("cfd4fa8a-cbe2-4f08-b6ce-ed51b93b2dba")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
95c4b4c94069390e7093f31dcfe6b0ff3a10f9c0 | Kill extra method | khellang/nancy-bootstrapper-prototype | src/Nancy.Core/Scanning/ScanningStrategies.cs | src/Nancy.Core/Scanning/ScanningStrategies.cs | namespace Nancy.Core.Scanning
{
using System;
using System.Reflection;
public static class ScanningStrategies
{
private static readonly Assembly NancyAssembly = typeof(IEngine).GetTypeInfo().Assembly;
public static ScanningStrategy All { get; } = assembly => true;
public static ScanningStrategy OnlyNancy { get; } = assembly => assembly.Equals(NancyAssembly);
public static ScanningStrategy ExcludeNancy { get; } = assembly => !assembly.Equals(NancyAssembly);
}
}
| namespace Nancy.Core.Scanning
{
using System;
using System.Reflection;
public static class ScanningStrategies
{
public static readonly Assembly NancyAssembly = typeof(IEngine).GetTypeInfo().Assembly;
public static ScanningStrategy All { get; } = assembly => true;
public static ScanningStrategy OnlyNancy { get; } = assembly => IsNancy(assembly);
public static ScanningStrategy ExcludeNancy { get; } = assembly => !IsNancy(assembly);
private static bool IsNancy(Assembly assembly)
{
return assembly.Equals(NancyAssembly);
}
}
}
| apache-2.0 | C# |
194384e68bc2e2f82b5c16567de5a47f71495da6 | add SqlConnection explicit cast operator | NServiceKit/NServiceKit.OrmLite,NServiceKit/NServiceKit.OrmLite | src/ServiceStack.OrmLite/OrmLiteConnection.cs | src/ServiceStack.OrmLite/OrmLiteConnection.cs | using System.Data;
using System.Data.SqlClient;
namespace ServiceStack.OrmLite
{
/// <summary>
/// Wrapper IDbConnection class to allow for connection sharing, mocking, etc.
/// </summary>
public class OrmLiteConnection
: IDbConnection
{
private readonly OrmLiteConnectionFactory factory;
private IDbConnection dbConnection;
private bool isOpen;
public OrmLiteConnection(OrmLiteConnectionFactory factory)
{
this.factory = factory;
}
public IDbConnection DbConnection
{
get
{
if (dbConnection == null)
{
dbConnection = factory.ConnectionString.ToDbConnection();
}
return dbConnection;
}
}
public void Dispose()
{
if (!factory.AutoDisposeConnection) return;
DbConnection.Dispose();
dbConnection = null;
isOpen = false;
}
public IDbTransaction BeginTransaction()
{
if (factory.AlwaysReturnTransaction != null)
return factory.AlwaysReturnTransaction;
return DbConnection.BeginTransaction();
}
public IDbTransaction BeginTransaction(IsolationLevel isolationLevel)
{
if (factory.AlwaysReturnTransaction != null)
return factory.AlwaysReturnTransaction;
return DbConnection.BeginTransaction(isolationLevel);
}
public void Close()
{
DbConnection.Close();
}
public void ChangeDatabase(string databaseName)
{
DbConnection.ChangeDatabase(databaseName);
}
public IDbCommand CreateCommand()
{
if (factory.AlwaysReturnCommand != null)
return factory.AlwaysReturnCommand;
return DbConnection.CreateCommand();
}
public void Open()
{
if (isOpen) return;
DbConnection.Open();
isOpen = true;
}
public string ConnectionString
{
get { return factory.ConnectionString; }
set { factory.ConnectionString = value; }
}
public int ConnectionTimeout
{
get { return DbConnection.ConnectionTimeout; }
}
public string Database
{
get { return DbConnection.Database; }
}
public ConnectionState State
{
get { return DbConnection.State; }
}
public static explicit operator SqlConnection(OrmLiteConnection dbConn)
{
return (SqlConnection)dbConn.DbConnection;
}
}
} | using System.Data;
namespace ServiceStack.OrmLite
{
/// <summary>
/// Wrapper IDbConnection class to allow for connection sharing, mocking, etc.
/// </summary>
public class OrmLiteConnection
: IDbConnection
{
private readonly OrmLiteConnectionFactory factory;
private IDbConnection dbConnection;
private bool isOpen;
public OrmLiteConnection(OrmLiteConnectionFactory factory)
{
this.factory = factory;
}
public IDbConnection DbConnection
{
get
{
if (dbConnection == null)
{
dbConnection = factory.ConnectionString.ToDbConnection();
}
return dbConnection;
}
}
public void Dispose()
{
if (!factory.AutoDisposeConnection) return;
DbConnection.Dispose();
dbConnection = null;
isOpen = false;
}
public IDbTransaction BeginTransaction()
{
if (factory.AlwaysReturnTransaction != null)
return factory.AlwaysReturnTransaction;
return DbConnection.BeginTransaction();
}
public IDbTransaction BeginTransaction(IsolationLevel isolationLevel)
{
if (factory.AlwaysReturnTransaction != null)
return factory.AlwaysReturnTransaction;
return DbConnection.BeginTransaction(isolationLevel);
}
public void Close()
{
DbConnection.Close();
}
public void ChangeDatabase(string databaseName)
{
DbConnection.ChangeDatabase(databaseName);
}
public IDbCommand CreateCommand()
{
if (factory.AlwaysReturnCommand != null)
return factory.AlwaysReturnCommand;
return DbConnection.CreateCommand();
}
public void Open()
{
if (isOpen) return;
DbConnection.Open();
isOpen = true;
}
public string ConnectionString
{
get { return factory.ConnectionString; }
set { factory.ConnectionString = value; }
}
public int ConnectionTimeout
{
get { return DbConnection.ConnectionTimeout; }
}
public string Database
{
get { return DbConnection.Database; }
}
public ConnectionState State
{
get { return DbConnection.State; }
}
}
} | bsd-3-clause | C# |
cf3e5f34d8f345b34b969f5718d74980d4fdc04a | Tag DataPoints with the class they were made from | CB17Echo/DroneSafety,CB17Echo/DroneSafety,CB17Echo/DroneSafety | AzureFunctions/Models/DataPoint.csx | AzureFunctions/Models/DataPoint.csx | using Microsoft.Azure.Documents.Spatial;
using System;
public abstract class DataPoint
{
public DateTime Time { get; set; }
public Point Location { get; set; }
public string Type
{
get
{
return GetType().Name;
}
}
}
| using Microsoft.Azure.Documents.Spatial;
using System;
public abstract class DataPoint
{
public DateTime Time { get; set; }
public Point Location { get; set; }
}
| apache-2.0 | C# |
449328a6aedb4fa738ed165cc773546195ca1541 | Add Add method | mtsuker/GitTest1 | ConsoleApp1/ConsoleApp1/Feature1.cs | ConsoleApp1/ConsoleApp1/Feature1.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
public int Add()
{
int x1 = 1;
int x2 = 2;
int sum = x1 + x2;
return sum;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
}
}
| mit | C# |
3a572abb2d6c110edfa8566566cd4a44fcec02b4 | Comment update | noobot/noobot,Workshop2/noobot | src/Noobot.Domain/MessagingPipeline/Request/IncomingMessage.cs | src/Noobot.Domain/MessagingPipeline/Request/IncomingMessage.cs | using Noobot.Domain.MessagingPipeline.Response;
namespace Noobot.Domain.MessagingPipeline.Request
{
public class IncomingMessage
{
/// <summary>
/// The Slack UserId of whoever sent the message
/// </summary>
public string UserId { get; set; }
/// <summary>
/// Username of whoever sent the mssage
/// </summary>
public string Username { get; set; }
/// <summary>
/// The channel used to send a DirectMessage back to the user who sent the message.
/// Note: this might be empty if the Bot hasn't talked to them privately before, but Noobot will join the DM automatically if required.
/// </summary>
public string UserChannel { get; set; }
/// <summary>
/// Contains the untainted raw Text that comes in from Slack. This hasn't been URL decoded
/// </summary>
public string RawText { get; set; }
/// <summary>
/// Contains the URL decoded text from the message.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Contains the text minus any Bot targetting text (e.g. @Noobot: {blah})
/// </summary>
public string TargetedText { get; set; }
/// <summary>
/// The 'channel' the message occured on. This might be a DirectMessage channel.
/// </summary>
public string Channel { get; set; }
/// <summary>
/// Detects if the bot's name is mentioned anywhere in the text
/// </summary>
public bool BotIsMentioned { get; set; }
/// <summary>
/// The Bot's Slack name - this is configurable in Slack
/// </summary>
public string BotName { get; set; }
/// <summary>
/// The Bot's UserId
/// </summary>
public string BotId { get; set; }
/// <summary>
/// Will generate a message to be sent the current channel the message arrived from
/// </summary>
public ResponseMessage ReplyToChannel(string text)
{
return ResponseMessage.ChannelMessage(Channel, text);
}
/// <summary>
/// Will send a DirectMessage reply to the use who sent the message
/// </summary>
public ResponseMessage ReplyDirectlyToUser(string text)
{
return ResponseMessage.DirectUserMessage(UserChannel, UserId, text);
}
}
} | using Noobot.Domain.MessagingPipeline.Response;
namespace Noobot.Domain.MessagingPipeline.Request
{
public class IncomingMessage
{
/// <summary>
/// The Slack UserId of whoever sent the message
/// </summary>
public string UserId { get; set; }
/// <summary>
/// Username of whoever sent the mssage
/// </summary>
public string Username { get; set; }
/// <summary>
/// The channel used to send a DirectMessage back to the user who sent the message.
/// Note: this might be empty if the Bot hasn't talked to them privately before, but Noobot will join the DM automatically if required.
/// </summary>
public string UserChannel { get; set; }
/// <summary>
/// Contains the untainted raw Text that comes in from Slack. This hasn't been URL decoded
/// </summary>
public string RawText { get; set; }
/// <summary>
/// Contains the URL decoded text from the message.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Contains the text minus as Bot targetting text (e.g. @Noobot: {blah})
/// </summary>
public string TargetedText { get; set; }
/// <summary>
/// The 'channel' the message occured on. This might be a DirectMessage channel.
/// </summary>
public string Channel { get; set; }
/// <summary>
/// Detects if the bot's name is mentioned anywhere in the text
/// </summary>
public bool BotIsMentioned { get; set; }
/// <summary>
/// The Bot's Slack name - this is configurable in Slack
/// </summary>
public string BotName { get; set; }
/// <summary>
/// The Bot's UserId
/// </summary>
public string BotId { get; set; }
/// <summary>
/// Will generate a message to be sent the current channel the message arrived from
/// </summary>
public ResponseMessage ReplyToChannel(string text)
{
return ResponseMessage.ChannelMessage(Channel, text);
}
/// <summary>
/// Will send a DirectMessage reply to the use who sent the message
/// </summary>
public ResponseMessage ReplyDirectlyToUser(string text)
{
return ResponseMessage.DirectUserMessage(UserChannel, UserId, text);
}
}
} | mit | C# |
92b766fa0a545141449ce09d832865f33b898c4d | Add GetAll() to org.freedesktop.DBus.Properties interface | Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp | src/DBus.cs | src/DBus.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;
namespace org.freedesktop.DBus
{
[Flags]
public enum NameFlag : uint
{
None = 0,
AllowReplacement = 0x1,
ReplaceExisting = 0x2,
DoNotQueue = 0x4,
}
public enum RequestNameReply : uint
{
PrimaryOwner = 1,
InQueue,
Exists,
AlreadyOwner,
}
public enum ReleaseNameReply : uint
{
Released = 1,
NonExistent,
NotOwner,
}
public enum StartReply : uint
{
//The service was successfully started.
Success = 1,
//A connection already owns the given name.
AlreadyRunning,
}
public delegate void NameOwnerChangedHandler (string name, string old_owner, string new_owner);
public delegate void NameAcquiredHandler (string name);
public delegate void NameLostHandler (string name);
[Interface ("org.freedesktop.DBus.Peer")]
public interface Peer
{
void Ping ();
[return: Argument ("machine_uuid")]
string GetMachineId ();
}
[Interface ("org.freedesktop.DBus.Introspectable")]
public interface Introspectable
{
[return: Argument ("data")]
string Introspect ();
}
[Interface ("org.freedesktop.DBus.Properties")]
public interface Properties
{
[return: Argument ("value")]
object Get (string @interface, string propname);
void Set (string @interface, string propname, object value);
[return: Argument ("props")]
IDictionary<string,object> GetAll(string @interface);
}
[Interface ("org.freedesktop.DBus")]
public interface IBus : Introspectable
{
RequestNameReply RequestName (string name, NameFlag flags);
ReleaseNameReply ReleaseName (string name);
string Hello ();
string[] ListNames ();
string[] ListActivatableNames ();
bool NameHasOwner (string name);
event NameOwnerChangedHandler NameOwnerChanged;
event NameLostHandler NameLost;
event NameAcquiredHandler NameAcquired;
StartReply StartServiceByName (string name, uint flags);
string GetNameOwner (string name);
uint GetConnectionUnixUser (string connection_name);
void AddMatch (string rule);
void RemoveMatch (string rule);
//undocumented in spec
string[] ListQueuedOwners (string name);
uint GetConnectionUnixProcessID (string connection_name);
byte[] GetConnectionSELinuxSecurityContext (string connection_name);
void ReloadConfig ();
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NDesk.DBus;
namespace org.freedesktop.DBus
{
[Flags]
public enum NameFlag : uint
{
None = 0,
AllowReplacement = 0x1,
ReplaceExisting = 0x2,
DoNotQueue = 0x4,
}
public enum RequestNameReply : uint
{
PrimaryOwner = 1,
InQueue,
Exists,
AlreadyOwner,
}
public enum ReleaseNameReply : uint
{
Released = 1,
NonExistent,
NotOwner,
}
public enum StartReply : uint
{
//The service was successfully started.
Success = 1,
//A connection already owns the given name.
AlreadyRunning,
}
public delegate void NameOwnerChangedHandler (string name, string old_owner, string new_owner);
public delegate void NameAcquiredHandler (string name);
public delegate void NameLostHandler (string name);
[Interface ("org.freedesktop.DBus.Peer")]
public interface Peer
{
void Ping ();
[return: Argument ("machine_uuid")]
string GetMachineId ();
}
[Interface ("org.freedesktop.DBus.Introspectable")]
public interface Introspectable
{
[return: Argument ("data")]
string Introspect ();
}
[Interface ("org.freedesktop.DBus.Properties")]
public interface Properties
{
[return: Argument ("value")]
object Get (string @interface, string propname);
void Set (string @interface, string propname, object value);
}
[Interface ("org.freedesktop.DBus")]
public interface IBus : Introspectable
{
RequestNameReply RequestName (string name, NameFlag flags);
ReleaseNameReply ReleaseName (string name);
string Hello ();
string[] ListNames ();
string[] ListActivatableNames ();
bool NameHasOwner (string name);
event NameOwnerChangedHandler NameOwnerChanged;
event NameLostHandler NameLost;
event NameAcquiredHandler NameAcquired;
StartReply StartServiceByName (string name, uint flags);
string GetNameOwner (string name);
uint GetConnectionUnixUser (string connection_name);
void AddMatch (string rule);
void RemoveMatch (string rule);
//undocumented in spec
string[] ListQueuedOwners (string name);
uint GetConnectionUnixProcessID (string connection_name);
byte[] GetConnectionSELinuxSecurityContext (string connection_name);
void ReloadConfig ();
}
}
| mit | C# |
2f55cf5ab7fed58abce5e0accfe16e5814a96add | use system default title in SelectColorDialog, if no title is specified | lytico/xwt,TheBrainTech/xwt,mono/xwt,hwthomas/xwt,directhex/xwt,sevoku/xwt,akrisiun/xwt,antmicro/xwt,hamekoz/xwt,mminns/xwt,mminns/xwt,iainx/xwt,cra0zy/xwt,steffenWi/xwt,residuum/xwt | Xwt.Gtk/Xwt.GtkBackend/SelectColorDialogBackend.cs | Xwt.Gtk/Xwt.GtkBackend/SelectColorDialogBackend.cs | //
// SelectColorDialogBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 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;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public class SelectColorDialogBackend: ISelectColorDialogBackend
{
Gtk.ColorSelectionDialog dlg;
Color color;
string defaultTitle;
public SelectColorDialogBackend ()
{
dlg = new Gtk.ColorSelectionDialog (null);
defaultTitle = dlg.Title;
}
#region ISelectColorDialogBackend implementation
public bool Run (IWindowFrameBackend parent, string title, bool supportsAlpha)
{
if (!String.IsNullOrEmpty (title))
dlg.Title = title;
else
dlg.Title = defaultTitle;
dlg.ColorSelection.HasOpacityControl = supportsAlpha;
dlg.ColorSelection.CurrentColor = color.ToGtkValue ();
if (supportsAlpha)
dlg.ColorSelection.CurrentAlpha = (ushort) (((double)ushort.MaxValue) * color.Alpha);
var p = (WindowFrameBackend) parent;
int result = MessageService.RunCustomDialog (dlg, p != null ? p.Window : null);
if (result == (int) Gtk.ResponseType.Ok) {
color = dlg.ColorSelection.CurrentColor.ToXwtValue ();
if (supportsAlpha)
color = color.WithAlpha ((double)dlg.ColorSelection.CurrentAlpha / (double)ushort.MaxValue);
return true;
}
else
return false;
}
public void Dispose ()
{
dlg.Destroy ();
}
public Color Color {
get {
return color;
}
set {
color = value;
}
}
#endregion
}
}
| //
// SelectColorDialogBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 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;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public class SelectColorDialogBackend: ISelectColorDialogBackend
{
Gtk.ColorSelectionDialog dlg;
Color color;
public SelectColorDialogBackend ()
{
dlg = new Gtk.ColorSelectionDialog ("");
}
#region ISelectColorDialogBackend implementation
public bool Run (IWindowFrameBackend parent, string title, bool supportsAlpha)
{
dlg.Title = title;
dlg.ColorSelection.HasOpacityControl = supportsAlpha;
dlg.ColorSelection.CurrentColor = color.ToGtkValue ();
if (supportsAlpha)
dlg.ColorSelection.CurrentAlpha = (ushort) (((double)ushort.MaxValue) * color.Alpha);
var p = (WindowFrameBackend) parent;
int result = MessageService.RunCustomDialog (dlg, p != null ? p.Window : null);
if (result == (int) Gtk.ResponseType.Ok) {
color = dlg.ColorSelection.CurrentColor.ToXwtValue ();
if (supportsAlpha)
color = color.WithAlpha ((double)dlg.ColorSelection.CurrentAlpha / (double)ushort.MaxValue);
return true;
}
else
return false;
}
public void Dispose ()
{
dlg.Destroy ();
}
public Color Color {
get {
return color;
}
set {
color = value;
}
}
#endregion
}
}
| mit | C# |
549ceb7c15c85d29699e31f17d3622a7262dfbff | Load only if the file given exists | Torrunt/vimage | vimage/Source/Program.cs | vimage/Source/Program.cs | // vimage - http://torrunt.net/vimage
// Corey Zeke Womack (Torrunt) - me@torrunt.net
using System;
namespace vimage
{
class Program
{
static void Main(string[] args)
{
string file;
if (args.Length == 0)
return;
else
file = args[0];
if (System.IO.File.Exists(file))
{
ImageViewer imageViewer = new ImageViewer(file);
}
}
}
}
| // vimage - http://torrunt.net/vimage
// Corey Zeke Womack (Torrunt) - me@torrunt.net
using System;
namespace vimage
{
class Program
{
static void Main(string[] args)
{
string file;
if (args.Length == 0)
{
#if DEBUG
//file = @"C:\Users\Corey\Pictures\Test Images\Beaver_Transparent.png";
//file = @"C:\Users\Corey\Pictures\Test Images\AdventureTime_TransparentAnimation.gif";
//file = @"C:\Users\Corey\Pictures\Test Images\AnimatedGif.gif";
file = @"G:\Misc\Desktop Backgrounds\0diHF.jpg";
#else
return;
#endif
}
else
file = args[0];
ImageViewer ImageViewer = new ImageViewer(file);
}
}
}
| mit | C# |
ed7388f3cc36d3a7a66212ababe183d45434ed23 | fix IsoCode doc link in Subdivision.cs | maxmind/GeoIP2-dotnet | MaxMind.GeoIP2/Model/Subdivision.cs | MaxMind.GeoIP2/Model/Subdivision.cs | #region
using MaxMind.Db;
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace MaxMind.GeoIP2.Model
{
/// <summary>
/// Contains data for the subdivisions associated with an IP address.
/// Do not use any of the subdivision names as a database or dictionary
/// key. Use the <see cred="GeoNameId" /> or <see cred="IsoCode" />
/// instead.
/// </summary>
public class Subdivision : NamedEntity
{
/// <summary>
/// Constructor
/// </summary>
public Subdivision()
{
}
/// <summary>
/// Constructor
/// </summary>
[Constructor]
public Subdivision(
int? confidence = null,
[Parameter("geoname_id")] long? geoNameId = null,
[Parameter("iso_code")] string? isoCode = null,
IReadOnlyDictionary<string, string>? names = null,
IReadOnlyList<string>? locales = null)
: base(geoNameId, names, locales)
{
Confidence = confidence;
IsoCode = isoCode;
}
/// <summary>
/// This is a value from 0-100 indicating MaxMind's confidence that
/// the subdivision is correct. This value is only set when using the
/// Insights web service or the Enterprise database.
/// </summary>
[JsonInclude]
[JsonPropertyName("confidence")]
public int? Confidence { get; internal set; }
/// <summary>
/// This is a string up to three characters long contain the
/// subdivision portion of the
/// <a
/// href="http://en.wikipedia.org/wiki/ISO_3166-2">
/// ISO 3166-2 code
/// </a>
/// .
/// </summary>
[JsonInclude]
[JsonPropertyName("iso_code")]
public string? IsoCode { get; internal set; }
}
}
| #region
using MaxMind.Db;
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace MaxMind.GeoIP2.Model
{
/// <summary>
/// Contains data for the subdivisions associated with an IP address.
/// Do not use any of the subdivision names as a database or dictionary
/// key. Use the <see cred="GeoNameId" /> or <see cred="IsoCode" />
/// instead.
/// </summary>
public class Subdivision : NamedEntity
{
/// <summary>
/// Constructor
/// </summary>
public Subdivision()
{
}
/// <summary>
/// Constructor
/// </summary>
[Constructor]
public Subdivision(
int? confidence = null,
[Parameter("geoname_id")] long? geoNameId = null,
[Parameter("iso_code")] string? isoCode = null,
IReadOnlyDictionary<string, string>? names = null,
IReadOnlyList<string>? locales = null)
: base(geoNameId, names, locales)
{
Confidence = confidence;
IsoCode = isoCode;
}
/// <summary>
/// This is a value from 0-100 indicating MaxMind's confidence that
/// the subdivision is correct. This value is only set when using the
/// Insights web service or the Enterprise database.
/// </summary>
[JsonInclude]
[JsonPropertyName("confidence")]
public int? Confidence { get; internal set; }
/// <summary>
/// This is a string up to three characters long contain the
/// subdivision portion of the
/// <a
/// href="http://en.wikipedia.org/wiki/ISO_3166-2 ISO 3166-2">
/// code
/// </a>
/// .
/// </summary>
[JsonInclude]
[JsonPropertyName("iso_code")]
public string? IsoCode { get; internal set; }
}
} | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.